diff --git a/testbed/dpkp__kafka-python/.covrc b/testbed/dpkp__kafka-python/.covrc new file mode 100644 index 0000000000000000000000000000000000000000..43c5fd7afe6ae11ab033a4eff10c6a2e2d4b52a7 --- /dev/null +++ b/testbed/dpkp__kafka-python/.covrc @@ -0,0 +1,3 @@ +[run] +omit = + kafka/vendor/* diff --git a/testbed/dpkp__kafka-python/.gitignore b/testbed/dpkp__kafka-python/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f3cd082fa2f318fc3553481da6f07292c5a8bd5a --- /dev/null +++ b/testbed/dpkp__kafka-python/.gitignore @@ -0,0 +1,17 @@ +*.egg-info +*.pyc +.tox +build +dist +MANIFEST +env +servers/*/kafka-bin* +servers/*/resources/ssl* +.coverage* +.noseids +docs/_build +.cache* +.idea/ +integration-test/ +tests-env/ +.pytest_cache/ diff --git a/testbed/dpkp__kafka-python/.travis.yml b/testbed/dpkp__kafka-python/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..21e51f5ed27732516d3545aae70d90c4e8ed643c --- /dev/null +++ b/testbed/dpkp__kafka-python/.travis.yml @@ -0,0 +1,46 @@ +language: python + +dist: xenial + +python: + - 2.7 + - 3.4 + - 3.7 + - 3.8 + - pypy2.7-6.0 + +env: + - KAFKA_VERSION=0.8.2.2 + - KAFKA_VERSION=0.9.0.1 + - KAFKA_VERSION=0.10.2.2 + - KAFKA_VERSION=0.11.0.3 + - KAFKA_VERSION=1.1.1 + - KAFKA_VERSION=2.4.0 + - KAFKA_VERSION=2.5.0 + - KAFKA_VERSION=2.6.0 + +addons: + apt: + packages: + - libsnappy-dev + - libzstd-dev + - openjdk-8-jdk + +cache: + directories: + - $HOME/.cache/pip + - servers/dist + +before_install: + - source travis_java_install.sh + - ./build_integration.sh + +install: + - pip install tox coveralls + - pip install . + +script: + - tox -e `if [ "$TRAVIS_PYTHON_VERSION" == "pypy2.7-6.0" ]; then echo pypy; else echo py${TRAVIS_PYTHON_VERSION/./}; fi` + +after_success: + - coveralls diff --git a/testbed/dpkp__kafka-python/AUTHORS.md b/testbed/dpkp__kafka-python/AUTHORS.md new file mode 100644 index 0000000000000000000000000000000000000000..7d44efd6eb35cf76d570d5a52ba336610fb17dfe --- /dev/null +++ b/testbed/dpkp__kafka-python/AUTHORS.md @@ -0,0 +1,51 @@ +# Current Maintainer +* Dana Powers, [@dpkp](https://github.com/dpkp) + +# Original Author and First Commit +* David Arthur, [@mumrah](https://github.com/mumrah) + +# Contributors - 2015 (alpha by username) +* Alex Couture-Beil, [@alexcb](https://github.com/alexcb) +* Ali-Akber Saifee, [@alisaifee](https://github.com/alisaifee) +* Christophe-Marie Duquesne, [@chmduquesne](https://github.com/chmduquesne) +* Thomas Dimson, [@cosbynator](https://github.com/cosbynator) +* Kasper Jacobsen, [@Dinoshauer](https://github.com/Dinoshauer) +* Ross Duggan, [@duggan](https://github.com/duggan) +* Enrico Canzonieri, [@ecanzonieri](https://github.com/ecanzonieri) +* haosdent, [@haosdent](https://github.com/haosdent) +* Arturo Filastò, [@hellais](https://github.com/hellais) +* Job Evers‐Meltzer, [@jobevers](https://github.com/jobevers) +* Martin Olveyra, [@kalessin](https://github.com/kalessin) +* Kubilay Kocak, [@koobs](https://github.com/koobs) +* Matthew L Daniel +* Eric Hewitt, [@meandthewallaby](https://github.com/meandthewallaby) +* Oliver Jowett [@mutability](https://github.com/mutability) +* Shaolei Zhou, [@reAsOn2010](https://github.com/reAsOn2010) +* Oskari Saarenmaa, [@saaros](https://github.com/saaros) +* John Anderson, [@sontek](https://github.com/sontek) +* Eduard Iskandarov, [@toidi](https://github.com/toidi) +* Todd Palino, [@toddpalino](https://github.com/toddpalino) +* trbs, [@trbs](https://github.com/trbs) +* Viktor Shlapakov, [@vshlapakov](https://github.com/vshlapakov) +* Will Daly, [@wedaly](https://github.com/wedaly) +* Warren Kiser, [@wkiser](https://github.com/wkiser) +* William Ting, [@wting](https://github.com/wting) +* Zack Dever, [@zackdever](https://github.com/zackdever) + +# More Contributors +* Bruno Renié, [@brutasse](https://github.com/brutasse) +* Thomas Dimson, [@cosbynator](https://github.com/cosbynator) +* Jesse Myers, [@jessemyers](https://github.com/jessemyers) +* Mahendra M, [@mahendra](https://github.com/mahendra) +* Miguel Eduardo Gil Biraud, [@mgilbir](https://github.com/mgilbir) +* Marc Labbé, [@mrtheb](https://github.com/mrtheb) +* Patrick Lucas, [@patricklucas](https://github.com/patricklucas) +* Omar Ghishan, [@rdiomar](https://github.com/rdiomar) - RIP, Omar. 2014 +* Ivan Pouzyrevsky, [@sandello](https://github.com/sandello) +* Lou Marvin Caraig, [@se7entyse7en](https://github.com/se7entyse7en) +* waliaashish85, [@waliaashish85](https://github.com/waliaashish85) +* Mark Roberts, [@wizzat](https://github.com/wizzat) +* Christophe Lecointe [@christophelec](https://github.com/christophelec) +* Mohamed Helmi Hichri [@hellich](https://github.com/hellich) + +Thanks to all who have contributed! diff --git a/testbed/dpkp__kafka-python/CHANGES.md b/testbed/dpkp__kafka-python/CHANGES.md new file mode 100644 index 0000000000000000000000000000000000000000..097c55db64e81990b06218d5d1466e5a4aeefb44 --- /dev/null +++ b/testbed/dpkp__kafka-python/CHANGES.md @@ -0,0 +1,1204 @@ +# 2.0.2 (Sep 29, 2020) + +Consumer +* KIP-54: Implement sticky partition assignment strategy (aynroot / PR #2057) +* Fix consumer deadlock when heartbeat thread request timeout (huangcuiyang / PR #2064) + +Compatibility +* Python 3.8 support (Photonios / PR #2088) + +Cleanups +* Bump dev requirements (jeffwidman / PR #2129) +* Fix crc32c deprecation warning (crc32c==2.1) (jeffwidman / PR #2128) +* Lint cleanup (jeffwidman / PR #2126) +* Fix initialization order in KafkaClient (pecalleja / PR #2119) +* Allow installing crc32c via extras (mishas / PR #2069) +* Remove unused imports (jameslamb / PR #2046) + +Admin Client +* Merge _find_coordinator_id methods (jeffwidman / PR #2127) +* Feature: delete consumergroups (swenzel / PR #2040) +* Allow configurable timeouts in admin client check version (sunnyakaxd / PR #2107) +* Enhancement for Kafka Admin Client's "Describe Consumer Group" (Apurva007 / PR #2035) + +Protocol +* Add support for zstd compression (gabriel-tincu / PR #2021) +* Add protocol support for brokers 1.1.0 - 2.5.0 (gabriel-tincu / PR #2038) +* Add ProduceRequest/ProduceResponse v6/v7/v8 (gabriel-tincu / PR #2020) +* Fix parsing NULL header values (kvfi / PR #2024) + +Tests +* Add 2.5.0 to automated CI tests (gabriel-tincu / PR #2038) +* Add 2.1.1 to build_integration (gabriel-tincu / PR #2019) + +Documentation / Logging / Errors +* Disable logging during producer object gc (gioele / PR #2043) +* Update example.py; use threading instead of multiprocessing (Mostafa-Elmenbawy / PR #2081) +* Fix typo in exception message (haracejacob / PR #2096) +* Add kafka.structs docstrings (Mostafa-Elmenbawy / PR #2080) +* Fix broken compatibility page link (anuragrana / PR #2045) +* Rename README to README.md (qhzxc0015 / PR #2055) +* Fix docs by adding SASL mention (jeffwidman / #1990) + +# 2.0.1 (Feb 19, 2020) + +Admin Client +* KAFKA-8962: Use least_loaded_node() for AdminClient.describe_topics() (jeffwidman / PR #2000) +* Fix AdminClient topic error parsing in MetadataResponse (jtribble / PR #1997) + +# 2.0.0 (Feb 10, 2020) + +This release includes breaking changes for any application code that has not +migrated from older Simple-style classes to newer Kafka-style classes. + +Deprecation +* Remove deprecated SimpleClient, Producer, Consumer, Unittest (jeffwidman / PR #1196) + +Admin Client +* Use the controller for topic metadata requests (TylerLubeck / PR #1995) +* Implement list_topics, describe_topics, and describe_cluster (TylerLubeck / PR #1993) +* Implement __eq__ and __hash__ for ACL objects (TylerLubeck / PR #1955) +* Fixes KafkaAdminClient returning `IncompatibleBrokerVersion` when passing an `api_version` (ian28223 / PR #1953) +* Admin protocol updates (TylerLubeck / PR #1948) +* Fix describe config for multi-broker clusters (jlandersen / PR #1869) + +Miscellaneous Bugfixes / Improvements +* Enable SCRAM-SHA-256 and SCRAM-SHA-512 for sasl (swenzel / PR #1918) +* Fix slots usage and use more slots (carsonip / PR #1987) +* Optionally return OffsetAndMetadata from consumer.committed(tp) (dpkp / PR #1979) +* Reset conn configs on exception in conn.check_version() (dpkp / PR #1977) +* Do not block on sender thread join after timeout in producer.close() (dpkp / PR #1974) +* Implement methods to convert a Struct object to a pythonic object (TylerLubeck / PR #1951) + +Test Infrastructure / Documentation / Maintenance +* Update 2.4.0 resource files for sasl integration (dpkp) +* Add kafka 2.4.0 to CI testing (vvuibert / PR #1972) +* convert test_admin_integration to pytest (ulrikjohansson / PR #1923) +* xfail test_describe_configs_topic_resource_returns_configs (dpkp / Issue #1929) +* Add crc32c to README and docs (dpkp) +* Improve docs for reconnect_backoff_max_ms (dpkp / PR #1976) +* Fix simple typo: managementment -> management (timgates42 / PR #1966) +* Fix typos (carsonip / PR #1938) +* Fix doc import paths (jeffwidman / PR #1933) +* Update docstring to match conn.py's (dabcoder / PR #1921) +* Do not log topic-specific errors in full metadata fetch (dpkp / PR #1980) +* Raise AssertionError if consumer closed in poll() (dpkp / PR #1978) +* Log retriable coordinator NodeNotReady, TooManyInFlightRequests as debug not error (dpkp / PR #1975) +* Remove unused import (jeffwidman) +* Remove some dead code (jeffwidman) +* Fix a benchmark to Use print() function in both Python 2 and Python 3 (cclauss / PR #1983) +* Fix a test to use ==/!= to compare str, bytes, and int literals (cclauss / PR #1984) +* Fix benchmarks to use pyperf (carsonip / PR #1986) +* Remove unused/empty .gitsubmodules file (jeffwidman / PR #1928) +* Remove deprecated `ConnectionError` (jeffwidman / PR #1816) + + +# 1.4.7 (Sep 30, 2019) + +This is a minor release focused on KafkaConsumer performance, Admin Client +improvements, and Client concurrency. The KafkaConsumer iterator implementation +has been greatly simplified so that it just wraps consumer.poll(). The prior +implementation will remain available for a few more releases using the optional +KafkaConsumer config: `legacy_iterator=True` . This is expected to improve +consumer throughput substantially and help reduce heartbeat failures / group +rebalancing. + +Client +* Send socket data via non-blocking IO with send buffer (dpkp / PR #1912) +* Rely on socket selector to detect completed connection attempts (dpkp / PR #1909) +* Improve connection lock handling; always use context manager (melor,dpkp / PR #1895) +* Reduce client poll timeout when there are no in-flight requests (dpkp / PR #1823) + +KafkaConsumer +* Do not use wakeup when sending fetch requests from consumer (dpkp / PR #1911) +* Wrap `consumer.poll()` for KafkaConsumer iteration (dpkp / PR #1902) +* Allow the coordinator to auto-commit on old brokers (justecorruptio / PR #1832) +* Reduce internal client poll timeout for (legacy) consumer iterator interface (dpkp / PR #1824) +* Use dedicated connection for group coordinator (dpkp / PR #1822) +* Change coordinator lock acquisition order (dpkp / PR #1821) +* Make `partitions_for_topic` a read-through cache (Baisang / PR #1781,#1809) +* Fix consumer hanging indefinitely on topic deletion while rebalancing (commanderdishwasher / PR #1782) + +Miscellaneous Bugfixes / Improvements +* Fix crc32c avilability on non-intel architectures (ossdev07 / PR #1904) +* Load system default SSL CAs if `ssl_cafile` is not provided (iAnomaly / PR #1883) +* Catch py3 TimeoutError in BrokerConnection send/recv (dpkp / PR #1820) +* Added a function to determine if bootstrap is successfully connected (Wayde2014 / PR #1876) + +Admin Client +* Add ACL api support to KafkaAdminClient (ulrikjohansson / PR #1833) +* Add `sasl_kerberos_domain_name` config to KafkaAdminClient (jeffwidman / PR #1852) +* Update `security_protocol` config documentation for KafkaAdminClient (cardy31 / PR #1849) +* Break FindCoordinator into request/response methods in KafkaAdminClient (jeffwidman / PR #1871) +* Break consumer operations into request / response methods in KafkaAdminClient (jeffwidman / PR #1845) +* Parallelize calls to `_send_request_to_node()` in KafkaAdminClient (davidheitman / PR #1807) + +Test Infrastructure / Documentation / Maintenance +* Add Kafka 2.3.0 to test matrix and compatibility docs (dpkp / PR #1915) +* Convert remaining `KafkaConsumer` tests to `pytest` (jeffwidman / PR #1886) +* Bump integration tests to 0.10.2.2 and 0.11.0.3 (jeffwidman / #1890) +* Cleanup handling of `KAFKA_VERSION` env var in tests (jeffwidman / PR #1887) +* Minor test cleanup (jeffwidman / PR #1885) +* Use `socket.SOCK_STREAM` in test assertions (iv-m / PR #1879) +* Sanity test for `consumer.topics()` and `consumer.partitions_for_topic()` (Baisang / PR #1829) +* Cleanup seconds conversion in client poll timeout calculation (jeffwidman / PR #1825) +* Remove unused imports (jeffwidman / PR #1808) +* Cleanup python nits in RangePartitionAssignor (jeffwidman / PR #1805) +* Update links to kafka consumer config docs (jeffwidman) +* Fix minor documentation typos (carsonip / PR #1865) +* Remove unused/weird comment line (jeffwidman / PR #1813) +* Update docs for `api_version_auto_timeout_ms` (jeffwidman / PR #1812) + + +# 1.4.6 (Apr 2, 2019) + +This is a patch release primarily focused on bugs related to concurrency, +SSL connections and testing, and SASL authentication: + +Client Concurrency Issues (Race Conditions / Deadlocks) +* Fix race condition in `protocol.send_bytes` (isamaru / PR #1752) +* Do not call `state_change_callback` with lock (dpkp / PR #1775) +* Additional BrokerConnection locks to synchronize protocol/IFR state (dpkp / PR #1768) +* Send pending requests before waiting for responses (dpkp / PR #1762) +* Avoid race condition on `client._conns` in send() (dpkp / PR #1772) +* Hold lock during `client.check_version` (dpkp / PR #1771) + +Producer Wakeup / TimeoutError +* Dont wakeup during `maybe_refresh_metadata` -- it is only called by poll() (dpkp / PR #1769) +* Dont do client wakeup when sending from sender thread (dpkp / PR #1761) + +SSL - Python3.7 Support / Bootstrap Hostname Verification / Testing +* Wrap SSL sockets after connecting for python3.7 compatibility (dpkp / PR #1754) +* Allow configuration of SSL Ciphers (dpkp / PR #1755) +* Maintain shadow cluster metadata for bootstrapping (dpkp / PR #1753) +* Generate SSL certificates for local testing (dpkp / PR #1756) +* Rename ssl.keystore.location and ssl.truststore.location config files (dpkp) +* Reset reconnect backoff on SSL connection (dpkp / PR #1777) + +SASL - OAuthBearer support / api version bugfix +* Fix 0.8.2 protocol quick detection / fix SASL version check (dpkp / PR #1763) +* Update sasl configuration docstrings to include supported mechanisms (dpkp) +* Support SASL OAuthBearer Authentication (pt2pham / PR #1750) + +Miscellaneous Bugfixes +* Dont force metadata refresh when closing unneeded bootstrap connections (dpkp / PR #1773) +* Fix possible AttributeError during conn._close_socket (dpkp / PR #1776) +* Return connection state explicitly after close in connect() (dpkp / PR #1778) +* Fix flaky conn tests that use time.time (dpkp / PR #1758) +* Add py to requirements-dev (dpkp) +* Fixups to benchmark scripts for py3 / new KafkaFixture interface (dpkp) + + +# 1.4.5 (Mar 14, 2019) + +This release is primarily focused on addressing lock contention +and other coordination issues between the KafkaConsumer and the +background heartbeat thread that was introduced in the 1.4 release. + +Consumer +* connections_max_idle_ms must be larger than request_timeout_ms (jeffwidman / PR #1688) +* Avoid race condition during close() / join heartbeat thread (dpkp / PR #1735) +* Use last offset from fetch v4 if available to avoid getting stuck in compacted topic (keithks / PR #1724) +* Synchronize puts to KafkaConsumer protocol buffer during async sends (dpkp / PR #1733) +* Improve KafkaConsumer join group / only enable Heartbeat Thread during stable group (dpkp / PR #1695) +* Remove unused `skip_double_compressed_messages` (jeffwidman / PR #1677) +* Fix commit_offsets_async() callback (Faqa / PR #1712) + +Client +* Retry bootstrapping after backoff when necessary (dpkp / PR #1736) +* Recheck connecting nodes sooner when refreshing metadata (dpkp / PR #1737) +* Avoid probing broker versions twice on newer brokers (dpkp / PR #1738) +* Move all network connections and writes to KafkaClient.poll() (dpkp / PR #1729) +* Do not require client lock for read-only operations (dpkp / PR #1730) +* Timeout all unconnected conns (incl SSL) after request_timeout_ms (dpkp / PR #1696) + +Admin Client +* Fix AttributeError in response topic error codes checking (jeffwidman) +* Fix response error checking in KafkaAdminClient send_to_controller (jeffwidman) +* Fix NotControllerError check (jeffwidman) + +Core/Protocol +* Fix default protocol parser version / 0.8.2 version probe (dpkp / PR #1740) +* Make NotEnoughReplicasError/NotEnoughReplicasAfterAppendError retriable (le-linh / PR #1722) + +Bugfixes +* Use copy() in metrics() to avoid thread safety issues (emeric254 / PR #1682) + +Test Infrastructure +* Mock dns lookups in test_conn (dpkp / PR #1739) +* Use test.fixtures.version not test.conftest.version to avoid warnings (dpkp / PR #1731) +* Fix test_legacy_correct_metadata_response on x86 arch (stanislavlevin / PR #1718) +* Travis CI: 'sudo' tag is now deprecated in Travis (cclauss / PR #1698) +* Use Popen.communicate() instead of Popen.wait() (Baisang / PR #1689) + +Compatibility +* Catch thrown OSError by python 3.7 when creating a connection (danjo133 / PR #1694) +* Update travis test coverage: 2.7, 3.4, 3.7, pypy2.7 (jeffwidman, dpkp / PR #1614) +* Drop dependency on sphinxcontrib-napoleon (stanislavlevin / PR #1715) +* Remove unused import from kafka/producer/record_accumulator.py (jeffwidman / PR #1705) +* Fix SSL connection testing in Python 3.7 (seanthegeek, silentben / PR #1669) + + +# 1.4.4 (Nov 20, 2018) + +Bugfixes +* (Attempt to) Fix deadlock between consumer and heartbeat (zhgjun / dpkp #1628) +* Fix Metrics dict memory leak (kishorenc #1569) + +Client +* Support Kafka record headers (hnousiainen #1574) +* Set socket timeout for the write-side of wake socketpair (Fleurer #1577) +* Add kerberos domain name config for gssapi sasl mechanism handshake (the-sea #1542) +* Support smaller topic metadata fetch during bootstrap (andyxning #1541) +* Use TypeError for invalid timeout type (jeffwidman #1636) +* Break poll if closed (dpkp) + +Admin Client +* Add KafkaAdminClient class (llamahunter #1540) +* Fix list_consumer_groups() to query all brokers (jeffwidman #1635) +* Stop using broker-errors for client-side problems (jeffwidman #1639) +* Fix send to controller (jeffwidman #1640) +* Add group coordinator lookup (jeffwidman #1641) +* Fix describe_groups (jeffwidman #1642) +* Add list_consumer_group_offsets() (jeffwidman #1643) +* Remove support for api versions as strings from KafkaAdminClient (jeffwidman #1644) +* Set a clear default value for `validate_only`/`include_synonyms` (jeffwidman #1645) +* Bugfix: Always set this_groups_coordinator_id (jeffwidman #1650) + +Consumer +* Fix linter warning on import of ConsumerRebalanceListener (ben-harack #1591) +* Remove ConsumerTimeout (emord #1587) +* Return future from commit_offsets_async() (ekimekim #1560) + +Core / Protocol +* Add protocol structs for {Describe,Create,Delete} Acls (ulrikjohansson #1646/partial) +* Pre-compile pack/unpack function calls (billyevans / jeffwidman #1619) +* Don't use `kafka.common` internally (jeffwidman #1509) +* Be explicit with tuples for %s formatting (jeffwidman #1634) + +Documentation +* Document connections_max_idle_ms (jeffwidman #1531) +* Fix sphinx url (jeffwidman #1610) +* Update remote urls: snappy, https, etc (jeffwidman #1603) +* Minor cleanup of testing doc (jeffwidman #1613) +* Various docstring / pep8 / code hygiene cleanups (jeffwidman #1647) + +Test Infrastructure +* Stop pinning `pylint` (jeffwidman #1611) +* (partial) Migrate from `Unittest` to `pytest` (jeffwidman #1620) +* Minor aesthetic cleanup of partitioner tests (jeffwidman #1618) +* Cleanup fixture imports (jeffwidman #1616) +* Fix typo in test file name (jeffwidman) +* Remove unused ivy_root variable (jeffwidman) +* Add test fixtures for kafka versions 1.0.2 -> 2.0.1 (dpkp) +* Bump travis test for 1.x brokers to 1.1.1 (dpkp) + +Logging / Error Messages +* raising logging level on messages signalling data loss (sibiryakov #1553) +* Stop using deprecated log.warn() (jeffwidman #1615) +* Fix typo in logging message (jeffwidman) + +Compatibility +* Vendor enum34 (jeffwidman #1604) +* Bump vendored `six` to `1.11.0` (jeffwidman #1602) +* Vendor `six` consistently (jeffwidman #1605) +* Prevent `pylint` import errors on `six.moves` (jeffwidman #1609) + + +# 1.4.3 (May 26, 2018) + +Compatibility +* Fix for python 3.7 support: remove 'async' keyword from SimpleProducer (dpkp #1454) + +Client +* Improve BrokerConnection initialization time (romulorosa #1475) +* Ignore MetadataResponses with empty broker list (dpkp #1506) +* Improve connection handling when bootstrap list is invalid (dpkp #1507) + +Consumer +* Check for immediate failure when looking up coordinator in heartbeat thread (dpkp #1457) + +Core / Protocol +* Always acquire client lock before coordinator lock to avoid deadlocks (dpkp #1464) +* Added AlterConfigs and DescribeConfigs apis (StephenSorriaux #1472) +* Fix CreatePartitionsRequest_v0 (StephenSorriaux #1469) +* Add codec validators to record parser and builder for all formats (tvoinarovskyi #1447) +* Fix MemoryRecord bugs re error handling and add test coverage (tvoinarovskyi #1448) +* Force lz4 to disable Kafka-unsupported block linking when encoding (mnito #1476) +* Stop shadowing `ConnectionError` (jeffwidman #1492) + +Documentation +* Document methods that return None (jeffwidman #1504) +* Minor doc capitalization cleanup (jeffwidman) +* Adds add_callback/add_errback example to docs (Berkodev #1441) +* Fix KafkaConsumer docstring for request_timeout_ms default (dpkp #1459) + +Test Infrastructure +* Skip flakey SimpleProducer test (dpkp) +* Fix skipped integration tests if KAFKA_VERSION unset (dpkp #1453) + +Logging / Error Messages +* Stop using deprecated log.warn() (jeffwidman) +* Change levels for some heartbeat thread logging (dpkp #1456) +* Log Heartbeat thread start / close for debugging (dpkp) + + +# 1.4.2 (Mar 10, 2018) + +Bugfixes +* Close leaked selector in version check (dpkp #1425) +* Fix `BrokerConnection.connection_delay()` to return milliseconds (dpkp #1414) +* Use local copies in `Fetcher._fetchable_partitions` to avoid mutation errors (dpkp #1400) +* Fix error var name in `_unpack` (j2gg0s #1403) +* Fix KafkaConsumer compacted offset handling (dpkp #1397) +* Fix byte size estimation with kafka producer (blakeembrey #1393) +* Fix coordinator timeout in consumer poll interface (braedon #1384) + +Client +* Add `BrokerConnection.connect_blocking()` to improve bootstrap to multi-address hostnames (dpkp #1411) +* Short-circuit `BrokerConnection.close()` if already disconnected (dpkp #1424) +* Only increase reconnect backoff if all addrinfos have been tried (dpkp #1423) +* Make BrokerConnection .host / .port / .afi immutable to avoid incorrect 'metadata changed' checks (dpkp #1422) +* Connect with sockaddrs to support non-zero ipv6 scope ids (dpkp #1433) +* Check timeout type in KafkaClient constructor (asdaraujo #1293) +* Update string representation of SimpleClient (asdaraujo #1293) +* Do not validate `api_version` against known versions (dpkp #1434) + +Consumer +* Avoid tight poll loop in consumer when brokers are down (dpkp #1415) +* Validate `max_records` in KafkaConsumer.poll (dpkp #1398) +* KAFKA-5512: Awake heartbeat thread when it is time to poll (dpkp #1439) + +Producer +* Validate that serializers generate bytes-like (or None) data (dpkp #1420) + +Core / Protocol +* Support alternative lz4 package: lz4framed (everpcpc #1395) +* Use hardware accelerated CRC32C function if available (tvoinarovskyi #1389) +* Add Admin CreatePartitions API call (alexef #1386) + +Test Infrastructure +* Close KafkaConsumer instances during tests (dpkp #1410) +* Introduce new fixtures to prepare for migration to pytest (asdaraujo #1293) +* Removed pytest-catchlog dependency (asdaraujo #1380) +* Fixes racing condition when message is sent to broker before topic logs are created (asdaraujo #1293) +* Add kafka 1.0.1 release to test fixtures (dpkp #1437) + +Logging / Error Messages +* Re-enable logging during broker version check (dpkp #1430) +* Connection logging cleanups (dpkp #1432) +* Remove old CommitFailed error message from coordinator (dpkp #1436) + + +# 1.4.1 (Feb 9, 2018) + +Bugfixes +* Fix consumer poll stuck error when no available partition (ckyoog #1375) +* Increase some integration test timeouts (dpkp #1374) +* Use raw in case string overriden (jeffwidman #1373) +* Fix pending completion IndexError bug caused by multiple threads (dpkp #1372) + + +# 1.4.0 (Feb 6, 2018) + +This is a substantial release. Although there are no known 'showstopper' bugs as of release, +we do recommend you test any planned upgrade to your application prior to running in production. + +Some of the major changes include: +* We have officially dropped python 2.6 support +* The KafkaConsumer now includes a background thread to handle coordinator heartbeats +* API protocol handling has been separated from networking code into a new class, KafkaProtocol +* Added support for kafka message format v2 +* Refactored DNS lookups during kafka broker connections +* SASL authentication is working (we think) +* Removed several circular references to improve gc on close() + +Thanks to all contributors -- the state of the kafka-python community is strong! + +Detailed changelog are listed below: + +Client +* Fixes for SASL support + * Refactor SASL/gssapi support (dpkp #1248 #1249 #1257 #1262 #1280) + * Add security layer negotiation to the GSSAPI authentication (asdaraujo #1283) + * Fix overriding sasl_kerberos_service_name in KafkaConsumer / KafkaProducer (natedogs911 #1264) + * Fix typo in _try_authenticate_plain (everpcpc #1333) + * Fix for Python 3 byte string handling in SASL auth (christophelec #1353) +* Move callback processing from BrokerConnection to KafkaClient (dpkp #1258) +* Use socket timeout of request_timeout_ms to prevent blocking forever on send (dpkp #1281) +* Refactor dns lookup in BrokerConnection (dpkp #1312) +* Read all available socket bytes (dpkp #1332) +* Honor reconnect_backoff in conn.connect() (dpkp #1342) + +Consumer +* KAFKA-3977: Defer fetch parsing for space efficiency, and to raise exceptions to user (dpkp #1245) +* KAFKA-4034: Avoid unnecessary consumer coordinator lookup (dpkp #1254) +* Handle lookup_coordinator send failures (dpkp #1279) +* KAFKA-3888 Use background thread to process consumer heartbeats (dpkp #1266) +* Improve KafkaConsumer cleanup (dpkp #1339) +* Fix coordinator join_future race condition (dpkp #1338) +* Avoid KeyError when filtering fetchable partitions (dpkp #1344) +* Name heartbeat thread with group_id; use backoff when polling (dpkp #1345) +* KAFKA-3949: Avoid race condition when subscription changes during rebalance (dpkp #1364) +* Fix #1239 regression to avoid consuming duplicate compressed messages from mid-batch (dpkp #1367) + +Producer +* Fix timestamp not passed to RecordMetadata (tvoinarovskyi #1273) +* Raise non-API exceptions (jeffwidman #1316) +* Fix reconnect_backoff_max_ms default config bug in KafkaProducer (YaoC #1352) + +Core / Protocol +* Add kafka.protocol.parser.KafkaProtocol w/ receive and send (dpkp #1230) +* Refactor MessageSet and Message into LegacyRecordBatch to later support v2 message format (tvoinarovskyi #1252) +* Add DefaultRecordBatch implementation aka V2 message format parser/builder. (tvoinarovskyi #1185) +* optimize util.crc32 (ofek #1304) +* Raise better struct pack/unpack errors (jeffwidman #1320) +* Add Request/Response structs for kafka broker 1.0.0 (dpkp #1368) + +Bugfixes +* use python standard max value (lukekingbru #1303) +* changed for to use enumerate() (TheAtomicOption #1301) +* Explicitly check for None rather than falsey (jeffwidman #1269) +* Minor Exception cleanup (jeffwidman #1317) +* Use non-deprecated exception handling (jeffwidman a699f6a) +* Remove assertion with side effect in client.wakeup() (bgedik #1348) +* use absolute imports everywhere (kevinkjt2000 #1362) + +Test Infrastructure +* Use 0.11.0.2 kafka broker for integration testing (dpkp #1357 #1244) +* Add a Makefile to help build the project, generate docs, and run tests (tvoinarovskyi #1247) +* Add fixture support for 1.0.0 broker (dpkp #1275) +* Add kafka 1.0.0 to travis integration tests (dpkp #1365) +* Change fixture default host to localhost (asdaraujo #1305) +* Minor test cleanups (dpkp #1343) +* Use latest pytest 3.4.0, but drop pytest-sugar due to incompatibility (dpkp #1361) + +Documentation +* Expand metrics docs (jeffwidman #1243) +* Fix docstring (jeffwidman #1261) +* Added controlled thread shutdown to example.py (TheAtomicOption #1268) +* Add license to wheel (jeffwidman #1286) +* Use correct casing for MB (jeffwidman #1298) + +Logging / Error Messages +* Fix two bugs in printing bytes instance (jeffwidman #1296) + + +# 1.3.5 (Oct 7, 2017) + +Bugfixes +* Fix partition assignment race condition (jeffwidman #1240) +* Fix consumer bug when seeking / resetting to the middle of a compressed messageset (dpkp #1239) +* Fix traceback sent to stderr not logging (dbgasaway #1221) +* Stop using mutable types for default arg values (jeffwidman #1213) +* Remove a few unused imports (jameslamb #1188) + +Client +* Refactor BrokerConnection to use asynchronous receive_bytes pipe (dpkp #1032) + +Consumer +* Drop unused sleep kwarg to poll (dpkp #1177) +* Enable KafkaConsumer beginning_offsets() and end_offsets() with older broker versions (buptljy #1200) +* Validate consumer subscription topic strings (nikeee #1238) + +Documentation +* Small fixes to SASL documentation and logging; validate security_protocol (dpkp #1231) +* Various typo and grammar fixes (jeffwidman) + + +# 1.3.4 (Aug 13, 2017) + +Bugfixes +* Avoid multiple connection attempts when refreshing metadata (dpkp #1067) +* Catch socket.errors when sending / recving bytes on wake socketpair (dpkp #1069) +* Deal with brokers that reappear with different IP address (originsmike #1085) +* Fix join-time-max and sync-time-max metrics to use Max() measure function (billyevans #1146) +* Raise AssertionError when decompression unsupported (bts-webber #1159) +* Catch ssl.EOFErrors on Python3.3 so we close the failing conn (Ormod #1162) +* Select on sockets to avoid busy polling during bootstrap (dpkp #1175) +* Initialize metadata_snapshot in group coordinator to avoid unnecessary rebalance (dpkp #1174) + +Client +* Timeout idle connections via connections_max_idle_ms (dpkp #1068) +* Warn, dont raise, on DNS lookup failures (dpkp #1091) +* Support exponential backoff for broker reconnections -- KIP-144 (dpkp #1124) +* Add gssapi support (Kerberos) for SASL (Harald-Berghoff #1152) +* Add private map of api key -> min/max versions to BrokerConnection (dpkp #1169) + +Consumer +* Backoff on unavailable group coordinator retry (dpkp #1125) +* Only change_subscription on pattern subscription when topics change (Artimi #1132) +* Add offsets_for_times, beginning_offsets and end_offsets APIs (tvoinarovskyi #1161) + +Producer +* Raise KafkaTimeoutError when flush times out (infecto) +* Set producer atexit timeout to 0 to match del (Ormod #1126) + +Core / Protocol +* 0.11.0.0 protocol updates (only - no client support yet) (dpkp #1127) +* Make UnknownTopicOrPartitionError retriable error (tvoinarovskyi) + +Test Infrastructure +* pylint 1.7.0+ supports python 3.6 and merge py36 into common testenv (jianbin-wei #1095) +* Add kafka 0.10.2.1 into integration testing version (jianbin-wei #1096) +* Disable automated tests for python 2.6 and kafka 0.8.0 and 0.8.1.1 (jianbin-wei #1096) +* Support manual py26 testing; dont advertise 3.3 support (dpkp) +* Add 0.11.0.0 server resources, fix tests for 0.11 brokers (dpkp) +* Use fixture hostname, dont assume localhost (dpkp) +* Add 0.11.0.0 to travis test matrix, remove 0.10.1.1; use scala 2.11 artifacts (dpkp #1176) + +Logging / Error Messages +* Improve error message when expiring batches in KafkaProducer (dpkp #1077) +* Update producer.send docstring -- raises KafkaTimeoutError (infecto) +* Use logging's built-in string interpolation (jeffwidman) +* Fix produce timeout message (melor #1151) +* Fix producer batch expiry messages to use seconds (dnwe) + +Documentation +* Fix typo in KafkaClient docstring (jeffwidman #1054) +* Update README: Prefer python-lz4 over lz4tools (kiri11 #1057) +* Fix poll() hyperlink in KafkaClient (jeffwidman) +* Update RTD links with https / .io (jeffwidman #1074) +* Describe consumer thread-safety (ecksun) +* Fix typo in consumer integration test (jeffwidman) +* Note max_in_flight_requests_per_connection > 1 may change order of messages (tvoinarovskyi #1149) + + +# 1.3.3 (Mar 14, 2017) + +Core / Protocol +* Derive all api classes from Request / Response base classes (dpkp 1030) +* Prefer python-lz4 if available (dpkp 1024) +* Fix kwarg handing in kafka.protocol.struct.Struct (dpkp 1025) +* Fixed couple of "leaks" when gc is disabled (Mephius 979) +* Added `max_bytes` option and FetchRequest_v3 usage. (Drizzt1991 962) +* CreateTopicsRequest / Response v1 (dpkp 1012) +* Add MetadataRequest_v2 and MetadataResponse_v2 structures for KIP-78 (Drizzt1991 974) +* KIP-88 / KAFKA-3853: OffsetFetch v2 structs (jeffwidman 971) +* DRY-up the MetadataRequest_v1 struct (jeffwidman 966) +* Add JoinGroup v1 structs (jeffwidman 965) +* DRY-up the OffsetCommitResponse Structs (jeffwidman 970) +* DRY-up the OffsetFetch structs (jeffwidman 964) +* time --> timestamp to match Java API (jeffwidman 969) +* Add support for offsetRequestV1 messages (jlafaye 951) +* Add FetchRequest/Response_v3 structs (jeffwidman 943) +* Add CreateTopics / DeleteTopics Structs (jeffwidman 944) + +Test Infrastructure +* Add python3.6 to travis test suite, drop python3.3 (exponea 992) +* Update to 0.10.1.1 for integration testing (dpkp 953) +* Update vendored berkerpeksag/selectors34 to ff61b82 (Mephius 979) +* Remove dead code (jeffwidman 967) +* Update pytest fixtures to new yield syntax (jeffwidman 919) + +Consumer +* Avoid re-encoding message for crc check (dpkp 1027) +* Optionally skip auto-commit during consumer.close (dpkp 1031) +* Return copy of consumer subscription set (dpkp 1029) +* Short-circuit group coordinator requests when NodeNotReady (dpkp 995) +* Avoid unknown coordinator after client poll (dpkp 1023) +* No longer configure a default consumer group (dpkp 1016) +* Dont refresh metadata on failed group coordinator request unless needed (dpkp 1006) +* Fail-fast on timeout constraint violations during KafkaConsumer creation (harelba 986) +* Default max_poll_records to Java default of 500 (jeffwidman 947) +* For 0.8.2, only attempt connection to coordinator if least_loaded_node succeeds (dpkp) + +Producer +* change default timeout of KafkaProducer.close() to threading.TIMEOUT_MAX on py3 (mmyjona 991) + +Client +* Add optional kwarg to ready/is_ready to disable metadata-priority logic (dpkp 1017) +* When closing a broker connection without error, fail in-flight-requests with Cancelled (dpkp 1010) +* Catch socket errors during ssl handshake (dpkp 1007) +* Drop old brokers when rebuilding broker metadata (dpkp 1005) +* Drop bad disconnect test -- just use the mocked-socket test (dpkp 982) +* Add support for Python built without ssl (minagawa-sho 954) +* Do not re-close a disconnected connection (dpkp) +* Drop unused last_failure time from BrokerConnection (dpkp) +* Use connection state functions where possible (dpkp) +* Pass error to BrokerConnection.close() (dpkp) + +Bugfixes +* Free lz4 decompression context to avoid leak (dpkp 1024) +* Fix sasl reconnect bug: auth future must be reset on close (dpkp 1003) +* Fix raise exception from SubscriptionState.assign_from_subscribed (qntln 960) +* Fix blackout calculation: mark last_attempt time during connection close (dpkp 1008) +* Fix buffer pool reallocation after raising timeout (dpkp 999) + +Logging / Error Messages +* Add client info logging re bootstrap; log connection attempts to balance with close (dpkp) +* Minor additional logging for consumer coordinator (dpkp) +* Add more debug-level connection logging (dpkp) +* Do not need str(self) when formatting to %s (dpkp) +* Add new broker response errors (dpkp) +* Small style fixes in kafka.errors (dpkp) +* Include the node id in BrokerConnection logging (dpkp 1009) +* Replace %s with %r in producer debug log message (chekunkov 973) + +Documentation +* Sphinx documentation updates (jeffwidman 1019) +* Add sphinx formatting to hyperlink methods (jeffwidman 898) +* Fix BrokerConnection api_version docs default (jeffwidman 909) +* PEP-8: Spacing & removed unused imports (jeffwidman 899) +* Move BrokerConnection docstring to class (jeffwidman 968) +* Move docstring so it shows up in Sphinx/RTD (jeffwidman 952) +* Remove non-pip install instructions (jeffwidman 940) +* Spelling and grammar changes (melissacrawford396 923) +* Fix typo: coorelation --> correlation (jeffwidman 929) +* Make SSL warning list the correct Python versions (jeffwidman 924) +* Fixup comment reference to _maybe_connect (dpkp) +* Add ClusterMetadata sphinx documentation (dpkp) + +Legacy Client +* Add send_list_offset_request for searching offset by timestamp (charsyam 1001) +* Use select to poll sockets for read to reduce CPU usage (jianbin-wei 958) +* Use select.select without instance bounding (adamwen829 949) + + +# 1.3.2 (Dec 28, 2016) + +Core +* Add kafka.serializer interfaces (dpkp 912) +* from kafka import ConsumerRebalanceListener, OffsetAndMetadata +* Use 0.10.0.1 for integration tests (dpkp 803) + +Consumer +* KAFKA-3007: KafkaConsumer max_poll_records (dpkp 831) +* Raise exception if given a non-str topic (ssaamm 824) +* Immediately update metadata for pattern subscription (laz2 915) + +Producer +* Update Partitioners for use with KafkaProducer (barrotsteindev 827) +* Sort partitions before calling partitioner (ms7s 905) +* Added ssl_password config option to KafkaProducer class (kierkegaard13 830) + +Client +* Always check for request timeouts (dpkp 887) +* When hostname lookup is necessary, do every connect (benauthor 812) + +Bugfixes +* Fix errorcode check when socket.connect_ex raises an exception (guojh 907) +* Fix fetcher bug when processing offset out of range (sibiryakov 860) +* Fix possible request draining in ensure_active_group (dpkp 896) +* Fix metadata refresh handling with 0.10+ brokers when topic list is empty (sibiryakov 867) +* KafkaProducer should set timestamp in Message if provided (Drizzt1991 875) +* Fix murmur2 bug handling python2 bytes that do not ascii encode (dpkp 815) +* Monkeypatch max_in_flight_requests_per_connection when checking broker version (dpkp 834) +* Fix message timestamp_type (qix 828) + +Logging / Error Messages +* Always include an error for logging when the coordinator is marked dead (dpkp 890) +* Only string-ify BrokerResponseError args if provided (dpkp 889) +* Update warning re advertised.listeners / advertised.host.name (jeffwidman 878) +* Fix unrecognized sasl_mechanism error message (sharego 883) + +Documentation +* Add docstring for max_records (jeffwidman 897) +* Fixup doc references to max_in_flight_requests_per_connection +* Fix typo: passowrd --> password (jeffwidman 901) +* Fix documentation typo 'Defualt' -> 'Default'. (rolando 895) +* Added doc for `max_poll_records` option (Drizzt1991 881) +* Remove old design notes from Kafka 8 era (jeffwidman 876) +* Fix documentation typos (jeffwidman 874) +* Fix quota violation exception message (dpkp 809) +* Add comment for round robin partitioner with different subscriptions +* Improve KafkaProducer docstring for retries configuration + + +# 1.3.1 (Aug 8, 2016) + +Bugfixes +* Fix AttributeError in BrokerConnectionMetrics after reconnecting + + +# 1.3.0 (Aug 4, 2016) + +Incompatible Changes +* Delete KafkaConnection class (dpkp 769) +* Rename partition_assignment -> assignment in MemberMetadata for consistency +* Move selectors34 and socketpair to kafka.vendor (dpkp 785) +* Change api_version config to tuple; deprecate str with warning (dpkp 761) +* Rename _DEFAULT_CONFIG -> DEFAULT_CONFIG in KafkaProducer (dpkp 788) + +Improvements +* Vendor six 1.10.0 to eliminate runtime dependency (dpkp 785) +* Add KafkaProducer and KafkaConsumer.metrics() with instrumentation similar to java client (dpkp 754 / 772 / 794) +* Support Sasl PLAIN authentication (larsjsol PR 779) +* Add checksum and size to RecordMetadata and ConsumerRecord (KAFKA-3196 / 770 / 594) +* Use MetadataRequest v1 for 0.10+ api_version (dpkp 762) +* Fix KafkaConsumer autocommit for 0.8 brokers (dpkp 756 / 706) +* Improve error logging (dpkp 760 / 759) +* Adapt benchmark scripts from https://github.com/mrafayaleem/kafka-jython (dpkp 754) +* Add api_version config to KafkaClient (dpkp 761) +* New Metadata method with_partitions() (dpkp 787) +* Use socket_options configuration to setsockopts(). Default TCP_NODELAY (dpkp 783) +* Expose selector type as config option (dpkp 764) +* Drain pending requests to the coordinator before initiating group rejoin (dpkp 798) +* Send combined size and payload bytes to socket to avoid potentially split packets with TCP_NODELAY (dpkp 797) + +Bugfixes +* Ignore socket.error when checking for protocol out of sync prior to socket close (dpkp 792) +* Fix offset fetch when partitions are manually assigned (KAFKA-3960 / 786) +* Change pickle_method to use python3 special attributes (jpaulodit 777) +* Fix ProduceResponse v2 throttle_time_ms +* Always encode size with MessageSet (#771) +* Avoid buffer overread when compressing messageset in KafkaProducer +* Explicit format string argument indices for python 2.6 compatibility +* Simplify RecordMetadata; short circuit callbacks (#768) +* Fix autocommit when partitions assigned manually (KAFKA-3486 / #767 / #626) +* Handle metadata updates during consumer rebalance (KAFKA-3117 / #766 / #701) +* Add a consumer config option to exclude internal topics (KAFKA-2832 / #765) +* Protect writes to wakeup socket with threading lock (#763 / #709) +* Fetcher spending unnecessary time during metrics recording (KAFKA-3785) +* Always use absolute_import (dpkp) + +Test / Fixtures +* Catch select errors while capturing test fixture logs +* Fix consumer group test race condition (dpkp 795) +* Retry fixture failures on a different port (dpkp 796) +* Dump fixture logs on failure + +Documentation +* Fix misspelling of password (ssaamm 793) +* Document the ssl_password config option (ssaamm 780) +* Fix typo in KafkaConsumer documentation (ssaamm 775) +* Expand consumer.fetcher inline comments +* Update kafka configuration links -> 0.10.0.0 docs +* Fixup metrics_sample_window_ms docstring in consumer + + +# 1.2.5 (July 15, 2016) + +Bugfixes +* Fix bug causing KafkaProducer to double-compress message batches on retry +* Check for double-compressed messages in KafkaConsumer, log warning and optionally skip +* Drop recursion in _unpack_message_set; only decompress once + + +# 1.2.4 (July 8, 2016) + +Bugfixes +* Update consumer_timeout_ms docstring - KafkaConsumer raises StopIteration, no longer ConsumerTimeout +* Use explicit subscription state flag to handle seek() during message iteration +* Fix consumer iteration on compacted topics (dpkp PR 752) +* Support ssl_password config when loading cert chains (amckemie PR 750) + + +# 1.2.3 (July 2, 2016) + +Patch Improvements +* Fix gc error log: avoid AttributeError in _unregister_cleanup (dpkp PR 747) +* Wakeup socket optimizations (dpkp PR 740) +* Assert will be disabled by "python -O" (tyronecai PR 736) +* Randomize order of topics/partitions processed by fetcher to improve balance (dpkp PR 732) +* Allow client.check_version timeout to be set in Producer and Consumer constructors (eastlondoner PR 647) + + +# 1.2.2 (June 21, 2016) + +Bugfixes +* Clarify timeout unit in KafkaProducer close and flush (ms7s PR 734) +* Avoid busy poll during metadata refresh failure with retry_backoff_ms (dpkp PR 733) +* Check_version should scan nodes until version found or timeout (dpkp PR 731) +* Fix bug which could cause least_loaded_node to always return the same unavailable node (dpkp PR 730) +* Fix producer garbage collection with weakref in atexit handler (dpkp PR 728) +* Close client selector to fix fd leak (msmith PR 729) +* Tweak spelling mistake in error const (steve8918 PR 719) +* Rearrange connection tests to separate legacy KafkaConnection + + +# 1.2.1 (June 1, 2016) + +Bugfixes +* Fix regression in MessageSet decoding wrt PartialMessages (#716) +* Catch response decode errors and log details (#715) +* Fix Legacy support url (#712 - JonasGroeger) +* Update sphinx docs re 0.10 broker support + + +# 1.2.0 (May 24, 2016) + +This release officially adds support for Kafka 0.10 +* Add protocol support for ApiVersionRequest (dpkp PR 678) +* KAFKA-3025: Message v1 -- add timetamp and relative offsets (dpkp PR 693) +* Use Fetch/Produce API v2 for brokers >= 0.10 (uses message format v1) (dpkp PR 694) +* Use standard LZ4 framing for v1 messages / kafka 0.10 (dpkp PR 695) + +Consumers +* Update SimpleConsumer / legacy protocol to handle compressed messages (paulcavallaro PR 684) + +Producers +* KAFKA-3388: Fix expiration of batches sitting in the accumulator (dpkp PR 699) +* KAFKA-3197: when max.in.flight.request.per.connection = 1, attempt to guarantee ordering (dpkp PR 698) +* Don't use soon-to-be-reserved keyword await as function name (FutureProduceResult) (dpkp PR 697) + +Clients +* Fix socket leaks in KafkaClient (dpkp PR 696) + +Documentation + + +Internals +* Support SSL CRL [requires python 2.7.9+ / 3.4+] (vincentbernat PR 683) +* Use original hostname for SSL checks (vincentbernat PR 682) +* Always pass encoded message bytes to MessageSet.encode() +* Raise ValueError on protocol encode/decode errors +* Supplement socket.gaierror exception in BrokerConnection.connect() (erikbeebe PR 687) +* BrokerConnection check_version: expect 0.9 to fail with CorrelationIdError +* Fix small bug in Sensor (zackdever PR 679) + + +# 1.1.1 (Apr 26, 2016) + +quick bugfixes +* fix throttle_time_ms sensor handling (zackdever pr 667) +* improve handling of disconnected sockets (easypost pr 666 / dpkp) +* disable standard metadata refresh triggers during bootstrap (dpkp) +* more predictable future callback/errback exceptions (zackdever pr 670) +* avoid some exceptions in coordinator.__del__ (dpkp pr 668) + + +# 1.1.0 (Apr 25, 2016) + +Consumers +* Avoid resending FetchRequests that are pending on internal queue +* Log debug messages when skipping fetched messages due to offset checks +* KAFKA-3013: Include topic-partition in exception for expired batches +* KAFKA-3318: clean up consumer logging and error messages +* Improve unknown coordinator error handling +* Improve auto-commit error handling when group_id is None +* Add paused() API (zackdever PR 602) +* Add default_offset_commit_callback to KafkaConsumer DEFAULT_CONFIGS + +Producers + + +Clients +* Support SSL connections +* Use selectors module for non-blocking IO +* Refactor KafkaClient connection management +* Fix AttributeError in __del__ +* SimpleClient: catch errors thrown by _get_leader_for_partition (zackdever PR 606) + +Documentation +* Fix serializer/deserializer examples in README +* Update max.block.ms docstring +* Remove errant next(consumer) from consumer documentation +* Add producer.flush() to usage docs + +Internals +* Add initial metrics implementation (zackdever PR 637) +* KAFKA-2136: support Fetch and Produce v1 (throttle_time_ms) +* Use version-indexed lists for request/response protocol structs (dpkp PR 630) +* Split kafka.common into kafka.structs and kafka.errors +* Handle partial socket send() (dpkp PR 611) +* Fix windows support (dpkp PR 603) +* IPv6 support (TimEvens PR 615; Roguelazer PR 642) + + +# 1.0.2 (Mar 14, 2016) + +Consumers +* Improve KafkaConsumer Heartbeat handling (dpkp PR 583) +* Fix KafkaConsumer.position bug (stefanth PR 578) +* Raise TypeError when partition is not a TopicPartition (dpkp PR 587) +* KafkaConsumer.poll should sleep to prevent tight-loops (dpkp PR 597) + +Producers +* Fix producer threading bug that can crash sender (dpkp PR 590) +* Fix bug in producer buffer pool reallocation (dpkp PR 585) +* Remove spurious warnings when closing sync SimpleProducer (twm PR 567) +* Fix FutureProduceResult.await() on python2.6 (dpkp) +* Add optional timeout parameter to KafkaProducer.flush() (dpkp) +* KafkaProducer Optimizations (zackdever PR 598) + +Clients +* Improve error handling in SimpleClient.load_metadata_for_topics (dpkp) +* Improve handling of KafkaClient.least_loaded_node failure (dpkp PR 588) + +Documentation +* Fix KafkaError import error in docs (shichao-an PR 564) +* Fix serializer / deserializer examples (scribu PR 573) + +Internals +* Update to Kafka 0.9.0.1 for integration testing +* Fix ifr.future.failure in conn.py (mortenlj PR 566) +* Improve Zookeeper / Kafka Fixture management (dpkp) + + +# 1.0.1 (Feb 19, 2016) + +Consumers +* Add RangePartitionAssignor (and use as default); add assignor tests (dpkp PR 550) +* Make sure all consumers are in same generation before stopping group test +* Verify node ready before sending offset fetch request from coordinator +* Improve warning when offset fetch request returns unknown topic / partition + +Producers +* Warn if pending batches failed during flush +* Fix concurrency bug in RecordAccumulator.ready() +* Fix bug in SimpleBufferPool memory condition waiting / timeout +* Support batch_size = 0 in producer buffers (dpkp PR 558) +* Catch duplicate batch.done() calls [e.g., maybe_expire then a response errback] + +Clients + +Documentation +* Improve kafka.cluster docstrings +* Migrate load_example.py to KafkaProducer / KafkaConsumer + +Internals +* Don't override system rcvbuf or sndbuf unless configured explicitly (dpkp PR 557) +* Some attributes may not exist in __del__ if we failed assertions +* Break up some circular references and close client wake pipes on __del__ (aisch PR 554) + + +# 1.0.0 (Feb 15, 2016) + +This release includes significant code changes. Users of older kafka-python +versions are encouraged to test upgrades before deploying to production as +some interfaces and configuration options have changed. + +Users of SimpleConsumer / SimpleProducer / SimpleClient (formerly KafkaClient) +from prior releases should migrate to KafkaConsumer / KafkaProducer. Low-level +APIs (Simple*) are no longer being actively maintained and will be removed in a +future release. + +For comprehensive API documentation, please see python help() / docstrings, +kafka-python.readthedocs.org, or run `tox -e docs` from source to build +documentation locally. + +Consumers +* KafkaConsumer re-written to emulate the new 0.9 kafka consumer (java client) + and support coordinated consumer groups (feature requires >= 0.9.0.0 brokers) + + * Methods no longer available: + + * configure [initialize a new consumer instead] + * set_topic_partitions [use subscribe() or assign()] + * fetch_messages [use poll() or iterator interface] + * get_partition_offsets + * offsets [use committed(partition)] + * task_done [handled internally by auto-commit; or commit offsets manually] + + * Configuration changes (consistent with updated java client): + + * lots of new configuration parameters -- see docs for details + * auto_offset_reset: previously values were 'smallest' or 'largest', now + values are 'earliest' or 'latest' + * fetch_wait_max_ms is now fetch_max_wait_ms + * max_partition_fetch_bytes is now max_partition_fetch_bytes + * deserializer_class is now value_deserializer and key_deserializer + * auto_commit_enable is now enable_auto_commit + * auto_commit_interval_messages was removed + * socket_timeout_ms was removed + * refresh_leader_backoff_ms was removed + +* SimpleConsumer and MultiProcessConsumer are now deprecated and will be removed + in a future release. Users are encouraged to migrate to KafkaConsumer. + +Producers +* new producer class: KafkaProducer. Exposes the same interface as official java client. + Async by default; returned future.get() can be called for synchronous blocking +* SimpleProducer is now deprecated and will be removed in a future release. Users are + encouraged to migrate to KafkaProducer. + +Clients +* synchronous KafkaClient renamed to SimpleClient. For backwards compatibility, you + will get a SimpleClient via `from kafka import KafkaClient`. This will change in + a future release. +* All client calls use non-blocking IO under the hood. +* Add probe method check_version() to infer broker versions. + +Documentation +* Updated README and sphinx documentation to address new classes. +* Docstring improvements to make python help() easier to use. + +Internals +* Old protocol stack is deprecated. It has been moved to kafka.protocol.legacy + and may be removed in a future release. +* Protocol layer re-written using Type classes, Schemas and Structs (modeled on + the java client). +* Add support for LZ4 compression (including broken framing header checksum). + + +# 0.9.5 (Dec 6, 2015) + +Consumers +* Initial support for consumer coordinator: offsets only (toddpalino PR 420) +* Allow blocking until some messages are received in SimpleConsumer (saaros PR 457) +* Support subclass config changes in KafkaConsumer (zackdever PR 446) +* Support retry semantics in MultiProcessConsumer (barricadeio PR 456) +* Support partition_info in MultiProcessConsumer (scrapinghub PR 418) +* Enable seek() to an absolute offset in SimpleConsumer (haosdent PR 412) +* Add KafkaConsumer.close() (ucarion PR 426) + +Producers +* Catch client.reinit() exceptions in async producer (dpkp) +* Producer.stop() now blocks until async thread completes (dpkp PR 485) +* Catch errors during load_metadata_for_topics in async producer (bschopman PR 467) +* Add compression-level support for codecs that support it (trbs PR 454) +* Fix translation of Java murmur2 code, fix byte encoding for Python 3 (chrischamberlin PR 439) +* Only call stop() on not-stopped producer objects (docker-hub PR 435) +* Allow null payload for deletion feature (scrapinghub PR 409) + +Clients +* Use non-blocking io for broker aware requests (ecanzonieri PR 473) +* Use debug logging level for metadata request (ecanzonieri PR 415) +* Catch KafkaUnavailableError in _send_broker_aware_request (mutability PR 436) +* Lower logging level on replica not available and commit (ecanzonieri PR 415) + +Documentation +* Update docs and links wrt maintainer change (mumrah -> dpkp) + +Internals +* Add py35 to tox testing +* Update travis config to use container infrastructure +* Add 0.8.2.2 and 0.9.0.0 resources for integration tests; update default official releases +* new pylint disables for pylint 1.5.1 (zackdever PR 481) +* Fix python3 / python2 comments re queue/Queue (dpkp) +* Add Murmur2Partitioner to kafka __all__ imports (dpkp Issue 471) +* Include LICENSE in PyPI sdist (koobs PR 441) + +# 0.9.4 (June 11, 2015) + +Consumers +* Refactor SimpleConsumer internal fetch handling (dpkp PR 399) +* Handle exceptions in SimpleConsumer commit() and reset_partition_offset() (dpkp PR 404) +* Improve FailedPayloadsError handling in KafkaConsumer (dpkp PR 398) +* KafkaConsumer: avoid raising KeyError in task_done (dpkp PR 389) +* MultiProcessConsumer -- support configured partitions list (dpkp PR 380) +* Fix SimpleConsumer leadership change handling (dpkp PR 393) +* Fix SimpleConsumer connection error handling (reAsOn2010 PR 392) +* Improve Consumer handling of 'falsy' partition values (wting PR 342) +* Fix _offsets call error in KafkaConsumer (hellais PR 376) +* Fix str/bytes bug in KafkaConsumer (dpkp PR 365) +* Register atexit handlers for consumer and producer thread/multiprocess cleanup (dpkp PR 360) +* Always fetch commit offsets in base consumer unless group is None (dpkp PR 356) +* Stop consumer threads on delete (dpkp PR 357) +* Deprecate metadata_broker_list in favor of bootstrap_servers in KafkaConsumer (dpkp PR 340) +* Support pass-through parameters in multiprocess consumer (scrapinghub PR 336) +* Enable offset commit on SimpleConsumer.seek (ecanzonieri PR 350) +* Improve multiprocess consumer partition distribution (scrapinghub PR 335) +* Ignore messages with offset less than requested (wkiser PR 328) +* Handle OffsetOutOfRange in SimpleConsumer (ecanzonieri PR 296) + +Producers +* Add Murmur2Partitioner (dpkp PR 378) +* Log error types in SimpleProducer and SimpleConsumer (dpkp PR 405) +* SimpleProducer support configuration of fail_on_error (dpkp PR 396) +* Deprecate KeyedProducer.send() (dpkp PR 379) +* Further improvements to async producer code (dpkp PR 388) +* Add more configuration parameters for async producer (dpkp) +* Deprecate SimpleProducer batch_send=True in favor of async (dpkp) +* Improve async producer error handling and retry logic (vshlapakov PR 331) +* Support message keys in async producer (vshlapakov PR 329) +* Use threading instead of multiprocessing for Async Producer (vshlapakov PR 330) +* Stop threads on __del__ (chmduquesne PR 324) +* Fix leadership failover handling in KeyedProducer (dpkp PR 314) + +KafkaClient +* Add .topics property for list of known topics (dpkp) +* Fix request / response order guarantee bug in KafkaClient (dpkp PR 403) +* Improve KafkaClient handling of connection failures in _get_conn (dpkp) +* Client clears local metadata cache before updating from server (dpkp PR 367) +* KafkaClient should return a response or error for each request - enable better retry handling (dpkp PR 366) +* Improve str/bytes conversion in KafkaClient and KafkaConsumer (dpkp PR 332) +* Always return sorted partition ids in client.get_partition_ids_for_topic() (dpkp PR 315) + +Documentation +* Cleanup Usage Documentation +* Improve KafkaConsumer documentation (dpkp PR 341) +* Update consumer documentation (sontek PR 317) +* Add doc configuration for tox (sontek PR 316) +* Switch to .rst doc format (sontek PR 321) +* Fixup google groups link in README (sontek PR 320) +* Automate documentation at kafka-python.readthedocs.org + +Internals +* Switch integration testing from 0.8.2.0 to 0.8.2.1 (dpkp PR 402) +* Fix most flaky tests, improve debug logging, improve fixture handling (dpkp) +* General style cleanups (dpkp PR 394) +* Raise error on duplicate topic-partition payloads in protocol grouping (dpkp) +* Use module-level loggers instead of simply 'kafka' (dpkp) +* Remove pkg_resources check for __version__ at runtime (dpkp PR 387) +* Make external API consistently support python3 strings for topic (kecaps PR 361) +* Fix correlation id overflow (dpkp PR 355) +* Cleanup kafka/common structs (dpkp PR 338) +* Use context managers in gzip_encode / gzip_decode (dpkp PR 337) +* Save failed request as FailedPayloadsError attribute (jobevers PR 302) +* Remove unused kafka.queue (mumrah) + +# 0.9.3 (Feb 3, 2015) + +* Add coveralls.io support (sontek PR 307) +* Fix python2.6 threading.Event bug in ReentrantTimer (dpkp PR 312) +* Add kafka 0.8.2.0 to travis integration tests (dpkp PR 310) +* Auto-convert topics to utf-8 bytes in Producer (sontek PR 306) +* Fix reference cycle between SimpleConsumer and ReentrantTimer (zhaopengzp PR 309) +* Add Sphinx API docs (wedaly PR 282) +* Handle additional error cases exposed by 0.8.2.0 kafka server (dpkp PR 295) +* Refactor error class management (alexcb PR 289) +* Expose KafkaConsumer in __all__ for easy imports (Dinoshauer PR 286) +* SimpleProducer starts on random partition by default (alexcb PR 288) +* Add keys to compressed messages (meandthewallaby PR 281) +* Add new high-level KafkaConsumer class based on java client api (dpkp PR 234) +* Add KeyedProducer.send_messages api (pubnub PR 277) +* Fix consumer pending() method (jettify PR 276) +* Update low-level demo in README (sunisdown PR 274) +* Include key in KeyedProducer messages (se7entyse7en PR 268) +* Fix SimpleConsumer timeout behavior in get_messages (dpkp PR 238) +* Fix error in consumer.py test against max_buffer_size (rthille/wizzat PR 225/242) +* Improve string concat performance on pypy / py3 (dpkp PR 233) +* Reorg directory layout for consumer/producer/partitioners (dpkp/wizzat PR 232/243) +* Add OffsetCommitContext (locationlabs PR 217) +* Metadata Refactor (dpkp PR 223) +* Add Python 3 support (brutasse/wizzat - PR 227) +* Minor cleanups - imports / README / PyPI classifiers (dpkp - PR 221) +* Fix socket test (dpkp - PR 222) +* Fix exception catching bug in test_failover_integration (zever - PR 216) + +# 0.9.2 (Aug 26, 2014) + +* Warn users that async producer does not reliably handle failures (dpkp - PR 213) +* Fix spurious ConsumerFetchSizeTooSmall error in consumer (DataDog - PR 136) +* Use PyLint for static error checking (dpkp - PR 208) +* Strictly enforce str message type in producer.send_messages (dpkp - PR 211) +* Add test timers via nose-timer plugin; list 10 slowest timings by default (dpkp) +* Move fetching last known offset logic to a stand alone function (zever - PR 177) +* Improve KafkaConnection and add more tests (dpkp - PR 196) +* Raise TypeError if necessary when encoding strings (mdaniel - PR 204) +* Use Travis-CI to publish tagged releases to pypi (tkuhlman / mumrah) +* Use official binary tarballs for integration tests and parallelize travis tests (dpkp - PR 193) +* Improve new-topic creation handling (wizzat - PR 174) + +# 0.9.1 (Aug 10, 2014) + +* Add codec parameter to Producers to enable compression (patricklucas - PR 166) +* Support IPv6 hosts and network (snaury - PR 169) +* Remove dependency on distribute (patricklucas - PR 163) +* Fix connection error timeout and improve tests (wizzat - PR 158) +* SimpleProducer randomization of initial round robin ordering (alexcb - PR 139) +* Fix connection timeout in KafkaClient and KafkaConnection (maciejkula - PR 161) +* Fix seek + commit behavior (wizzat - PR 148) + + +# 0.9.0 (Mar 21, 2014) + +* Connection refactor and test fixes (wizzat - PR 134) +* Fix when partition has no leader (mrtheb - PR 109) +* Change Producer API to take topic as send argument, not as instance variable (rdiomar - PR 111) +* Substantial refactor and Test Fixing (rdiomar - PR 88) +* Fix Multiprocess Consumer on windows (mahendra - PR 62) +* Improve fault tolerance; add integration tests (jimjh) +* PEP8 / Flakes / Style cleanups (Vetoshkin Nikita; mrtheb - PR 59) +* Setup Travis CI (jimjh - PR 53/54) +* Fix import of BufferUnderflowError (jimjh - PR 49) +* Fix code examples in README (StevenLeRoux - PR 47/48) + +# 0.8.0 + +* Changing auto_commit to False in [SimpleConsumer](kafka/consumer.py), until 0.8.1 is release offset commits are unsupported +* Adding fetch_size_bytes to SimpleConsumer constructor to allow for user-configurable fetch sizes +* Allow SimpleConsumer to automatically increase the fetch size if a partial message is read and no other messages were read during that fetch request. The increase factor is 1.5 +* Exception classes moved to kafka.common diff --git a/testbed/dpkp__kafka-python/LICENSE b/testbed/dpkp__kafka-python/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..412a2b630bac63250b65e8e14e20451759a0d8ed --- /dev/null +++ b/testbed/dpkp__kafka-python/LICENSE @@ -0,0 +1,202 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 David Arthur + + 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. + diff --git a/testbed/dpkp__kafka-python/MANIFEST.in b/testbed/dpkp__kafka-python/MANIFEST.in new file mode 100644 index 0000000000000000000000000000000000000000..01e6a4d441091d6621bac7df1b644e2e6102bd99 --- /dev/null +++ b/testbed/dpkp__kafka-python/MANIFEST.in @@ -0,0 +1,5 @@ +recursive-include kafka *.py +include README.rst +include LICENSE +include AUTHORS.md +include CHANGES.md diff --git a/testbed/dpkp__kafka-python/Makefile b/testbed/dpkp__kafka-python/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..b4dcbffc986ab2f8d8909e235ae6f647bc1212bf --- /dev/null +++ b/testbed/dpkp__kafka-python/Makefile @@ -0,0 +1,59 @@ +# Some simple testing tasks (sorry, UNIX only). + +FLAGS= +KAFKA_VERSION=0.11.0.2 +SCALA_VERSION=2.12 + +setup: + pip install -r requirements-dev.txt + pip install -Ue . + +servers/$(KAFKA_VERSION)/kafka-bin: + KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) ./build_integration.sh + +build-integration: servers/$(KAFKA_VERSION)/kafka-bin + +# Test and produce coverage using tox. This is the same as is run on Travis +test37: build-integration + KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) tox -e py37 -- $(FLAGS) + +test27: build-integration + KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) tox -e py27 -- $(FLAGS) + +# Test using py.test directly if you want to use local python. Useful for other +# platforms that require manual installation for C libraries, ie. Windows. +test-local: build-integration + KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) py.test \ + --pylint --pylint-rcfile=pylint.rc --pylint-error-types=EF $(FLAGS) kafka test + +cov-local: build-integration + KAFKA_VERSION=$(KAFKA_VERSION) SCALA_VERSION=$(SCALA_VERSION) py.test \ + --pylint --pylint-rcfile=pylint.rc --pylint-error-types=EF --cov=kafka \ + --cov-config=.covrc --cov-report html $(FLAGS) kafka test + @echo "open file://`pwd`/htmlcov/index.html" + +# Check the readme for syntax errors, which can lead to invalid formatting on +# PyPi homepage (https://pypi.python.org/pypi/kafka-python) +check-readme: + python setup.py check -rms + +clean: + rm -rf `find . -name __pycache__` + rm -f `find . -type f -name '*.py[co]' ` + rm -f `find . -type f -name '*~' ` + rm -f `find . -type f -name '.*~' ` + rm -f `find . -type f -name '@*' ` + rm -f `find . -type f -name '#*#' ` + rm -f `find . -type f -name '*.orig' ` + rm -f `find . -type f -name '*.rej' ` + rm -f .coverage + rm -rf htmlcov + rm -rf docs/_build/ + rm -rf cover + rm -rf dist + +doc: + make -C docs html + @echo "open file://`pwd`/docs/_build/html/index.html" + +.PHONY: all test37 test27 test-local cov-local clean doc diff --git a/testbed/dpkp__kafka-python/README.rst b/testbed/dpkp__kafka-python/README.rst new file mode 100644 index 0000000000000000000000000000000000000000..5f834442c5d691a896369593e7b7a89d384275d3 --- /dev/null +++ b/testbed/dpkp__kafka-python/README.rst @@ -0,0 +1,172 @@ +Kafka Python client +------------------------ + +.. image:: https://img.shields.io/badge/kafka-2.6%2C%202.5%2C%202.4%2C%202.3%2C%202.2%2C%202.1%2C%202.0%2C%201.1%2C%201.0%2C%200.11%2C%200.10%2C%200.9%2C%200.8-brightgreen.svg + :target: https://kafka-python.readthedocs.io/en/master/compatibility.html +.. image:: https://img.shields.io/pypi/pyversions/kafka-python.svg + :target: https://pypi.python.org/pypi/kafka-python +.. image:: https://coveralls.io/repos/dpkp/kafka-python/badge.svg?branch=master&service=github + :target: https://coveralls.io/github/dpkp/kafka-python?branch=master +.. image:: https://travis-ci.org/dpkp/kafka-python.svg?branch=master + :target: https://travis-ci.org/dpkp/kafka-python +.. image:: https://img.shields.io/badge/license-Apache%202-blue.svg + :target: https://github.com/dpkp/kafka-python/blob/master/LICENSE + +Python client for the Apache Kafka distributed stream processing system. +kafka-python is designed to function much like the official java client, with a +sprinkling of pythonic interfaces (e.g., consumer iterators). + +kafka-python is best used with newer brokers (0.9+), but is backwards-compatible with +older versions (to 0.8.0). Some features will only be enabled on newer brokers. +For example, fully coordinated consumer groups -- i.e., dynamic partition +assignment to multiple consumers in the same group -- requires use of 0.9+ kafka +brokers. Supporting this feature for earlier broker releases would require +writing and maintaining custom leadership election and membership / health +check code (perhaps using zookeeper or consul). For older brokers, you can +achieve something similar by manually assigning different partitions to each +consumer instance with config management tools like chef, ansible, etc. This +approach will work fine, though it does not support rebalancing on failures. +See +for more details. + +Please note that the master branch may contain unreleased features. For release +documentation, please see readthedocs and/or python's inline help. + +>>> pip install kafka-python + + +KafkaConsumer +************* + +KafkaConsumer is a high-level message consumer, intended to operate as similarly +as possible to the official java client. Full support for coordinated +consumer groups requires use of kafka brokers that support the Group APIs: kafka v0.9+. + +See +for API and configuration details. + +The consumer iterator returns ConsumerRecords, which are simple namedtuples +that expose basic message attributes: topic, partition, offset, key, and value: + +>>> from kafka import KafkaConsumer +>>> consumer = KafkaConsumer('my_favorite_topic') +>>> for msg in consumer: +... print (msg) + +>>> # join a consumer group for dynamic partition assignment and offset commits +>>> from kafka import KafkaConsumer +>>> consumer = KafkaConsumer('my_favorite_topic', group_id='my_favorite_group') +>>> for msg in consumer: +... print (msg) + +>>> # manually assign the partition list for the consumer +>>> from kafka import TopicPartition +>>> consumer = KafkaConsumer(bootstrap_servers='localhost:1234') +>>> consumer.assign([TopicPartition('foobar', 2)]) +>>> msg = next(consumer) + +>>> # Deserialize msgpack-encoded values +>>> consumer = KafkaConsumer(value_deserializer=msgpack.loads) +>>> consumer.subscribe(['msgpackfoo']) +>>> for msg in consumer: +... assert isinstance(msg.value, dict) + +>>> # Access record headers. The returned value is a list of tuples +>>> # with str, bytes for key and value +>>> for msg in consumer: +... print (msg.headers) + +>>> # Get consumer metrics +>>> metrics = consumer.metrics() + + +KafkaProducer +************* + +KafkaProducer is a high-level, asynchronous message producer. The class is +intended to operate as similarly as possible to the official java client. +See +for more details. + +>>> from kafka import KafkaProducer +>>> producer = KafkaProducer(bootstrap_servers='localhost:1234') +>>> for _ in range(100): +... producer.send('foobar', b'some_message_bytes') + +>>> # Block until a single message is sent (or timeout) +>>> future = producer.send('foobar', b'another_message') +>>> result = future.get(timeout=60) + +>>> # Block until all pending messages are at least put on the network +>>> # NOTE: This does not guarantee delivery or success! It is really +>>> # only useful if you configure internal batching using linger_ms +>>> producer.flush() + +>>> # Use a key for hashed-partitioning +>>> producer.send('foobar', key=b'foo', value=b'bar') + +>>> # Serialize json messages +>>> import json +>>> producer = KafkaProducer(value_serializer=lambda v: json.dumps(v).encode('utf-8')) +>>> producer.send('fizzbuzz', {'foo': 'bar'}) + +>>> # Serialize string keys +>>> producer = KafkaProducer(key_serializer=str.encode) +>>> producer.send('flipflap', key='ping', value=b'1234') + +>>> # Compress messages +>>> producer = KafkaProducer(compression_type='gzip') +>>> for i in range(1000): +... producer.send('foobar', b'msg %d' % i) + +>>> # Include record headers. The format is list of tuples with string key +>>> # and bytes value. +>>> producer.send('foobar', value=b'c29tZSB2YWx1ZQ==', headers=[('content-encoding', b'base64')]) + +>>> # Get producer performance metrics +>>> metrics = producer.metrics() + + +Thread safety +************* + +The KafkaProducer can be used across threads without issue, unlike the +KafkaConsumer which cannot. + +While it is possible to use the KafkaConsumer in a thread-local manner, +multiprocessing is recommended. + + +Compression +*********** + +kafka-python supports the following compression formats: + +- gzip +- LZ4 +- Snappy +- Zstandard (zstd) + +gzip is supported natively, the others require installing additional libraries. +See for more information. + + +Optimized CRC32 Validation +************************** + +Kafka uses CRC32 checksums to validate messages. kafka-python includes a pure +python implementation for compatibility. To improve performance for high-throughput +applications, kafka-python will use `crc32c` for optimized native code if installed. +See for installation instructions. +See https://pypi.org/project/crc32c/ for details on the underlying crc32c lib. + + +Protocol +******** + +A secondary goal of kafka-python is to provide an easy-to-use protocol layer +for interacting with kafka brokers via the python repl. This is useful for +testing, probing, and general experimentation. The protocol support is +leveraged to enable a KafkaClient.check_version() method that +probes a kafka broker and attempts to identify which version it is running +(0.8.0 to 2.6+). diff --git a/testbed/dpkp__kafka-python/benchmarks/README.md b/testbed/dpkp__kafka-python/benchmarks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1c120358bf8016aadb7cb185608c9d50ce5e67a5 --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/README.md @@ -0,0 +1,4 @@ +The `record_batch_*` benchmarks in this section are written using +``pyperf`` library, created by Victor Stinner. For more information on +how to get reliable results of test runs please consult +https://pyperf.readthedocs.io/en/latest/run_benchmark.html. diff --git a/testbed/dpkp__kafka-python/benchmarks/consumer_performance.py b/testbed/dpkp__kafka-python/benchmarks/consumer_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..9e3b6a919924dd6f8880b496126c6f37f8375666 --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/consumer_performance.py @@ -0,0 +1,181 @@ +#!/usr/bin/env python +# Adapted from https://github.com/mrafayaleem/kafka-jython + +from __future__ import absolute_import, print_function + +import argparse +import logging +import pprint +import sys +import threading +import traceback + +from kafka.vendor.six.moves import range + +from kafka import KafkaConsumer, KafkaProducer +from test.fixtures import KafkaFixture, ZookeeperFixture + +logging.basicConfig(level=logging.ERROR) + + +def start_brokers(n): + print('Starting {0} {1}-node cluster...'.format(KafkaFixture.kafka_version, n)) + print('-> 1 Zookeeper') + zk = ZookeeperFixture.instance() + print('---> {0}:{1}'.format(zk.host, zk.port)) + print() + + partitions = min(n, 3) + replicas = min(n, 3) + print('-> {0} Brokers [{1} partitions / {2} replicas]'.format(n, partitions, replicas)) + brokers = [ + KafkaFixture.instance(i, zk, zk_chroot='', + partitions=partitions, replicas=replicas) + for i in range(n) + ] + for broker in brokers: + print('---> {0}:{1}'.format(broker.host, broker.port)) + print() + return brokers + + +class ConsumerPerformance(object): + + @staticmethod + def run(args): + try: + props = {} + for prop in args.consumer_config: + k, v = prop.split('=') + try: + v = int(v) + except ValueError: + pass + if v == 'None': + v = None + props[k] = v + + if args.brokers: + brokers = start_brokers(args.brokers) + props['bootstrap_servers'] = ['{0}:{1}'.format(broker.host, broker.port) + for broker in brokers] + print('---> bootstrap_servers={0}'.format(props['bootstrap_servers'])) + print() + + print('-> Producing records') + record = bytes(bytearray(args.record_size)) + producer = KafkaProducer(compression_type=args.fixture_compression, + **props) + for i in range(args.num_records): + producer.send(topic=args.topic, value=record) + producer.flush() + producer.close() + print('-> OK!') + print() + + print('Initializing Consumer...') + props['auto_offset_reset'] = 'earliest' + if 'consumer_timeout_ms' not in props: + props['consumer_timeout_ms'] = 10000 + props['metrics_sample_window_ms'] = args.stats_interval * 1000 + for k, v in props.items(): + print('---> {0}={1}'.format(k, v)) + consumer = KafkaConsumer(args.topic, **props) + print('---> group_id={0}'.format(consumer.config['group_id'])) + print('---> report stats every {0} secs'.format(args.stats_interval)) + print('---> raw metrics? {0}'.format(args.raw_metrics)) + timer_stop = threading.Event() + timer = StatsReporter(args.stats_interval, consumer, + event=timer_stop, + raw_metrics=args.raw_metrics) + timer.start() + print('-> OK!') + print() + + records = 0 + for msg in consumer: + records += 1 + if records >= args.num_records: + break + print('Consumed {0} records'.format(records)) + + timer_stop.set() + + except Exception: + exc_info = sys.exc_info() + traceback.print_exception(*exc_info) + sys.exit(1) + + +class StatsReporter(threading.Thread): + def __init__(self, interval, consumer, event=None, raw_metrics=False): + super(StatsReporter, self).__init__() + self.interval = interval + self.consumer = consumer + self.event = event + self.raw_metrics = raw_metrics + + def print_stats(self): + metrics = self.consumer.metrics() + if self.raw_metrics: + pprint.pprint(metrics) + else: + print('{records-consumed-rate} records/sec ({bytes-consumed-rate} B/sec),' + ' {fetch-latency-avg} latency,' + ' {fetch-rate} fetch/s,' + ' {fetch-size-avg} fetch size,' + ' {records-lag-max} max record lag,' + ' {records-per-request-avg} records/req' + .format(**metrics['consumer-fetch-manager-metrics'])) + + + def print_final(self): + self.print_stats() + + def run(self): + while self.event and not self.event.wait(self.interval): + self.print_stats() + else: + self.print_final() + + +def get_args_parser(): + parser = argparse.ArgumentParser( + description='This tool is used to verify the consumer performance.') + + parser.add_argument( + '--topic', type=str, + help='Topic for consumer test', + default='kafka-python-benchmark-test') + parser.add_argument( + '--num-records', type=int, + help='number of messages to consume', + default=1000000) + parser.add_argument( + '--record-size', type=int, + help='message size in bytes', + default=100) + parser.add_argument( + '--consumer-config', type=str, nargs='+', default=(), + help='kafka consumer related configuration properties like ' + 'bootstrap_servers,client_id etc..') + parser.add_argument( + '--fixture-compression', type=str, + help='specify a compression type for use with broker fixtures / producer') + parser.add_argument( + '--brokers', type=int, + help='Number of kafka brokers to start', + default=0) + parser.add_argument( + '--stats-interval', type=int, + help='Interval in seconds for stats reporting to console', + default=5) + parser.add_argument( + '--raw-metrics', action='store_true', + help='Enable this flag to print full metrics dict on each interval') + return parser + + +if __name__ == '__main__': + args = get_args_parser().parse_args() + ConsumerPerformance.run(args) diff --git a/testbed/dpkp__kafka-python/benchmarks/load_example.py b/testbed/dpkp__kafka-python/benchmarks/load_example.py new file mode 100644 index 0000000000000000000000000000000000000000..eef113e9af85142f29a0fa9556c69072e0e0fd9c --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/load_example.py @@ -0,0 +1,66 @@ +#!/usr/bin/env python +from __future__ import print_function +import threading, logging, time + +from kafka import KafkaConsumer, KafkaProducer + +msg_size = 524288 + +producer_stop = threading.Event() +consumer_stop = threading.Event() + +class Producer(threading.Thread): + big_msg = b'1' * msg_size + + def run(self): + producer = KafkaProducer(bootstrap_servers='localhost:9092') + self.sent = 0 + + while not producer_stop.is_set(): + producer.send('my-topic', self.big_msg) + self.sent += 1 + producer.flush() + + +class Consumer(threading.Thread): + + def run(self): + consumer = KafkaConsumer(bootstrap_servers='localhost:9092', + auto_offset_reset='earliest') + consumer.subscribe(['my-topic']) + self.valid = 0 + self.invalid = 0 + + for message in consumer: + if len(message.value) == msg_size: + self.valid += 1 + else: + self.invalid += 1 + + if consumer_stop.is_set(): + break + + consumer.close() + +def main(): + threads = [ + Producer(), + Consumer() + ] + + for t in threads: + t.start() + + time.sleep(10) + producer_stop.set() + consumer_stop.set() + print('Messages sent: %d' % threads[0].sent) + print('Messages recvd: %d' % threads[1].valid) + print('Messages invalid: %d' % threads[1].invalid) + +if __name__ == "__main__": + logging.basicConfig( + format='%(asctime)s.%(msecs)s:%(name)s:%(thread)d:%(levelname)s:%(process)d:%(message)s', + level=logging.INFO + ) + main() diff --git a/testbed/dpkp__kafka-python/benchmarks/producer_performance.py b/testbed/dpkp__kafka-python/benchmarks/producer_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..c0de6fd239d9f5d03b8358c16e508fab5cae75a0 --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/producer_performance.py @@ -0,0 +1,160 @@ +#!/usr/bin/env python +# Adapted from https://github.com/mrafayaleem/kafka-jython + +from __future__ import absolute_import, print_function + +import argparse +import pprint +import sys +import threading +import traceback + +from kafka.vendor.six.moves import range + +from kafka import KafkaProducer +from test.fixtures import KafkaFixture, ZookeeperFixture + + +def start_brokers(n): + print('Starting {0} {1}-node cluster...'.format(KafkaFixture.kafka_version, n)) + print('-> 1 Zookeeper') + zk = ZookeeperFixture.instance() + print('---> {0}:{1}'.format(zk.host, zk.port)) + print() + + partitions = min(n, 3) + replicas = min(n, 3) + print('-> {0} Brokers [{1} partitions / {2} replicas]'.format(n, partitions, replicas)) + brokers = [ + KafkaFixture.instance(i, zk, zk_chroot='', + partitions=partitions, replicas=replicas) + for i in range(n) + ] + for broker in brokers: + print('---> {0}:{1}'.format(broker.host, broker.port)) + print() + return brokers + + +class ProducerPerformance(object): + + @staticmethod + def run(args): + try: + props = {} + for prop in args.producer_config: + k, v = prop.split('=') + try: + v = int(v) + except ValueError: + pass + if v == 'None': + v = None + props[k] = v + + if args.brokers: + brokers = start_brokers(args.brokers) + props['bootstrap_servers'] = ['{0}:{1}'.format(broker.host, broker.port) + for broker in brokers] + print("---> bootstrap_servers={0}".format(props['bootstrap_servers'])) + print() + print('-> OK!') + print() + + print('Initializing producer...') + record = bytes(bytearray(args.record_size)) + props['metrics_sample_window_ms'] = args.stats_interval * 1000 + + producer = KafkaProducer(**props) + for k, v in props.items(): + print('---> {0}={1}'.format(k, v)) + print('---> send {0} byte records'.format(args.record_size)) + print('---> report stats every {0} secs'.format(args.stats_interval)) + print('---> raw metrics? {0}'.format(args.raw_metrics)) + timer_stop = threading.Event() + timer = StatsReporter(args.stats_interval, producer, + event=timer_stop, + raw_metrics=args.raw_metrics) + timer.start() + print('-> OK!') + print() + + for i in range(args.num_records): + producer.send(topic=args.topic, value=record) + producer.flush() + + timer_stop.set() + + except Exception: + exc_info = sys.exc_info() + traceback.print_exception(*exc_info) + sys.exit(1) + + +class StatsReporter(threading.Thread): + def __init__(self, interval, producer, event=None, raw_metrics=False): + super(StatsReporter, self).__init__() + self.interval = interval + self.producer = producer + self.event = event + self.raw_metrics = raw_metrics + + def print_stats(self): + metrics = self.producer.metrics() + if self.raw_metrics: + pprint.pprint(metrics) + else: + print('{record-send-rate} records/sec ({byte-rate} B/sec),' + ' {request-latency-avg} latency,' + ' {record-size-avg} record size,' + ' {batch-size-avg} batch size,' + ' {records-per-request-avg} records/req' + .format(**metrics['producer-metrics'])) + + def print_final(self): + self.print_stats() + + def run(self): + while self.event and not self.event.wait(self.interval): + self.print_stats() + else: + self.print_final() + + +def get_args_parser(): + parser = argparse.ArgumentParser( + description='This tool is used to verify the producer performance.') + + parser.add_argument( + '--topic', type=str, + help='Topic name for test', + default='kafka-python-benchmark-test') + parser.add_argument( + '--num-records', type=int, + help='number of messages to produce', + default=1000000) + parser.add_argument( + '--record-size', type=int, + help='message size in bytes', + default=100) + parser.add_argument( + '--producer-config', type=str, nargs='+', default=(), + help='kafka producer related configuaration properties like ' + 'bootstrap_servers,client_id etc..') + parser.add_argument( + '--brokers', type=int, + help='Number of kafka brokers to start', + default=0) + parser.add_argument( + '--stats-interval', type=int, + help='Interval in seconds for stats reporting to console', + default=5) + parser.add_argument( + '--raw-metrics', action='store_true', + help='Enable this flag to print full metrics dict on each interval') + return parser + + +if __name__ == '__main__': + args = get_args_parser().parse_args() + ProducerPerformance.run(args) diff --git a/testbed/dpkp__kafka-python/benchmarks/record_batch_compose.py b/testbed/dpkp__kafka-python/benchmarks/record_batch_compose.py new file mode 100644 index 0000000000000000000000000000000000000000..5bdefa7af5b59055b47c74889e83f5f162729126 --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/record_batch_compose.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +from __future__ import print_function +import hashlib +import itertools +import os +import random + +import pyperf + +from kafka.record.memory_records import MemoryRecordsBuilder + + +DEFAULT_BATCH_SIZE = 1600 * 1024 +KEY_SIZE = 6 +VALUE_SIZE = 60 +TIMESTAMP_RANGE = [1505824130000, 1505824140000] + +# With values above v1 record is 100 bytes, so 10 000 bytes for 100 messages +MESSAGES_PER_BATCH = 100 + + +def random_bytes(length): + buffer = bytearray(length) + for i in range(length): + buffer[i] = random.randint(0, 255) + return bytes(buffer) + + +def prepare(): + return iter(itertools.cycle([ + (random_bytes(KEY_SIZE), + random_bytes(VALUE_SIZE), + random.randint(*TIMESTAMP_RANGE) + ) + for _ in range(int(MESSAGES_PER_BATCH * 1.94)) + ])) + + +def finalize(results): + # Just some strange code to make sure PyPy does execute the main code + # properly, without optimizing it away + hash_val = hashlib.md5() + for buf in results: + hash_val.update(buf) + print(hash_val, file=open(os.devnull, "w")) + + +def func(loops, magic): + # Jit can optimize out the whole function if the result is the same each + # time, so we need some randomized input data ) + precomputed_samples = prepare() + results = [] + + # Main benchmark code. + t0 = pyperf.perf_counter() + for _ in range(loops): + batch = MemoryRecordsBuilder( + magic, batch_size=DEFAULT_BATCH_SIZE, compression_type=0) + for _ in range(MESSAGES_PER_BATCH): + key, value, timestamp = next(precomputed_samples) + size = batch.append( + timestamp=timestamp, key=key, value=value) + assert size + batch.close() + results.append(batch.buffer()) + + res = pyperf.perf_counter() - t0 + + finalize(results) + + return res + + +runner = pyperf.Runner() +runner.bench_time_func('batch_append_v0', func, 0) +runner.bench_time_func('batch_append_v1', func, 1) +runner.bench_time_func('batch_append_v2', func, 2) diff --git a/testbed/dpkp__kafka-python/benchmarks/record_batch_read.py b/testbed/dpkp__kafka-python/benchmarks/record_batch_read.py new file mode 100644 index 0000000000000000000000000000000000000000..aa5e9c1e5de00dd5fac30a69060707b9f06135d6 --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/record_batch_read.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +from __future__ import print_function +import hashlib +import itertools +import os +import random + +import pyperf + +from kafka.record.memory_records import MemoryRecords, MemoryRecordsBuilder + + +DEFAULT_BATCH_SIZE = 1600 * 1024 +KEY_SIZE = 6 +VALUE_SIZE = 60 +TIMESTAMP_RANGE = [1505824130000, 1505824140000] + +BATCH_SAMPLES = 5 +MESSAGES_PER_BATCH = 100 + + +def random_bytes(length): + buffer = bytearray(length) + for i in range(length): + buffer[i] = random.randint(0, 255) + return bytes(buffer) + + +def prepare(magic): + samples = [] + for _ in range(BATCH_SAMPLES): + batch = MemoryRecordsBuilder( + magic, batch_size=DEFAULT_BATCH_SIZE, compression_type=0) + for _ in range(MESSAGES_PER_BATCH): + size = batch.append( + random.randint(*TIMESTAMP_RANGE), + random_bytes(KEY_SIZE), + random_bytes(VALUE_SIZE), + headers=[]) + assert size + batch.close() + samples.append(bytes(batch.buffer())) + + return iter(itertools.cycle(samples)) + + +def finalize(results): + # Just some strange code to make sure PyPy does execute the code above + # properly + hash_val = hashlib.md5() + for buf in results: + hash_val.update(buf) + print(hash_val, file=open(os.devnull, "w")) + + +def func(loops, magic): + # Jit can optimize out the whole function if the result is the same each + # time, so we need some randomized input data ) + precomputed_samples = prepare(magic) + results = [] + + # Main benchmark code. + batch_data = next(precomputed_samples) + t0 = pyperf.perf_counter() + for _ in range(loops): + records = MemoryRecords(batch_data) + while records.has_next(): + batch = records.next_batch() + batch.validate_crc() + for record in batch: + results.append(record.value) + + res = pyperf.perf_counter() - t0 + finalize(results) + + return res + + +runner = pyperf.Runner() +runner.bench_time_func('batch_read_v0', func, 0) +runner.bench_time_func('batch_read_v1', func, 1) +runner.bench_time_func('batch_read_v2', func, 2) diff --git a/testbed/dpkp__kafka-python/benchmarks/varint_speed.py b/testbed/dpkp__kafka-python/benchmarks/varint_speed.py new file mode 100644 index 0000000000000000000000000000000000000000..fd63d0ac157dd7b2703cf495a94ab17fe804b0a4 --- /dev/null +++ b/testbed/dpkp__kafka-python/benchmarks/varint_speed.py @@ -0,0 +1,443 @@ +#!/usr/bin/env python +from __future__ import print_function +import pyperf +from kafka.vendor import six + + +test_data = [ + (b"\x00", 0), + (b"\x01", -1), + (b"\x02", 1), + (b"\x7E", 63), + (b"\x7F", -64), + (b"\x80\x01", 64), + (b"\x81\x01", -65), + (b"\xFE\x7F", 8191), + (b"\xFF\x7F", -8192), + (b"\x80\x80\x01", 8192), + (b"\x81\x80\x01", -8193), + (b"\xFE\xFF\x7F", 1048575), + (b"\xFF\xFF\x7F", -1048576), + (b"\x80\x80\x80\x01", 1048576), + (b"\x81\x80\x80\x01", -1048577), + (b"\xFE\xFF\xFF\x7F", 134217727), + (b"\xFF\xFF\xFF\x7F", -134217728), + (b"\x80\x80\x80\x80\x01", 134217728), + (b"\x81\x80\x80\x80\x01", -134217729), + (b"\xFE\xFF\xFF\xFF\x7F", 17179869183), + (b"\xFF\xFF\xFF\xFF\x7F", -17179869184), + (b"\x80\x80\x80\x80\x80\x01", 17179869184), + (b"\x81\x80\x80\x80\x80\x01", -17179869185), + (b"\xFE\xFF\xFF\xFF\xFF\x7F", 2199023255551), + (b"\xFF\xFF\xFF\xFF\xFF\x7F", -2199023255552), + (b"\x80\x80\x80\x80\x80\x80\x01", 2199023255552), + (b"\x81\x80\x80\x80\x80\x80\x01", -2199023255553), + (b"\xFE\xFF\xFF\xFF\xFF\xFF\x7F", 281474976710655), + (b"\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -281474976710656), + (b"\x80\x80\x80\x80\x80\x80\x80\x01", 281474976710656), + (b"\x81\x80\x80\x80\x80\x80\x80\x01", -281474976710657), + (b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 36028797018963967), + (b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -36028797018963968), + (b"\x80\x80\x80\x80\x80\x80\x80\x80\x01", 36028797018963968), + (b"\x81\x80\x80\x80\x80\x80\x80\x80\x01", -36028797018963969), + (b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 4611686018427387903), + (b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -4611686018427387904), + (b"\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01", 4611686018427387904), + (b"\x81\x80\x80\x80\x80\x80\x80\x80\x80\x01", -4611686018427387905), +] + + +BENCH_VALUES_ENC = [ + 60, # 1 byte + -8192, # 2 bytes + 1048575, # 3 bytes + 134217727, # 4 bytes + -17179869184, # 5 bytes + 2199023255551, # 6 bytes +] + +BENCH_VALUES_DEC = [ + b"\x7E", # 1 byte + b"\xFF\x7F", # 2 bytes + b"\xFE\xFF\x7F", # 3 bytes + b"\xFF\xFF\xFF\x7F", # 4 bytes + b"\x80\x80\x80\x80\x01", # 5 bytes + b"\xFE\xFF\xFF\xFF\xFF\x7F", # 6 bytes +] +BENCH_VALUES_DEC = list(map(bytearray, BENCH_VALUES_DEC)) + + +def _assert_valid_enc(enc_func): + for encoded, decoded in test_data: + assert enc_func(decoded) == encoded, decoded + + +def _assert_valid_dec(dec_func): + for encoded, decoded in test_data: + res, pos = dec_func(bytearray(encoded)) + assert res == decoded, (decoded, res) + assert pos == len(encoded), (decoded, pos) + + +def _assert_valid_size(size_func): + for encoded, decoded in test_data: + assert size_func(decoded) == len(encoded), decoded + + +def encode_varint_1(num): + """ Encode an integer to a varint presentation. See + https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints + on how those can be produced. + + Arguments: + num (int): Value to encode + + Returns: + bytearray: Encoded presentation of integer with length from 1 to 10 + bytes + """ + # Shift sign to the end of number + num = (num << 1) ^ (num >> 63) + # Max 10 bytes. We assert those are allocated + buf = bytearray(10) + + for i in range(10): + # 7 lowest bits from the number and set 8th if we still have pending + # bits left to encode + buf[i] = num & 0x7f | (0x80 if num > 0x7f else 0) + num = num >> 7 + if num == 0: + break + else: + # Max size of endcoded double is 10 bytes for unsigned values + raise ValueError("Out of double range") + return buf[:i + 1] + +_assert_valid_enc(encode_varint_1) + + +def encode_varint_2(value, int2byte=six.int2byte): + value = (value << 1) ^ (value >> 63) + + bits = value & 0x7f + value >>= 7 + res = b"" + while value: + res += int2byte(0x80 | bits) + bits = value & 0x7f + value >>= 7 + return res + int2byte(bits) + +_assert_valid_enc(encode_varint_2) + + +def encode_varint_3(value, buf): + append = buf.append + value = (value << 1) ^ (value >> 63) + + bits = value & 0x7f + value >>= 7 + while value: + append(0x80 | bits) + bits = value & 0x7f + value >>= 7 + append(bits) + return value + + +for encoded, decoded in test_data: + res = bytearray() + encode_varint_3(decoded, res) + assert res == encoded + + +def encode_varint_4(value, int2byte=six.int2byte): + value = (value << 1) ^ (value >> 63) + + if value <= 0x7f: # 1 byte + return int2byte(value) + if value <= 0x3fff: # 2 bytes + return int2byte(0x80 | (value & 0x7f)) + int2byte(value >> 7) + if value <= 0x1fffff: # 3 bytes + return int2byte(0x80 | (value & 0x7f)) + \ + int2byte(0x80 | ((value >> 7) & 0x7f)) + \ + int2byte(value >> 14) + if value <= 0xfffffff: # 4 bytes + return int2byte(0x80 | (value & 0x7f)) + \ + int2byte(0x80 | ((value >> 7) & 0x7f)) + \ + int2byte(0x80 | ((value >> 14) & 0x7f)) + \ + int2byte(value >> 21) + if value <= 0x7ffffffff: # 5 bytes + return int2byte(0x80 | (value & 0x7f)) + \ + int2byte(0x80 | ((value >> 7) & 0x7f)) + \ + int2byte(0x80 | ((value >> 14) & 0x7f)) + \ + int2byte(0x80 | ((value >> 21) & 0x7f)) + \ + int2byte(value >> 28) + else: + # Return to general algorithm + bits = value & 0x7f + value >>= 7 + res = b"" + while value: + res += int2byte(0x80 | bits) + bits = value & 0x7f + value >>= 7 + return res + int2byte(bits) + + +_assert_valid_enc(encode_varint_4) + +# import dis +# dis.dis(encode_varint_4) + + +def encode_varint_5(value, buf, pos=0): + value = (value << 1) ^ (value >> 63) + + bits = value & 0x7f + value >>= 7 + while value: + buf[pos] = 0x80 | bits + bits = value & 0x7f + value >>= 7 + pos += 1 + buf[pos] = bits + return pos + 1 + +for encoded, decoded in test_data: + res = bytearray(10) + written = encode_varint_5(decoded, res) + assert res[:written] == encoded + + +def encode_varint_6(value, buf): + append = buf.append + value = (value << 1) ^ (value >> 63) + + if value <= 0x7f: # 1 byte + append(value) + return 1 + if value <= 0x3fff: # 2 bytes + append(0x80 | (value & 0x7f)) + append(value >> 7) + return 2 + if value <= 0x1fffff: # 3 bytes + append(0x80 | (value & 0x7f)) + append(0x80 | ((value >> 7) & 0x7f)) + append(value >> 14) + return 3 + if value <= 0xfffffff: # 4 bytes + append(0x80 | (value & 0x7f)) + append(0x80 | ((value >> 7) & 0x7f)) + append(0x80 | ((value >> 14) & 0x7f)) + append(value >> 21) + return 4 + if value <= 0x7ffffffff: # 5 bytes + append(0x80 | (value & 0x7f)) + append(0x80 | ((value >> 7) & 0x7f)) + append(0x80 | ((value >> 14) & 0x7f)) + append(0x80 | ((value >> 21) & 0x7f)) + append(value >> 28) + return 5 + else: + # Return to general algorithm + bits = value & 0x7f + value >>= 7 + i = 0 + while value: + append(0x80 | bits) + bits = value & 0x7f + value >>= 7 + i += 1 + append(bits) + return i + + +for encoded, decoded in test_data: + res = bytearray() + encode_varint_6(decoded, res) + assert res == encoded + + +def size_of_varint_1(value): + """ Number of bytes needed to encode an integer in variable-length format. + """ + value = (value << 1) ^ (value >> 63) + res = 0 + while True: + res += 1 + value = value >> 7 + if value == 0: + break + return res + +_assert_valid_size(size_of_varint_1) + + +def size_of_varint_2(value): + """ Number of bytes needed to encode an integer in variable-length format. + """ + value = (value << 1) ^ (value >> 63) + if value <= 0x7f: + return 1 + if value <= 0x3fff: + return 2 + if value <= 0x1fffff: + return 3 + if value <= 0xfffffff: + return 4 + if value <= 0x7ffffffff: + return 5 + if value <= 0x3ffffffffff: + return 6 + if value <= 0x1ffffffffffff: + return 7 + if value <= 0xffffffffffffff: + return 8 + if value <= 0x7fffffffffffffff: + return 9 + return 10 + +_assert_valid_size(size_of_varint_2) + + +if six.PY3: + def _read_byte(memview, pos): + """ Read a byte from memoryview as an integer + + Raises: + IndexError: if position is out of bounds + """ + return memview[pos] +else: + def _read_byte(memview, pos): + """ Read a byte from memoryview as an integer + + Raises: + IndexError: if position is out of bounds + """ + return ord(memview[pos]) + + +def decode_varint_1(buffer, pos=0): + """ Decode an integer from a varint presentation. See + https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints + on how those can be produced. + + Arguments: + buffer (bytes-like): any object acceptable by ``memoryview`` + pos (int): optional position to read from + + Returns: + (int, int): Decoded int value and next read position + """ + value = 0 + shift = 0 + memview = memoryview(buffer) + for i in range(pos, pos + 10): + try: + byte = _read_byte(memview, i) + except IndexError: + raise ValueError("End of byte stream") + if byte & 0x80 != 0: + value |= (byte & 0x7f) << shift + shift += 7 + else: + value |= byte << shift + break + else: + # Max size of endcoded double is 10 bytes for unsigned values + raise ValueError("Out of double range") + # Normalize sign + return (value >> 1) ^ -(value & 1), i + 1 + +_assert_valid_dec(decode_varint_1) + + +def decode_varint_2(buffer, pos=0): + result = 0 + shift = 0 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + # result = result_type(() & mask) + return ((result >> 1) ^ -(result & 1), pos) + shift += 7 + if shift >= 64: + raise ValueError("Out of int64 range") + + +_assert_valid_dec(decode_varint_2) + + +def decode_varint_3(buffer, pos=0): + result = buffer[pos] + if not (result & 0x81): + return (result >> 1), pos + 1 + if not (result & 0x80): + return (result >> 1) ^ (~0), pos + 1 + + result &= 0x7f + pos += 1 + shift = 7 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + return ((result >> 1) ^ -(result & 1), pos) + shift += 7 + if shift >= 64: + raise ValueError("Out of int64 range") + + +_assert_valid_dec(decode_varint_3) + +# import dis +# dis.dis(decode_varint_3) + +runner = pyperf.Runner() +# Encode algorithms returning a bytes result +for bench_func in [ + encode_varint_1, + encode_varint_2, + encode_varint_4]: + for i, value in enumerate(BENCH_VALUES_ENC): + runner.bench_func( + '{}_{}byte'.format(bench_func.__name__, i + 1), + bench_func, value) + +# Encode algorithms writing to the buffer +for bench_func in [ + encode_varint_3, + encode_varint_5, + encode_varint_6]: + for i, value in enumerate(BENCH_VALUES_ENC): + fname = bench_func.__name__ + runner.timeit( + '{}_{}byte'.format(fname, i + 1), + stmt="{}({}, buffer)".format(fname, value), + setup="from __main__ import {}; buffer = bytearray(10)".format( + fname) + ) + +# Size algorithms +for bench_func in [ + size_of_varint_1, + size_of_varint_2]: + for i, value in enumerate(BENCH_VALUES_ENC): + runner.bench_func( + '{}_{}byte'.format(bench_func.__name__, i + 1), + bench_func, value) + +# Decode algorithms +for bench_func in [ + decode_varint_1, + decode_varint_2, + decode_varint_3]: + for i, value in enumerate(BENCH_VALUES_DEC): + runner.bench_func( + '{}_{}byte'.format(bench_func.__name__, i + 1), + bench_func, value) diff --git a/testbed/dpkp__kafka-python/build_integration.sh b/testbed/dpkp__kafka-python/build_integration.sh new file mode 100644 index 0000000000000000000000000000000000000000..c020b0fe26a5c3f6bb565806496243403352008e --- /dev/null +++ b/testbed/dpkp__kafka-python/build_integration.sh @@ -0,0 +1,73 @@ +#!/bin/bash + +: ${ALL_RELEASES:="0.8.2.2 0.9.0.1 0.10.1.1 0.10.2.2 0.11.0.3 1.0.2 1.1.1 2.0.1 2.1.1 2.2.1 2.3.0 2.4.0 2.5.0"} +: ${SCALA_VERSION:=2.11} +: ${DIST_BASE_URL:=https://archive.apache.org/dist/kafka/} +: ${KAFKA_SRC_GIT:=https://github.com/apache/kafka.git} + +# On travis CI, empty KAFKA_VERSION means skip integration tests +# so we don't try to get binaries +# Otherwise it means test all official releases, so we get all of them! +if [ -z "$KAFKA_VERSION" -a -z "$TRAVIS" ]; then + KAFKA_VERSION=$ALL_RELEASES +fi + +pushd servers + mkdir -p dist + pushd dist + for kafka in $KAFKA_VERSION; do + if [ "$kafka" == "trunk" ]; then + if [ ! -d "$kafka" ]; then + git clone $KAFKA_SRC_GIT $kafka + fi + pushd $kafka + git pull + ./gradlew -PscalaVersion=$SCALA_VERSION -Pversion=$kafka releaseTarGz -x signArchives + popd + # Not sure how to construct the .tgz name accurately, so use a wildcard (ugh) + tar xzvf $kafka/core/build/distributions/kafka_*.tgz -C ../$kafka/ + rm $kafka/core/build/distributions/kafka_*.tgz + rm -rf ../$kafka/kafka-bin + mv ../$kafka/kafka_* ../$kafka/kafka-bin + else + echo "-------------------------------------" + echo "Checking kafka binaries for ${kafka}" + echo + if [ "$kafka" == "0.8.0" ]; then + KAFKA_ARTIFACT="kafka_2.8.0-${kafka}.tar.gz" + else if [ "$kafka" \> "2.4.0" ]; then + KAFKA_ARTIFACT="kafka_2.12-${kafka}.tgz" + else + KAFKA_ARTIFACT="kafka_${SCALA_VERSION}-${kafka}.tgz" + fi + fi + if [ ! -f "../$kafka/kafka-bin/bin/kafka-run-class.sh" ]; then + if [ -f "${KAFKA_ARTIFACT}" ]; then + echo "Using cached artifact: ${KAFKA_ARTIFACT}" + else + echo "Downloading kafka ${kafka} tarball" + TARBALL=${DIST_BASE_URL}${kafka}/${KAFKA_ARTIFACT} + if command -v wget 2>/dev/null; then + wget -N $TARBALL + else + echo "wget not found... using curl" + curl -f $TARBALL -o ${KAFKA_ARTIFACT} + fi + fi + echo + echo "Extracting kafka ${kafka} binaries" + tar xzvf ${KAFKA_ARTIFACT} -C ../$kafka/ + rm -rf ../$kafka/kafka-bin + mv ../$kafka/${KAFKA_ARTIFACT/%.t*/} ../$kafka/kafka-bin + if [ ! -f "../$kafka/kafka-bin/bin/kafka-run-class.sh" ]; then + echo "Extraction Failed ($kafka/kafka-bin/bin/kafka-run-class.sh does not exist)!" + exit 1 + fi + else + echo "$kafka is already installed in servers/$kafka/ -- skipping" + fi + fi + echo + done + popd +popd diff --git a/testbed/dpkp__kafka-python/example.py b/testbed/dpkp__kafka-python/example.py new file mode 100644 index 0000000000000000000000000000000000000000..9907450f633a4b0036925b59ad73efa5700a11d6 --- /dev/null +++ b/testbed/dpkp__kafka-python/example.py @@ -0,0 +1,82 @@ +#!/usr/bin/env python +import threading, time + +from kafka import KafkaAdminClient, KafkaConsumer, KafkaProducer +from kafka.admin import NewTopic + + +class Producer(threading.Thread): + def __init__(self): + threading.Thread.__init__(self) + self.stop_event = threading.Event() + + def stop(self): + self.stop_event.set() + + def run(self): + producer = KafkaProducer(bootstrap_servers='localhost:9092') + + while not self.stop_event.is_set(): + producer.send('my-topic', b"test") + producer.send('my-topic', b"\xc2Hola, mundo!") + time.sleep(1) + + producer.close() + + +class Consumer(threading.Thread): + def __init__(self): + threading.Thread.__init__(self) + self.stop_event = threading.Event() + + def stop(self): + self.stop_event.set() + + def run(self): + consumer = KafkaConsumer(bootstrap_servers='localhost:9092', + auto_offset_reset='earliest', + consumer_timeout_ms=1000) + consumer.subscribe(['my-topic']) + + while not self.stop_event.is_set(): + for message in consumer: + print(message) + if self.stop_event.is_set(): + break + + consumer.close() + + +def main(): + # Create 'my-topic' Kafka topic + try: + admin = KafkaAdminClient(bootstrap_servers='localhost:9092') + + topic = NewTopic(name='my-topic', + num_partitions=1, + replication_factor=1) + admin.create_topics([topic]) + except Exception: + pass + + tasks = [ + Producer(), + Consumer() + ] + + # Start threads of a publisher/producer and a subscriber/consumer to 'my-topic' Kafka topic + for t in tasks: + t.start() + + time.sleep(10) + + # Stop threads + for task in tasks: + task.stop() + + for task in tasks: + task.join() + + +if __name__ == "__main__": + main() diff --git a/testbed/dpkp__kafka-python/kafka/__init__.py b/testbed/dpkp__kafka-python/kafka/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5e30affa0ef08217ac678e79457f1cbc9919ea6 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/__init__.py @@ -0,0 +1,34 @@ +from __future__ import absolute_import + +__title__ = 'kafka' +from kafka.version import __version__ +__author__ = 'Dana Powers' +__license__ = 'Apache License 2.0' +__copyright__ = 'Copyright 2016 Dana Powers, David Arthur, and Contributors' + +# Set default logging handler to avoid "No handler found" warnings. +import logging +try: # Python 2.7+ + from logging import NullHandler +except ImportError: + class NullHandler(logging.Handler): + def emit(self, record): + pass + +logging.getLogger(__name__).addHandler(NullHandler()) + + +from kafka.admin import KafkaAdminClient +from kafka.client_async import KafkaClient +from kafka.consumer import KafkaConsumer +from kafka.consumer.subscription_state import ConsumerRebalanceListener +from kafka.producer import KafkaProducer +from kafka.conn import BrokerConnection +from kafka.serializer import Serializer, Deserializer +from kafka.structs import TopicPartition, OffsetAndMetadata + + +__all__ = [ + 'BrokerConnection', 'ConsumerRebalanceListener', 'KafkaAdminClient', + 'KafkaClient', 'KafkaConsumer', 'KafkaProducer', +] diff --git a/testbed/dpkp__kafka-python/kafka/admin/__init__.py b/testbed/dpkp__kafka-python/kafka/admin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c240fc6d009d287128b1e01070dc3d0c898fc94a --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/admin/__init__.py @@ -0,0 +1,14 @@ +from __future__ import absolute_import + +from kafka.admin.config_resource import ConfigResource, ConfigResourceType +from kafka.admin.client import KafkaAdminClient +from kafka.admin.acl_resource import (ACL, ACLFilter, ResourcePattern, ResourcePatternFilter, ACLOperation, + ResourceType, ACLPermissionType, ACLResourcePatternType) +from kafka.admin.new_topic import NewTopic +from kafka.admin.new_partitions import NewPartitions + +__all__ = [ + 'ConfigResource', 'ConfigResourceType', 'KafkaAdminClient', 'NewTopic', 'NewPartitions', 'ACL', 'ACLFilter', + 'ResourcePattern', 'ResourcePatternFilter', 'ACLOperation', 'ResourceType', 'ACLPermissionType', + 'ACLResourcePatternType' +] diff --git a/testbed/dpkp__kafka-python/kafka/admin/acl_resource.py b/testbed/dpkp__kafka-python/kafka/admin/acl_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..fd997a10a5265045f31e6e78baf7f7a2374db831 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/admin/acl_resource.py @@ -0,0 +1,244 @@ +from __future__ import absolute_import +from kafka.errors import IllegalArgumentError + +# enum in stdlib as of py3.4 +try: + from enum import IntEnum # pylint: disable=import-error +except ImportError: + # vendored backport module + from kafka.vendor.enum34 import IntEnum + + +class ResourceType(IntEnum): + """Type of kafka resource to set ACL for + + The ANY value is only valid in a filter context + """ + + UNKNOWN = 0, + ANY = 1, + CLUSTER = 4, + DELEGATION_TOKEN = 6, + GROUP = 3, + TOPIC = 2, + TRANSACTIONAL_ID = 5 + + +class ACLOperation(IntEnum): + """Type of operation + + The ANY value is only valid in a filter context + """ + + ANY = 1, + ALL = 2, + READ = 3, + WRITE = 4, + CREATE = 5, + DELETE = 6, + ALTER = 7, + DESCRIBE = 8, + CLUSTER_ACTION = 9, + DESCRIBE_CONFIGS = 10, + ALTER_CONFIGS = 11, + IDEMPOTENT_WRITE = 12 + + +class ACLPermissionType(IntEnum): + """An enumerated type of permissions + + The ANY value is only valid in a filter context + """ + + ANY = 1, + DENY = 2, + ALLOW = 3 + + +class ACLResourcePatternType(IntEnum): + """An enumerated type of resource patterns + + More details on the pattern types and how they work + can be found in KIP-290 (Support for prefixed ACLs) + https://cwiki.apache.org/confluence/display/KAFKA/KIP-290%3A+Support+for+Prefixed+ACLs + """ + + ANY = 1, + MATCH = 2, + LITERAL = 3, + PREFIXED = 4 + + +class ACLFilter(object): + """Represents a filter to use with describing and deleting ACLs + + The difference between this class and the ACL class is mainly that + we allow using ANY with the operation, permission, and resource type objects + to fetch ALCs matching any of the properties. + + To make a filter matching any principal, set principal to None + """ + + def __init__( + self, + principal, + host, + operation, + permission_type, + resource_pattern + ): + self.principal = principal + self.host = host + self.operation = operation + self.permission_type = permission_type + self.resource_pattern = resource_pattern + + self.validate() + + def validate(self): + if not isinstance(self.operation, ACLOperation): + raise IllegalArgumentError("operation must be an ACLOperation object, and cannot be ANY") + if not isinstance(self.permission_type, ACLPermissionType): + raise IllegalArgumentError("permission_type must be an ACLPermissionType object, and cannot be ANY") + if not isinstance(self.resource_pattern, ResourcePatternFilter): + raise IllegalArgumentError("resource_pattern must be a ResourcePatternFilter object") + + def __repr__(self): + return "".format( + principal=self.principal, + host=self.host, + operation=self.operation.name, + type=self.permission_type.name, + resource=self.resource_pattern + ) + + def __eq__(self, other): + return all(( + self.principal == other.principal, + self.host == other.host, + self.operation == other.operation, + self.permission_type == other.permission_type, + self.resource_pattern == other.resource_pattern + )) + + def __hash__(self): + return hash(( + self.principal, + self.host, + self.operation, + self.permission_type, + self.resource_pattern, + )) + + +class ACL(ACLFilter): + """Represents a concrete ACL for a specific ResourcePattern + + In kafka an ACL is a 4-tuple of (principal, host, operation, permission_type) + that limits who can do what on a specific resource (or since KIP-290 a resource pattern) + + Terminology: + Principal -> This is the identifier for the user. Depending on the authorization method used (SSL, SASL etc) + the principal will look different. See http://kafka.apache.org/documentation/#security_authz for details. + The principal must be on the format "User:" or kafka will treat it as invalid. It's possible to use + other principal types than "User" if using a custom authorizer for the cluster. + Host -> This must currently be an IP address. It cannot be a range, and it cannot be a domain name. + It can be set to "*", which is special cased in kafka to mean "any host" + Operation -> Which client operation this ACL refers to. Has different meaning depending + on the resource type the ACL refers to. See https://docs.confluent.io/current/kafka/authorization.html#acl-format + for a list of which combinations of resource/operation that unlocks which kafka APIs + Permission Type: Whether this ACL is allowing or denying access + Resource Pattern -> This is a representation of the resource or resource pattern that the ACL + refers to. See the ResourcePattern class for details. + + """ + + def __init__( + self, + principal, + host, + operation, + permission_type, + resource_pattern + ): + super(ACL, self).__init__(principal, host, operation, permission_type, resource_pattern) + self.validate() + + def validate(self): + if self.operation == ACLOperation.ANY: + raise IllegalArgumentError("operation cannot be ANY") + if self.permission_type == ACLPermissionType.ANY: + raise IllegalArgumentError("permission_type cannot be ANY") + if not isinstance(self.resource_pattern, ResourcePattern): + raise IllegalArgumentError("resource_pattern must be a ResourcePattern object") + + +class ResourcePatternFilter(object): + def __init__( + self, + resource_type, + resource_name, + pattern_type + ): + self.resource_type = resource_type + self.resource_name = resource_name + self.pattern_type = pattern_type + + self.validate() + + def validate(self): + if not isinstance(self.resource_type, ResourceType): + raise IllegalArgumentError("resource_type must be a ResourceType object") + if not isinstance(self.pattern_type, ACLResourcePatternType): + raise IllegalArgumentError("pattern_type must be an ACLResourcePatternType object") + + def __repr__(self): + return "".format( + self.resource_type.name, + self.resource_name, + self.pattern_type.name + ) + + def __eq__(self, other): + return all(( + self.resource_type == other.resource_type, + self.resource_name == other.resource_name, + self.pattern_type == other.pattern_type, + )) + + def __hash__(self): + return hash(( + self.resource_type, + self.resource_name, + self.pattern_type + )) + + +class ResourcePattern(ResourcePatternFilter): + """A resource pattern to apply the ACL to + + Resource patterns are used to be able to specify which resources an ACL + describes in a more flexible way than just pointing to a literal topic name for example. + Since KIP-290 (kafka 2.0) it's possible to set an ACL for a prefixed resource name, which + can cut down considerably on the number of ACLs needed when the number of topics and + consumer groups start to grow. + The default pattern_type is LITERAL, and it describes a specific resource. This is also how + ACLs worked before the introduction of prefixed ACLs + """ + + def __init__( + self, + resource_type, + resource_name, + pattern_type=ACLResourcePatternType.LITERAL + ): + super(ResourcePattern, self).__init__(resource_type, resource_name, pattern_type) + self.validate() + + def validate(self): + if self.resource_type == ResourceType.ANY: + raise IllegalArgumentError("resource_type cannot be ANY") + if self.pattern_type in [ACLResourcePatternType.ANY, ACLResourcePatternType.MATCH]: + raise IllegalArgumentError( + "pattern_type cannot be {} on a concrete ResourcePattern".format(self.pattern_type.name) + ) diff --git a/testbed/dpkp__kafka-python/kafka/admin/client.py b/testbed/dpkp__kafka-python/kafka/admin/client.py new file mode 100644 index 0000000000000000000000000000000000000000..c58da0c52a6da1a657dced0aa70bbb8b588a6d82 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/admin/client.py @@ -0,0 +1,1342 @@ +from __future__ import absolute_import + +from collections import defaultdict +import copy +import logging +import socket + +from . import ConfigResourceType +from kafka.vendor import six + +from kafka.admin.acl_resource import ACLOperation, ACLPermissionType, ACLFilter, ACL, ResourcePattern, ResourceType, \ + ACLResourcePatternType +from kafka.client_async import KafkaClient, selectors +from kafka.coordinator.protocol import ConsumerProtocolMemberMetadata, ConsumerProtocolMemberAssignment, ConsumerProtocol +import kafka.errors as Errors +from kafka.errors import ( + IncompatibleBrokerVersion, KafkaConfigurationError, NotControllerError, + UnrecognizedBrokerVersion, IllegalArgumentError) +from kafka.metrics import MetricConfig, Metrics +from kafka.protocol.admin import ( + CreateTopicsRequest, DeleteTopicsRequest, DescribeConfigsRequest, AlterConfigsRequest, CreatePartitionsRequest, + ListGroupsRequest, DescribeGroupsRequest, DescribeAclsRequest, CreateAclsRequest, DeleteAclsRequest, + DeleteGroupsRequest +) +from kafka.protocol.commit import GroupCoordinatorRequest, OffsetFetchRequest +from kafka.protocol.metadata import MetadataRequest +from kafka.protocol.types import Array +from kafka.structs import TopicPartition, OffsetAndMetadata, MemberInformation, GroupInformation +from kafka.version import __version__ + + +log = logging.getLogger(__name__) + + +class KafkaAdminClient(object): + """A class for administering the Kafka cluster. + + Warning: + This is an unstable interface that was recently added and is subject to + change without warning. In particular, many methods currently return + raw protocol tuples. In future releases, we plan to make these into + nicer, more pythonic objects. Unfortunately, this will likely break + those interfaces. + + The KafkaAdminClient class will negotiate for the latest version of each message + protocol format supported by both the kafka-python client library and the + Kafka broker. Usage of optional fields from protocol versions that are not + supported by the broker will result in IncompatibleBrokerVersion exceptions. + + Use of this class requires a minimum broker version >= 0.10.0.0. + + Keyword Arguments: + bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' + strings) that the consumer should contact to bootstrap initial + cluster metadata. This does not have to be the full node list. + It just needs to have at least one broker that will respond to a + Metadata API Request. Default port is 9092. If no servers are + specified, will default to localhost:9092. + client_id (str): a name for this client. This string is passed in + each request to servers and can be used to identify specific + server-side log entries that correspond to this client. Also + submitted to GroupCoordinator for logging with respect to + consumer group administration. Default: 'kafka-python-{version}' + reconnect_backoff_ms (int): The amount of time in milliseconds to + wait before attempting to reconnect to a given host. + Default: 50. + reconnect_backoff_max_ms (int): The maximum amount of time in + milliseconds to backoff/wait when reconnecting to a broker that has + repeatedly failed to connect. If provided, the backoff per host + will increase exponentially for each consecutive connection + failure, up to this maximum. Once the maximum is reached, + reconnection attempts will continue periodically with this fixed + rate. To avoid connection storms, a randomization factor of 0.2 + will be applied to the backoff resulting in a random range between + 20% below and 20% above the computed value. Default: 1000. + request_timeout_ms (int): Client request timeout in milliseconds. + Default: 30000. + connections_max_idle_ms: Close idle connections after the number of + milliseconds specified by this config. The broker closes idle + connections after connections.max.idle.ms, so this avoids hitting + unexpected socket disconnected errors on the client. + Default: 540000 + retry_backoff_ms (int): Milliseconds to backoff when retrying on + errors. Default: 100. + max_in_flight_requests_per_connection (int): Requests are pipelined + to kafka brokers up to this number of maximum requests per + broker connection. Default: 5. + receive_buffer_bytes (int): The size of the TCP receive buffer + (SO_RCVBUF) to use when reading data. Default: None (relies on + system defaults). Java client defaults to 32768. + send_buffer_bytes (int): The size of the TCP send buffer + (SO_SNDBUF) to use when sending data. Default: None (relies on + system defaults). Java client defaults to 131072. + socket_options (list): List of tuple-arguments to socket.setsockopt + to apply to broker connection sockets. Default: + [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] + metadata_max_age_ms (int): The period of time in milliseconds after + which we force a refresh of metadata even if we haven't seen any + partition leadership changes to proactively discover any new + brokers or partitions. Default: 300000 + security_protocol (str): Protocol used to communicate with brokers. + Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL. + Default: PLAINTEXT. + ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping + socket connections. If provided, all other ssl_* configurations + will be ignored. Default: None. + ssl_check_hostname (bool): Flag to configure whether SSL handshake + should verify that the certificate matches the broker's hostname. + Default: True. + ssl_cafile (str): Optional filename of CA file to use in certificate + verification. Default: None. + ssl_certfile (str): Optional filename of file in PEM format containing + the client certificate, as well as any CA certificates needed to + establish the certificate's authenticity. Default: None. + ssl_keyfile (str): Optional filename containing the client private key. + Default: None. + ssl_password (str): Optional password to be used when loading the + certificate chain. Default: None. + ssl_crlfile (str): Optional filename containing the CRL to check for + certificate expiration. By default, no CRL check is done. When + providing a file, only the leaf certificate will be checked against + this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+. + Default: None. + api_version (tuple): Specify which Kafka API version to use. If set + to None, KafkaClient will attempt to infer the broker version by + probing various APIs. Example: (0, 10, 2). Default: None + api_version_auto_timeout_ms (int): number of milliseconds to throw a + timeout exception from the constructor when checking the broker + api version. Only applies if api_version is None + selector (selectors.BaseSelector): Provide a specific selector + implementation to use for I/O multiplexing. + Default: selectors.DefaultSelector + metrics (kafka.metrics.Metrics): Optionally provide a metrics + instance for capturing network IO stats. Default: None. + metric_group_prefix (str): Prefix for metric names. Default: '' + sasl_mechanism (str): Authentication mechanism when security_protocol + is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are: + PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512. + sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_kerberos_service_name (str): Service name to include in GSSAPI + sasl mechanism handshake. Default: 'kafka' + sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI + sasl mechanism handshake. Default: one of bootstrap servers + sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider + instance. (See kafka.oauth.abstract). Default: None + + """ + DEFAULT_CONFIG = { + # client configs + 'bootstrap_servers': 'localhost', + 'client_id': 'kafka-python-' + __version__, + 'request_timeout_ms': 30000, + 'connections_max_idle_ms': 9 * 60 * 1000, + 'reconnect_backoff_ms': 50, + 'reconnect_backoff_max_ms': 1000, + 'max_in_flight_requests_per_connection': 5, + 'receive_buffer_bytes': None, + 'send_buffer_bytes': None, + 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)], + 'sock_chunk_bytes': 4096, # undocumented experimental option + 'sock_chunk_buffer_count': 1000, # undocumented experimental option + 'retry_backoff_ms': 100, + 'metadata_max_age_ms': 300000, + 'security_protocol': 'PLAINTEXT', + 'ssl_context': None, + 'ssl_check_hostname': True, + 'ssl_cafile': None, + 'ssl_certfile': None, + 'ssl_keyfile': None, + 'ssl_password': None, + 'ssl_crlfile': None, + 'api_version': None, + 'api_version_auto_timeout_ms': 2000, + 'selector': selectors.DefaultSelector, + 'sasl_mechanism': None, + 'sasl_plain_username': None, + 'sasl_plain_password': None, + 'sasl_kerberos_service_name': 'kafka', + 'sasl_kerberos_domain_name': None, + 'sasl_oauth_token_provider': None, + + # metrics configs + 'metric_reporters': [], + 'metrics_num_samples': 2, + 'metrics_sample_window_ms': 30000, + } + + def __init__(self, **configs): + log.debug("Starting KafkaAdminClient with configuration: %s", configs) + extra_configs = set(configs).difference(self.DEFAULT_CONFIG) + if extra_configs: + raise KafkaConfigurationError("Unrecognized configs: {}".format(extra_configs)) + + self.config = copy.copy(self.DEFAULT_CONFIG) + self.config.update(configs) + + # Configure metrics + metrics_tags = {'client-id': self.config['client_id']} + metric_config = MetricConfig(samples=self.config['metrics_num_samples'], + time_window_ms=self.config['metrics_sample_window_ms'], + tags=metrics_tags) + reporters = [reporter() for reporter in self.config['metric_reporters']] + self._metrics = Metrics(metric_config, reporters) + + self._client = KafkaClient(metrics=self._metrics, + metric_group_prefix='admin', + **self.config) + self._client.check_version(timeout=(self.config['api_version_auto_timeout_ms'] / 1000)) + + # Get auto-discovered version from client if necessary + if self.config['api_version'] is None: + self.config['api_version'] = self._client.config['api_version'] + + self._closed = False + self._refresh_controller_id() + log.debug("KafkaAdminClient started.") + + def close(self): + """Close the KafkaAdminClient connection to the Kafka broker.""" + if not hasattr(self, '_closed') or self._closed: + log.info("KafkaAdminClient already closed.") + return + + self._metrics.close() + self._client.close() + self._closed = True + log.debug("KafkaAdminClient is now closed.") + + def _matching_api_version(self, operation): + """Find the latest version of the protocol operation supported by both + this library and the broker. + + This resolves to the lesser of either the latest api version this + library supports, or the max version supported by the broker. + + :param operation: A list of protocol operation versions from kafka.protocol. + :return: The max matching version number between client and broker. + """ + broker_api_versions = self._client.get_api_versions() + api_key = operation[0].API_KEY + if broker_api_versions is None or api_key not in broker_api_versions: + raise IncompatibleBrokerVersion( + "Kafka broker does not support the '{}' Kafka protocol." + .format(operation[0].__name__)) + min_version, max_version = broker_api_versions[api_key] + version = min(len(operation) - 1, max_version) + if version < min_version: + # max library version is less than min broker version. Currently, + # no Kafka versions specify a min msg version. Maybe in the future? + raise IncompatibleBrokerVersion( + "No version of the '{}' Kafka protocol is supported by both the client and broker." + .format(operation[0].__name__)) + return version + + def _validate_timeout(self, timeout_ms): + """Validate the timeout is set or use the configuration default. + + :param timeout_ms: The timeout provided by api call, in milliseconds. + :return: The timeout to use for the operation. + """ + return timeout_ms or self.config['request_timeout_ms'] + + def _refresh_controller_id(self): + """Determine the Kafka cluster controller.""" + version = self._matching_api_version(MetadataRequest) + if 1 <= version <= 6: + request = MetadataRequest[version]() + future = self._send_request_to_node(self._client.least_loaded_node(), request) + + self._wait_for_futures([future]) + + response = future.value + controller_id = response.controller_id + # verify the controller is new enough to support our requests + controller_version = self._client.check_version(controller_id, timeout=(self.config['api_version_auto_timeout_ms'] / 1000)) + if controller_version < (0, 10, 0): + raise IncompatibleBrokerVersion( + "The controller appears to be running Kafka {}. KafkaAdminClient requires brokers >= 0.10.0.0." + .format(controller_version)) + self._controller_id = controller_id + else: + raise UnrecognizedBrokerVersion( + "Kafka Admin interface cannot determine the controller using MetadataRequest_v{}." + .format(version)) + + def _find_coordinator_id_send_request(self, group_id): + """Send a FindCoordinatorRequest to a broker. + + :param group_id: The consumer group ID. This is typically the group + name as a string. + :return: A message future + """ + # TODO add support for dynamically picking version of + # GroupCoordinatorRequest which was renamed to FindCoordinatorRequest. + # When I experimented with this, the coordinator value returned in + # GroupCoordinatorResponse_v1 didn't match the value returned by + # GroupCoordinatorResponse_v0 and I couldn't figure out why. + version = 0 + # version = self._matching_api_version(GroupCoordinatorRequest) + if version <= 0: + request = GroupCoordinatorRequest[version](group_id) + else: + raise NotImplementedError( + "Support for GroupCoordinatorRequest_v{} has not yet been added to KafkaAdminClient." + .format(version)) + return self._send_request_to_node(self._client.least_loaded_node(), request) + + def _find_coordinator_id_process_response(self, response): + """Process a FindCoordinatorResponse. + + :param response: a FindCoordinatorResponse. + :return: The node_id of the broker that is the coordinator. + """ + if response.API_VERSION <= 0: + error_type = Errors.for_code(response.error_code) + if error_type is not Errors.NoError: + # Note: When error_type.retriable, Java will retry... see + # KafkaAdminClient's handleFindCoordinatorError method + raise error_type( + "FindCoordinatorRequest failed with response '{}'." + .format(response)) + else: + raise NotImplementedError( + "Support for FindCoordinatorRequest_v{} has not yet been added to KafkaAdminClient." + .format(response.API_VERSION)) + return response.coordinator_id + + def _find_coordinator_ids(self, group_ids): + """Find the broker node_ids of the coordinators of the given groups. + + Sends a FindCoordinatorRequest message to the cluster for each group_id. + Will block until the FindCoordinatorResponse is received for all groups. + Any errors are immediately raised. + + :param group_ids: A list of consumer group IDs. This is typically the group + name as a string. + :return: A dict of {group_id: node_id} where node_id is the id of the + broker that is the coordinator for the corresponding group. + """ + groups_futures = { + group_id: self._find_coordinator_id_send_request(group_id) + for group_id in group_ids + } + self._wait_for_futures(groups_futures.values()) + groups_coordinators = { + group_id: self._find_coordinator_id_process_response(future.value) + for group_id, future in groups_futures.items() + } + return groups_coordinators + + def _send_request_to_node(self, node_id, request): + """Send a Kafka protocol message to a specific broker. + + Returns a future that may be polled for status and results. + + :param node_id: The broker id to which to send the message. + :param request: The message to send. + :return: A future object that may be polled for status and results. + :exception: The exception if the message could not be sent. + """ + while not self._client.ready(node_id): + # poll until the connection to broker is ready, otherwise send() + # will fail with NodeNotReadyError + self._client.poll() + return self._client.send(node_id, request) + + def _send_request_to_controller(self, request): + """Send a Kafka protocol message to the cluster controller. + + Will block until the message result is received. + + :param request: The message to send. + :return: The Kafka protocol response for the message. + """ + tries = 2 # in case our cached self._controller_id is outdated + while tries: + tries -= 1 + future = self._send_request_to_node(self._controller_id, request) + + self._wait_for_futures([future]) + + response = future.value + # In Java, the error field name is inconsistent: + # - CreateTopicsResponse / CreatePartitionsResponse uses topic_errors + # - DeleteTopicsResponse uses topic_error_codes + # So this is a little brittle in that it assumes all responses have + # one of these attributes and that they always unpack into + # (topic, error_code) tuples. + topic_error_tuples = (response.topic_errors if hasattr(response, 'topic_errors') + else response.topic_error_codes) + # Also small py2/py3 compatibility -- py3 can ignore extra values + # during unpack via: for x, y, *rest in list_of_values. py2 cannot. + # So for now we have to map across the list and explicitly drop any + # extra values (usually the error_message) + for topic, error_code in map(lambda e: e[:2], topic_error_tuples): + error_type = Errors.for_code(error_code) + if tries and error_type is NotControllerError: + # No need to inspect the rest of the errors for + # non-retriable errors because NotControllerError should + # either be thrown for all errors or no errors. + self._refresh_controller_id() + break + elif error_type is not Errors.NoError: + raise error_type( + "Request '{}' failed with response '{}'." + .format(request, response)) + else: + return response + raise RuntimeError("This should never happen, please file a bug with full stacktrace if encountered") + + @staticmethod + def _convert_new_topic_request(new_topic): + return ( + new_topic.name, + new_topic.num_partitions, + new_topic.replication_factor, + [ + (partition_id, replicas) for partition_id, replicas in new_topic.replica_assignments.items() + ], + [ + (config_key, config_value) for config_key, config_value in new_topic.topic_configs.items() + ] + ) + + def create_topics(self, new_topics, timeout_ms=None, validate_only=False): + """Create new topics in the cluster. + + :param new_topics: A list of NewTopic objects. + :param timeout_ms: Milliseconds to wait for new topics to be created + before the broker returns. + :param validate_only: If True, don't actually create new topics. + Not supported by all versions. Default: False + :return: Appropriate version of CreateTopicResponse class. + """ + version = self._matching_api_version(CreateTopicsRequest) + timeout_ms = self._validate_timeout(timeout_ms) + if version == 0: + if validate_only: + raise IncompatibleBrokerVersion( + "validate_only requires CreateTopicsRequest >= v1, which is not supported by Kafka {}." + .format(self.config['api_version'])) + request = CreateTopicsRequest[version]( + create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics], + timeout=timeout_ms + ) + elif version <= 3: + request = CreateTopicsRequest[version]( + create_topic_requests=[self._convert_new_topic_request(new_topic) for new_topic in new_topics], + timeout=timeout_ms, + validate_only=validate_only + ) + else: + raise NotImplementedError( + "Support for CreateTopics v{} has not yet been added to KafkaAdminClient." + .format(version)) + # TODO convert structs to a more pythonic interface + # TODO raise exceptions if errors + return self._send_request_to_controller(request) + + def delete_topics(self, topics, timeout_ms=None): + """Delete topics from the cluster. + + :param topics: A list of topic name strings. + :param timeout_ms: Milliseconds to wait for topics to be deleted + before the broker returns. + :return: Appropriate version of DeleteTopicsResponse class. + """ + version = self._matching_api_version(DeleteTopicsRequest) + timeout_ms = self._validate_timeout(timeout_ms) + if version <= 3: + request = DeleteTopicsRequest[version]( + topics=topics, + timeout=timeout_ms + ) + response = self._send_request_to_controller(request) + else: + raise NotImplementedError( + "Support for DeleteTopics v{} has not yet been added to KafkaAdminClient." + .format(version)) + return response + + + def _get_cluster_metadata(self, topics=None, auto_topic_creation=False): + """ + topics == None means "get all topics" + """ + version = self._matching_api_version(MetadataRequest) + if version <= 3: + if auto_topic_creation: + raise IncompatibleBrokerVersion( + "auto_topic_creation requires MetadataRequest >= v4, which" + " is not supported by Kafka {}" + .format(self.config['api_version'])) + + request = MetadataRequest[version](topics=topics) + elif version <= 5: + request = MetadataRequest[version]( + topics=topics, + allow_auto_topic_creation=auto_topic_creation + ) + + future = self._send_request_to_node( + self._client.least_loaded_node(), + request + ) + self._wait_for_futures([future]) + return future.value + + def list_topics(self): + metadata = self._get_cluster_metadata(topics=None) + obj = metadata.to_object() + return [t['topic'] for t in obj['topics']] + + def describe_topics(self, topics=None): + metadata = self._get_cluster_metadata(topics=topics) + obj = metadata.to_object() + return obj['topics'] + + def describe_cluster(self): + metadata = self._get_cluster_metadata() + obj = metadata.to_object() + obj.pop('topics') # We have 'describe_topics' for this + return obj + + @staticmethod + def _convert_describe_acls_response_to_acls(describe_response): + version = describe_response.API_VERSION + + error = Errors.for_code(describe_response.error_code) + acl_list = [] + for resources in describe_response.resources: + if version == 0: + resource_type, resource_name, acls = resources + resource_pattern_type = ACLResourcePatternType.LITERAL.value + elif version <= 1: + resource_type, resource_name, resource_pattern_type, acls = resources + else: + raise NotImplementedError( + "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin." + .format(version) + ) + for acl in acls: + principal, host, operation, permission_type = acl + conv_acl = ACL( + principal=principal, + host=host, + operation=ACLOperation(operation), + permission_type=ACLPermissionType(permission_type), + resource_pattern=ResourcePattern( + ResourceType(resource_type), + resource_name, + ACLResourcePatternType(resource_pattern_type) + ) + ) + acl_list.append(conv_acl) + + return (acl_list, error,) + + def describe_acls(self, acl_filter): + """Describe a set of ACLs + + Used to return a set of ACLs matching the supplied ACLFilter. + The cluster must be configured with an authorizer for this to work, or + you will get a SecurityDisabledError + + :param acl_filter: an ACLFilter object + :return: tuple of a list of matching ACL objects and a KafkaError (NoError if successful) + """ + + version = self._matching_api_version(DescribeAclsRequest) + if version == 0: + request = DescribeAclsRequest[version]( + resource_type=acl_filter.resource_pattern.resource_type, + resource_name=acl_filter.resource_pattern.resource_name, + principal=acl_filter.principal, + host=acl_filter.host, + operation=acl_filter.operation, + permission_type=acl_filter.permission_type + ) + elif version <= 1: + request = DescribeAclsRequest[version]( + resource_type=acl_filter.resource_pattern.resource_type, + resource_name=acl_filter.resource_pattern.resource_name, + resource_pattern_type_filter=acl_filter.resource_pattern.pattern_type, + principal=acl_filter.principal, + host=acl_filter.host, + operation=acl_filter.operation, + permission_type=acl_filter.permission_type + + ) + else: + raise NotImplementedError( + "Support for DescribeAcls v{} has not yet been added to KafkaAdmin." + .format(version) + ) + + future = self._send_request_to_node(self._client.least_loaded_node(), request) + self._wait_for_futures([future]) + response = future.value + + error_type = Errors.for_code(response.error_code) + if error_type is not Errors.NoError: + # optionally we could retry if error_type.retriable + raise error_type( + "Request '{}' failed with response '{}'." + .format(request, response)) + + return self._convert_describe_acls_response_to_acls(response) + + @staticmethod + def _convert_create_acls_resource_request_v0(acl): + + return ( + acl.resource_pattern.resource_type, + acl.resource_pattern.resource_name, + acl.principal, + acl.host, + acl.operation, + acl.permission_type + ) + + @staticmethod + def _convert_create_acls_resource_request_v1(acl): + + return ( + acl.resource_pattern.resource_type, + acl.resource_pattern.resource_name, + acl.resource_pattern.pattern_type, + acl.principal, + acl.host, + acl.operation, + acl.permission_type + ) + + @staticmethod + def _convert_create_acls_response_to_acls(acls, create_response): + version = create_response.API_VERSION + + creations_error = [] + creations_success = [] + for i, creations in enumerate(create_response.creation_responses): + if version <= 1: + error_code, error_message = creations + acl = acls[i] + error = Errors.for_code(error_code) + else: + raise NotImplementedError( + "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin." + .format(version) + ) + + if error is Errors.NoError: + creations_success.append(acl) + else: + creations_error.append((acl, error,)) + + return {"succeeded": creations_success, "failed": creations_error} + + def create_acls(self, acls): + """Create a list of ACLs + + This endpoint only accepts a list of concrete ACL objects, no ACLFilters. + Throws TopicAlreadyExistsError if topic is already present. + + :param acls: a list of ACL objects + :return: dict of successes and failures + """ + + for acl in acls: + if not isinstance(acl, ACL): + raise IllegalArgumentError("acls must contain ACL objects") + + version = self._matching_api_version(CreateAclsRequest) + if version == 0: + request = CreateAclsRequest[version]( + creations=[self._convert_create_acls_resource_request_v0(acl) for acl in acls] + ) + elif version <= 1: + request = CreateAclsRequest[version]( + creations=[self._convert_create_acls_resource_request_v1(acl) for acl in acls] + ) + else: + raise NotImplementedError( + "Support for CreateAcls v{} has not yet been added to KafkaAdmin." + .format(version) + ) + + future = self._send_request_to_node(self._client.least_loaded_node(), request) + self._wait_for_futures([future]) + response = future.value + + return self._convert_create_acls_response_to_acls(acls, response) + + @staticmethod + def _convert_delete_acls_resource_request_v0(acl): + return ( + acl.resource_pattern.resource_type, + acl.resource_pattern.resource_name, + acl.principal, + acl.host, + acl.operation, + acl.permission_type + ) + + @staticmethod + def _convert_delete_acls_resource_request_v1(acl): + return ( + acl.resource_pattern.resource_type, + acl.resource_pattern.resource_name, + acl.resource_pattern.pattern_type, + acl.principal, + acl.host, + acl.operation, + acl.permission_type + ) + + @staticmethod + def _convert_delete_acls_response_to_matching_acls(acl_filters, delete_response): + version = delete_response.API_VERSION + filter_result_list = [] + for i, filter_responses in enumerate(delete_response.filter_responses): + filter_error_code, filter_error_message, matching_acls = filter_responses + filter_error = Errors.for_code(filter_error_code) + acl_result_list = [] + for acl in matching_acls: + if version == 0: + error_code, error_message, resource_type, resource_name, principal, host, operation, permission_type = acl + resource_pattern_type = ACLResourcePatternType.LITERAL.value + elif version == 1: + error_code, error_message, resource_type, resource_name, resource_pattern_type, principal, host, operation, permission_type = acl + else: + raise NotImplementedError( + "Support for DescribeAcls Response v{} has not yet been added to KafkaAdmin." + .format(version) + ) + acl_error = Errors.for_code(error_code) + conv_acl = ACL( + principal=principal, + host=host, + operation=ACLOperation(operation), + permission_type=ACLPermissionType(permission_type), + resource_pattern=ResourcePattern( + ResourceType(resource_type), + resource_name, + ACLResourcePatternType(resource_pattern_type) + ) + ) + acl_result_list.append((conv_acl, acl_error,)) + filter_result_list.append((acl_filters[i], acl_result_list, filter_error,)) + return filter_result_list + + def delete_acls(self, acl_filters): + """Delete a set of ACLs + + Deletes all ACLs matching the list of input ACLFilter + + :param acl_filters: a list of ACLFilter + :return: a list of 3-tuples corresponding to the list of input filters. + The tuples hold (the input ACLFilter, list of affected ACLs, KafkaError instance) + """ + + for acl in acl_filters: + if not isinstance(acl, ACLFilter): + raise IllegalArgumentError("acl_filters must contain ACLFilter type objects") + + version = self._matching_api_version(DeleteAclsRequest) + + if version == 0: + request = DeleteAclsRequest[version]( + filters=[self._convert_delete_acls_resource_request_v0(acl) for acl in acl_filters] + ) + elif version <= 1: + request = DeleteAclsRequest[version]( + filters=[self._convert_delete_acls_resource_request_v1(acl) for acl in acl_filters] + ) + else: + raise NotImplementedError( + "Support for DeleteAcls v{} has not yet been added to KafkaAdmin." + .format(version) + ) + + future = self._send_request_to_node(self._client.least_loaded_node(), request) + self._wait_for_futures([future]) + response = future.value + + return self._convert_delete_acls_response_to_matching_acls(acl_filters, response) + + @staticmethod + def _convert_describe_config_resource_request(config_resource): + return ( + config_resource.resource_type, + config_resource.name, + [ + config_key for config_key, config_value in config_resource.configs.items() + ] if config_resource.configs else None + ) + + def describe_configs(self, config_resources, include_synonyms=False): + """Fetch configuration parameters for one or more Kafka resources. + + :param config_resources: An list of ConfigResource objects. + Any keys in ConfigResource.configs dict will be used to filter the + result. Setting the configs dict to None will get all values. An + empty dict will get zero values (as per Kafka protocol). + :param include_synonyms: If True, return synonyms in response. Not + supported by all versions. Default: False. + :return: Appropriate version of DescribeConfigsResponse class. + """ + + # Break up requests by type - a broker config request must be sent to the specific broker. + # All other (currently just topic resources) can be sent to any broker. + broker_resources = [] + topic_resources = [] + + for config_resource in config_resources: + if config_resource.resource_type == ConfigResourceType.BROKER: + broker_resources.append(self._convert_describe_config_resource_request(config_resource)) + else: + topic_resources.append(self._convert_describe_config_resource_request(config_resource)) + + futures = [] + version = self._matching_api_version(DescribeConfigsRequest) + if version == 0: + if include_synonyms: + raise IncompatibleBrokerVersion( + "include_synonyms requires DescribeConfigsRequest >= v1, which is not supported by Kafka {}." + .format(self.config['api_version'])) + + if len(broker_resources) > 0: + for broker_resource in broker_resources: + try: + broker_id = int(broker_resource[1]) + except ValueError: + raise ValueError("Broker resource names must be an integer or a string represented integer") + + futures.append(self._send_request_to_node( + broker_id, + DescribeConfigsRequest[version](resources=[broker_resource]) + )) + + if len(topic_resources) > 0: + futures.append(self._send_request_to_node( + self._client.least_loaded_node(), + DescribeConfigsRequest[version](resources=topic_resources) + )) + + elif version <= 2: + if len(broker_resources) > 0: + for broker_resource in broker_resources: + try: + broker_id = int(broker_resource[1]) + except ValueError: + raise ValueError("Broker resource names must be an integer or a string represented integer") + + futures.append(self._send_request_to_node( + broker_id, + DescribeConfigsRequest[version]( + resources=[broker_resource], + include_synonyms=include_synonyms) + )) + + if len(topic_resources) > 0: + futures.append(self._send_request_to_node( + self._client.least_loaded_node(), + DescribeConfigsRequest[version](resources=topic_resources, include_synonyms=include_synonyms) + )) + else: + raise NotImplementedError( + "Support for DescribeConfigs v{} has not yet been added to KafkaAdminClient.".format(version)) + + self._wait_for_futures(futures) + return [f.value for f in futures] + + @staticmethod + def _convert_alter_config_resource_request(config_resource): + return ( + config_resource.resource_type, + config_resource.name, + [ + (config_key, config_value) for config_key, config_value in config_resource.configs.items() + ] + ) + + def alter_configs(self, config_resources): + """Alter configuration parameters of one or more Kafka resources. + + Warning: + This is currently broken for BROKER resources because those must be + sent to that specific broker, versus this always picks the + least-loaded node. See the comment in the source code for details. + We would happily accept a PR fixing this. + + :param config_resources: A list of ConfigResource objects. + :return: Appropriate version of AlterConfigsResponse class. + """ + version = self._matching_api_version(AlterConfigsRequest) + if version <= 1: + request = AlterConfigsRequest[version]( + resources=[self._convert_alter_config_resource_request(config_resource) for config_resource in config_resources] + ) + else: + raise NotImplementedError( + "Support for AlterConfigs v{} has not yet been added to KafkaAdminClient." + .format(version)) + # TODO the Java client has the note: + # // We must make a separate AlterConfigs request for every BROKER resource we want to alter + # // and send the request to that specific broker. Other resources are grouped together into + # // a single request that may be sent to any broker. + # + # So this is currently broken as it always sends to the least_loaded_node() + future = self._send_request_to_node(self._client.least_loaded_node(), request) + + self._wait_for_futures([future]) + response = future.value + return response + + # alter replica logs dir protocol not yet implemented + # Note: have to lookup the broker with the replica assignment and send the request to that broker + + # describe log dirs protocol not yet implemented + # Note: have to lookup the broker with the replica assignment and send the request to that broker + + @staticmethod + def _convert_create_partitions_request(topic_name, new_partitions): + return ( + topic_name, + ( + new_partitions.total_count, + new_partitions.new_assignments + ) + ) + + def create_partitions(self, topic_partitions, timeout_ms=None, validate_only=False): + """Create additional partitions for an existing topic. + + :param topic_partitions: A map of topic name strings to NewPartition objects. + :param timeout_ms: Milliseconds to wait for new partitions to be + created before the broker returns. + :param validate_only: If True, don't actually create new partitions. + Default: False + :return: Appropriate version of CreatePartitionsResponse class. + """ + version = self._matching_api_version(CreatePartitionsRequest) + timeout_ms = self._validate_timeout(timeout_ms) + if version <= 1: + request = CreatePartitionsRequest[version]( + topic_partitions=[self._convert_create_partitions_request(topic_name, new_partitions) for topic_name, new_partitions in topic_partitions.items()], + timeout=timeout_ms, + validate_only=validate_only + ) + else: + raise NotImplementedError( + "Support for CreatePartitions v{} has not yet been added to KafkaAdminClient." + .format(version)) + return self._send_request_to_controller(request) + + # delete records protocol not yet implemented + # Note: send the request to the partition leaders + + # create delegation token protocol not yet implemented + # Note: send the request to the least_loaded_node() + + # renew delegation token protocol not yet implemented + # Note: send the request to the least_loaded_node() + + # expire delegation_token protocol not yet implemented + # Note: send the request to the least_loaded_node() + + # describe delegation_token protocol not yet implemented + # Note: send the request to the least_loaded_node() + + def _describe_consumer_groups_send_request(self, group_id, group_coordinator_id, include_authorized_operations=False): + """Send a DescribeGroupsRequest to the group's coordinator. + + :param group_id: The group name as a string + :param group_coordinator_id: The node_id of the groups' coordinator + broker. + :return: A message future. + """ + version = self._matching_api_version(DescribeGroupsRequest) + if version <= 2: + if include_authorized_operations: + raise IncompatibleBrokerVersion( + "include_authorized_operations requests " + "DescribeGroupsRequest >= v3, which is not " + "supported by Kafka {}".format(version) + ) + # Note: KAFKA-6788 A potential optimization is to group the + # request per coordinator and send one request with a list of + # all consumer groups. Java still hasn't implemented this + # because the error checking is hard to get right when some + # groups error and others don't. + request = DescribeGroupsRequest[version](groups=(group_id,)) + elif version <= 3: + request = DescribeGroupsRequest[version]( + groups=(group_id,), + include_authorized_operations=include_authorized_operations + ) + else: + raise NotImplementedError( + "Support for DescribeGroupsRequest_v{} has not yet been added to KafkaAdminClient." + .format(version)) + return self._send_request_to_node(group_coordinator_id, request) + + def _describe_consumer_groups_process_response(self, response): + """Process a DescribeGroupsResponse into a group description.""" + if response.API_VERSION <= 3: + assert len(response.groups) == 1 + for response_field, response_name in zip(response.SCHEMA.fields, response.SCHEMA.names): + if isinstance(response_field, Array): + described_groups_field_schema = response_field.array_of + described_group = response.__dict__[response_name][0] + described_group_information_list = [] + protocol_type_is_consumer = False + for (described_group_information, group_information_name, group_information_field) in zip(described_group, described_groups_field_schema.names, described_groups_field_schema.fields): + if group_information_name == 'protocol_type': + protocol_type = described_group_information + protocol_type_is_consumer = (protocol_type == ConsumerProtocol.PROTOCOL_TYPE or not protocol_type) + if isinstance(group_information_field, Array): + member_information_list = [] + member_schema = group_information_field.array_of + for members in described_group_information: + member_information = [] + for (member, member_field, member_name) in zip(members, member_schema.fields, member_schema.names): + if protocol_type_is_consumer: + if member_name == 'member_metadata' and member: + member_information.append(ConsumerProtocolMemberMetadata.decode(member)) + elif member_name == 'member_assignment' and member: + member_information.append(ConsumerProtocolMemberAssignment.decode(member)) + else: + member_information.append(member) + member_info_tuple = MemberInformation._make(member_information) + member_information_list.append(member_info_tuple) + described_group_information_list.append(member_information_list) + else: + described_group_information_list.append(described_group_information) + # Version 3 of the DescribeGroups API introduced the "authorized_operations" field. + # This will cause the namedtuple to fail. + # Therefore, appending a placeholder of None in it. + if response.API_VERSION <=2: + described_group_information_list.append(None) + group_description = GroupInformation._make(described_group_information_list) + error_code = group_description.error_code + error_type = Errors.for_code(error_code) + # Java has the note: KAFKA-6789, we can retry based on the error code + if error_type is not Errors.NoError: + raise error_type( + "DescribeGroupsResponse failed with response '{}'." + .format(response)) + else: + raise NotImplementedError( + "Support for DescribeGroupsResponse_v{} has not yet been added to KafkaAdminClient." + .format(response.API_VERSION)) + return group_description + + def describe_consumer_groups(self, group_ids, group_coordinator_id=None, include_authorized_operations=False): + """Describe a set of consumer groups. + + Any errors are immediately raised. + + :param group_ids: A list of consumer group IDs. These are typically the + group names as strings. + :param group_coordinator_id: The node_id of the groups' coordinator + broker. If set to None, it will query the cluster for each group to + find that group's coordinator. Explicitly specifying this can be + useful for avoiding extra network round trips if you already know + the group coordinator. This is only useful when all the group_ids + have the same coordinator, otherwise it will error. Default: None. + :param include_authorized_operations: Whether or not to include + information about the operations a group is allowed to perform. + Only supported on API version >= v3. Default: False. + :return: A list of group descriptions. For now the group descriptions + are the raw results from the DescribeGroupsResponse. Long-term, we + plan to change this to return namedtuples as well as decoding the + partition assignments. + """ + group_descriptions = [] + + if group_coordinator_id is not None: + groups_coordinators = {group_id: group_coordinator_id for group_id in group_ids} + else: + groups_coordinators = self._find_coordinator_ids(group_ids) + + futures = [ + self._describe_consumer_groups_send_request( + group_id, + coordinator_id, + include_authorized_operations) + for group_id, coordinator_id in groups_coordinators.items() + ] + self._wait_for_futures(futures) + + for future in futures: + response = future.value + group_description = self._describe_consumer_groups_process_response(response) + group_descriptions.append(group_description) + + return group_descriptions + + def _list_consumer_groups_send_request(self, broker_id): + """Send a ListGroupsRequest to a broker. + + :param broker_id: The broker's node_id. + :return: A message future + """ + version = self._matching_api_version(ListGroupsRequest) + if version <= 2: + request = ListGroupsRequest[version]() + else: + raise NotImplementedError( + "Support for ListGroupsRequest_v{} has not yet been added to KafkaAdminClient." + .format(version)) + return self._send_request_to_node(broker_id, request) + + def _list_consumer_groups_process_response(self, response): + """Process a ListGroupsResponse into a list of groups.""" + if response.API_VERSION <= 2: + error_type = Errors.for_code(response.error_code) + if error_type is not Errors.NoError: + raise error_type( + "ListGroupsRequest failed with response '{}'." + .format(response)) + else: + raise NotImplementedError( + "Support for ListGroupsResponse_v{} has not yet been added to KafkaAdminClient." + .format(response.API_VERSION)) + return response.groups + + def list_consumer_groups(self, broker_ids=None): + """List all consumer groups known to the cluster. + + This returns a list of Consumer Group tuples. The tuples are + composed of the consumer group name and the consumer group protocol + type. + + Only consumer groups that store their offsets in Kafka are returned. + The protocol type will be an empty string for groups created using + Kafka < 0.9 APIs because, although they store their offsets in Kafka, + they don't use Kafka for group coordination. For groups created using + Kafka >= 0.9, the protocol type will typically be "consumer". + + As soon as any error is encountered, it is immediately raised. + + :param broker_ids: A list of broker node_ids to query for consumer + groups. If set to None, will query all brokers in the cluster. + Explicitly specifying broker(s) can be useful for determining which + consumer groups are coordinated by those broker(s). Default: None + :return list: List of tuples of Consumer Groups. + :exception GroupCoordinatorNotAvailableError: The coordinator is not + available, so cannot process requests. + :exception GroupLoadInProgressError: The coordinator is loading and + hence can't process requests. + """ + # While we return a list, internally use a set to prevent duplicates + # because if a group coordinator fails after being queried, and its + # consumer groups move to new brokers that haven't yet been queried, + # then the same group could be returned by multiple brokers. + consumer_groups = set() + if broker_ids is None: + broker_ids = [broker.nodeId for broker in self._client.cluster.brokers()] + futures = [self._list_consumer_groups_send_request(b) for b in broker_ids] + self._wait_for_futures(futures) + for f in futures: + response = f.value + consumer_groups.update(self._list_consumer_groups_process_response(response)) + return list(consumer_groups) + + def _list_consumer_group_offsets_send_request(self, group_id, + group_coordinator_id, partitions=None): + """Send an OffsetFetchRequest to a broker. + + :param group_id: The consumer group id name for which to fetch offsets. + :param group_coordinator_id: The node_id of the group's coordinator + broker. + :return: A message future + """ + version = self._matching_api_version(OffsetFetchRequest) + if version <= 3: + if partitions is None: + if version <= 1: + raise ValueError( + """OffsetFetchRequest_v{} requires specifying the + partitions for which to fetch offsets. Omitting the + partitions is only supported on brokers >= 0.10.2. + For details, see KIP-88.""".format(version)) + topics_partitions = None + else: + # transform from [TopicPartition("t1", 1), TopicPartition("t1", 2)] to [("t1", [1, 2])] + topics_partitions_dict = defaultdict(set) + for topic, partition in partitions: + topics_partitions_dict[topic].add(partition) + topics_partitions = list(six.iteritems(topics_partitions_dict)) + request = OffsetFetchRequest[version](group_id, topics_partitions) + else: + raise NotImplementedError( + "Support for OffsetFetchRequest_v{} has not yet been added to KafkaAdminClient." + .format(version)) + return self._send_request_to_node(group_coordinator_id, request) + + def _list_consumer_group_offsets_process_response(self, response): + """Process an OffsetFetchResponse. + + :param response: an OffsetFetchResponse. + :return: A dictionary composed of TopicPartition keys and + OffsetAndMetada values. + """ + if response.API_VERSION <= 3: + + # OffsetFetchResponse_v1 lacks a top-level error_code + if response.API_VERSION > 1: + error_type = Errors.for_code(response.error_code) + if error_type is not Errors.NoError: + # optionally we could retry if error_type.retriable + raise error_type( + "OffsetFetchResponse failed with response '{}'." + .format(response)) + + # transform response into a dictionary with TopicPartition keys and + # OffsetAndMetada values--this is what the Java AdminClient returns + offsets = {} + for topic, partitions in response.topics: + for partition, offset, metadata, error_code in partitions: + error_type = Errors.for_code(error_code) + if error_type is not Errors.NoError: + raise error_type( + "Unable to fetch consumer group offsets for topic {}, partition {}" + .format(topic, partition)) + offsets[TopicPartition(topic, partition)] = OffsetAndMetadata(offset, metadata) + else: + raise NotImplementedError( + "Support for OffsetFetchResponse_v{} has not yet been added to KafkaAdminClient." + .format(response.API_VERSION)) + return offsets + + def list_consumer_group_offsets(self, group_id, group_coordinator_id=None, + partitions=None): + """Fetch Consumer Offsets for a single consumer group. + + Note: + This does not verify that the group_id or partitions actually exist + in the cluster. + + As soon as any error is encountered, it is immediately raised. + + :param group_id: The consumer group id name for which to fetch offsets. + :param group_coordinator_id: The node_id of the group's coordinator + broker. If set to None, will query the cluster to find the group + coordinator. Explicitly specifying this can be useful to prevent + that extra network round trip if you already know the group + coordinator. Default: None. + :param partitions: A list of TopicPartitions for which to fetch + offsets. On brokers >= 0.10.2, this can be set to None to fetch all + known offsets for the consumer group. Default: None. + :return dictionary: A dictionary with TopicPartition keys and + OffsetAndMetada values. Partitions that are not specified and for + which the group_id does not have a recorded offset are omitted. An + offset value of `-1` indicates the group_id has no offset for that + TopicPartition. A `-1` can only happen for partitions that are + explicitly specified. + """ + if group_coordinator_id is None: + group_coordinator_id = self._find_coordinator_ids([group_id])[group_id] + future = self._list_consumer_group_offsets_send_request( + group_id, group_coordinator_id, partitions) + self._wait_for_futures([future]) + response = future.value + return self._list_consumer_group_offsets_process_response(response) + + def delete_consumer_groups(self, group_ids, group_coordinator_id=None): + """Delete Consumer Group Offsets for given consumer groups. + + Note: + This does not verify that the group ids actually exist and + group_coordinator_id is the correct coordinator for all these groups. + + The result needs checking for potential errors. + + :param group_ids: The consumer group ids of the groups which are to be deleted. + :param group_coordinator_id: The node_id of the broker which is the coordinator for + all the groups. Use only if all groups are coordinated by the same broker. + If set to None, will query the cluster to find the coordinator for every single group. + Explicitly specifying this can be useful to prevent + that extra network round trips if you already know the group + coordinator. Default: None. + :return: A list of tuples (group_id, KafkaError) + """ + if group_coordinator_id is not None: + futures = [self._delete_consumer_groups_send_request(group_ids, group_coordinator_id)] + else: + coordinators_groups = defaultdict(list) + for group_id, coordinator_id in self._find_coordinator_ids(group_ids).items(): + coordinators_groups[coordinator_id].append(group_id) + futures = [ + self._delete_consumer_groups_send_request(group_ids, coordinator_id) + for coordinator_id, group_ids in coordinators_groups.items() + ] + + self._wait_for_futures(futures) + + results = [] + for f in futures: + results.extend(self._convert_delete_groups_response(f.value)) + return results + + def _convert_delete_groups_response(self, response): + if response.API_VERSION <= 1: + results = [] + for group_id, error_code in response.results: + results.append((group_id, Errors.for_code(error_code))) + return results + else: + raise NotImplementedError( + "Support for DeleteGroupsResponse_v{} has not yet been added to KafkaAdminClient." + .format(response.API_VERSION)) + + def _delete_consumer_groups_send_request(self, group_ids, group_coordinator_id): + """Send a DeleteGroups request to a broker. + + :param group_ids: The consumer group ids of the groups which are to be deleted. + :param group_coordinator_id: The node_id of the broker which is the coordinator for + all the groups. + :return: A message future + """ + version = self._matching_api_version(DeleteGroupsRequest) + if version <= 1: + request = DeleteGroupsRequest[version](group_ids) + else: + raise NotImplementedError( + "Support for DeleteGroupsRequest_v{} has not yet been added to KafkaAdminClient." + .format(version)) + return self._send_request_to_node(group_coordinator_id, request) + + def _wait_for_futures(self, futures): + while not all(future.succeeded() for future in futures): + for future in futures: + self._client.poll(future=future) + + if future.failed(): + raise future.exception # pylint: disable-msg=raising-bad-type diff --git a/testbed/dpkp__kafka-python/kafka/admin/config_resource.py b/testbed/dpkp__kafka-python/kafka/admin/config_resource.py new file mode 100644 index 0000000000000000000000000000000000000000..e3294c9c4553310eede2c47aa2aa766417a52a31 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/admin/config_resource.py @@ -0,0 +1,36 @@ +from __future__ import absolute_import + +# enum in stdlib as of py3.4 +try: + from enum import IntEnum # pylint: disable=import-error +except ImportError: + # vendored backport module + from kafka.vendor.enum34 import IntEnum + + +class ConfigResourceType(IntEnum): + """An enumerated type of config resources""" + + BROKER = 4, + TOPIC = 2 + + +class ConfigResource(object): + """A class for specifying config resources. + Arguments: + resource_type (ConfigResourceType): the type of kafka resource + name (string): The name of the kafka resource + configs ({key : value}): A maps of config keys to values. + """ + + def __init__( + self, + resource_type, + name, + configs=None + ): + if not isinstance(resource_type, (ConfigResourceType)): + resource_type = ConfigResourceType[str(resource_type).upper()] # pylint: disable-msg=unsubscriptable-object + self.resource_type = resource_type + self.name = name + self.configs = configs diff --git a/testbed/dpkp__kafka-python/kafka/admin/new_partitions.py b/testbed/dpkp__kafka-python/kafka/admin/new_partitions.py new file mode 100644 index 0000000000000000000000000000000000000000..429b2e190be16ece5ba02ae18ea6dfe57aa9eece --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/admin/new_partitions.py @@ -0,0 +1,19 @@ +from __future__ import absolute_import + + +class NewPartitions(object): + """A class for new partition creation on existing topics. Note that the length of new_assignments, if specified, + must be the difference between the new total number of partitions and the existing number of partitions. + Arguments: + total_count (int): the total number of partitions that should exist on the topic + new_assignments ([[int]]): an array of arrays of replica assignments for new partitions. + If not set, broker assigns replicas per an internal algorithm. + """ + + def __init__( + self, + total_count, + new_assignments=None + ): + self.total_count = total_count + self.new_assignments = new_assignments diff --git a/testbed/dpkp__kafka-python/kafka/admin/new_topic.py b/testbed/dpkp__kafka-python/kafka/admin/new_topic.py new file mode 100644 index 0000000000000000000000000000000000000000..645ac383ae56e5144b0e952038dd27eb726d0bd7 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/admin/new_topic.py @@ -0,0 +1,34 @@ +from __future__ import absolute_import + +from kafka.errors import IllegalArgumentError + + +class NewTopic(object): + """ A class for new topic creation + Arguments: + name (string): name of the topic + num_partitions (int): number of partitions + or -1 if replica_assignment has been specified + replication_factor (int): replication factor or -1 if + replica assignment is specified + replica_assignment (dict of int: [int]): A mapping containing + partition id and replicas to assign to it. + topic_configs (dict of str: str): A mapping of config key + and value for the topic. + """ + + def __init__( + self, + name, + num_partitions, + replication_factor, + replica_assignments=None, + topic_configs=None, + ): + if not (num_partitions == -1 or replication_factor == -1) ^ (replica_assignments is None): + raise IllegalArgumentError('either num_partitions/replication_factor or replica_assignment must be specified') + self.name = name + self.num_partitions = num_partitions + self.replication_factor = replication_factor + self.replica_assignments = replica_assignments or {} + self.topic_configs = topic_configs or {} diff --git a/testbed/dpkp__kafka-python/kafka/client_async.py b/testbed/dpkp__kafka-python/kafka/client_async.py new file mode 100644 index 0000000000000000000000000000000000000000..58f22d4ecf0c7fe0a01aafd16c30ff7feabdf602 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/client_async.py @@ -0,0 +1,1077 @@ +from __future__ import absolute_import, division + +import collections +import copy +import logging +import random +import socket +import threading +import time +import weakref + +# selectors in stdlib as of py3.4 +try: + import selectors # pylint: disable=import-error +except ImportError: + # vendored backport module + from kafka.vendor import selectors34 as selectors + +from kafka.vendor import six + +from kafka.cluster import ClusterMetadata +from kafka.conn import BrokerConnection, ConnectionStates, collect_hosts, get_ip_port_afi +from kafka import errors as Errors +from kafka.future import Future +from kafka.metrics import AnonMeasurable +from kafka.metrics.stats import Avg, Count, Rate +from kafka.metrics.stats.rate import TimeUnit +from kafka.protocol.metadata import MetadataRequest +from kafka.util import Dict, WeakMethod +# Although this looks unused, it actually monkey-patches socket.socketpair() +# and should be left in as long as we're using socket.socketpair() in this file +from kafka.vendor import socketpair +from kafka.version import __version__ + +if six.PY2: + ConnectionError = None + + +log = logging.getLogger('kafka.client') + + +class KafkaClient(object): + """ + A network client for asynchronous request/response network I/O. + + This is an internal class used to implement the user-facing producer and + consumer clients. + + This class is not thread-safe! + + Attributes: + cluster (:any:`ClusterMetadata`): Local cache of cluster metadata, retrieved + via MetadataRequests during :meth:`~kafka.KafkaClient.poll`. + + Keyword Arguments: + bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' + strings) that the client should contact to bootstrap initial + cluster metadata. This does not have to be the full node list. + It just needs to have at least one broker that will respond to a + Metadata API Request. Default port is 9092. If no servers are + specified, will default to localhost:9092. + client_id (str): a name for this client. This string is passed in + each request to servers and can be used to identify specific + server-side log entries that correspond to this client. Also + submitted to GroupCoordinator for logging with respect to + consumer group administration. Default: 'kafka-python-{version}' + reconnect_backoff_ms (int): The amount of time in milliseconds to + wait before attempting to reconnect to a given host. + Default: 50. + reconnect_backoff_max_ms (int): The maximum amount of time in + milliseconds to backoff/wait when reconnecting to a broker that has + repeatedly failed to connect. If provided, the backoff per host + will increase exponentially for each consecutive connection + failure, up to this maximum. Once the maximum is reached, + reconnection attempts will continue periodically with this fixed + rate. To avoid connection storms, a randomization factor of 0.2 + will be applied to the backoff resulting in a random range between + 20% below and 20% above the computed value. Default: 1000. + request_timeout_ms (int): Client request timeout in milliseconds. + Default: 30000. + connections_max_idle_ms: Close idle connections after the number of + milliseconds specified by this config. The broker closes idle + connections after connections.max.idle.ms, so this avoids hitting + unexpected socket disconnected errors on the client. + Default: 540000 + retry_backoff_ms (int): Milliseconds to backoff when retrying on + errors. Default: 100. + max_in_flight_requests_per_connection (int): Requests are pipelined + to kafka brokers up to this number of maximum requests per + broker connection. Default: 5. + receive_buffer_bytes (int): The size of the TCP receive buffer + (SO_RCVBUF) to use when reading data. Default: None (relies on + system defaults). Java client defaults to 32768. + send_buffer_bytes (int): The size of the TCP send buffer + (SO_SNDBUF) to use when sending data. Default: None (relies on + system defaults). Java client defaults to 131072. + socket_options (list): List of tuple-arguments to socket.setsockopt + to apply to broker connection sockets. Default: + [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] + metadata_max_age_ms (int): The period of time in milliseconds after + which we force a refresh of metadata even if we haven't seen any + partition leadership changes to proactively discover any new + brokers or partitions. Default: 300000 + security_protocol (str): Protocol used to communicate with brokers. + Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL. + Default: PLAINTEXT. + ssl_context (ssl.SSLContext): Pre-configured SSLContext for wrapping + socket connections. If provided, all other ssl_* configurations + will be ignored. Default: None. + ssl_check_hostname (bool): Flag to configure whether SSL handshake + should verify that the certificate matches the broker's hostname. + Default: True. + ssl_cafile (str): Optional filename of CA file to use in certificate + verification. Default: None. + ssl_certfile (str): Optional filename of file in PEM format containing + the client certificate, as well as any CA certificates needed to + establish the certificate's authenticity. Default: None. + ssl_keyfile (str): Optional filename containing the client private key. + Default: None. + ssl_password (str): Optional password to be used when loading the + certificate chain. Default: None. + ssl_crlfile (str): Optional filename containing the CRL to check for + certificate expiration. By default, no CRL check is done. When + providing a file, only the leaf certificate will be checked against + this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+. + Default: None. + ssl_ciphers (str): optionally set the available ciphers for ssl + connections. It should be a string in the OpenSSL cipher list + format. If no cipher can be selected (because compile-time options + or other configuration forbids use of all the specified ciphers), + an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers + api_version (tuple): Specify which Kafka API version to use. If set + to None, KafkaClient will attempt to infer the broker version by + probing various APIs. Example: (0, 10, 2). Default: None + api_version_auto_timeout_ms (int): number of milliseconds to throw a + timeout exception from the constructor when checking the broker + api version. Only applies if api_version is None + selector (selectors.BaseSelector): Provide a specific selector + implementation to use for I/O multiplexing. + Default: selectors.DefaultSelector + metrics (kafka.metrics.Metrics): Optionally provide a metrics + instance for capturing network IO stats. Default: None. + metric_group_prefix (str): Prefix for metric names. Default: '' + sasl_mechanism (str): Authentication mechanism when security_protocol + is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are: + PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512. + sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_kerberos_service_name (str): Service name to include in GSSAPI + sasl mechanism handshake. Default: 'kafka' + sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI + sasl mechanism handshake. Default: one of bootstrap servers + sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider + instance. (See kafka.oauth.abstract). Default: None + """ + + DEFAULT_CONFIG = { + 'bootstrap_servers': 'localhost', + 'bootstrap_topics_filter': set(), + 'client_id': 'kafka-python-' + __version__, + 'request_timeout_ms': 30000, + 'wakeup_timeout_ms': 3000, + 'connections_max_idle_ms': 9 * 60 * 1000, + 'reconnect_backoff_ms': 50, + 'reconnect_backoff_max_ms': 1000, + 'max_in_flight_requests_per_connection': 5, + 'receive_buffer_bytes': None, + 'send_buffer_bytes': None, + 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)], + 'sock_chunk_bytes': 4096, # undocumented experimental option + 'sock_chunk_buffer_count': 1000, # undocumented experimental option + 'retry_backoff_ms': 100, + 'metadata_max_age_ms': 300000, + 'security_protocol': 'PLAINTEXT', + 'ssl_context': None, + 'ssl_check_hostname': True, + 'ssl_cafile': None, + 'ssl_certfile': None, + 'ssl_keyfile': None, + 'ssl_password': None, + 'ssl_crlfile': None, + 'ssl_ciphers': None, + 'api_version': None, + 'api_version_auto_timeout_ms': 2000, + 'selector': selectors.DefaultSelector, + 'metrics': None, + 'metric_group_prefix': '', + 'sasl_mechanism': None, + 'sasl_plain_username': None, + 'sasl_plain_password': None, + 'sasl_kerberos_service_name': 'kafka', + 'sasl_kerberos_domain_name': None, + 'sasl_oauth_token_provider': None + } + + def __init__(self, **configs): + self.config = copy.copy(self.DEFAULT_CONFIG) + for key in self.config: + if key in configs: + self.config[key] = configs[key] + + # these properties need to be set on top of the initialization pipeline + # because they are used when __del__ method is called + self._closed = False + self._wake_r, self._wake_w = socket.socketpair() + self._selector = self.config['selector']() + + self.cluster = ClusterMetadata(**self.config) + self._topics = set() # empty set will fetch all topic metadata + self._metadata_refresh_in_progress = False + self._conns = Dict() # object to support weakrefs + self._api_versions = None + self._connecting = set() + self._sending = set() + self._refresh_on_disconnects = True + self._last_bootstrap = 0 + self._bootstrap_fails = 0 + self._wake_r.setblocking(False) + self._wake_w.settimeout(self.config['wakeup_timeout_ms'] / 1000.0) + self._wake_lock = threading.Lock() + + self._lock = threading.RLock() + + # when requests complete, they are transferred to this queue prior to + # invocation. The purpose is to avoid invoking them while holding the + # lock above. + self._pending_completion = collections.deque() + + self._selector.register(self._wake_r, selectors.EVENT_READ) + self._idle_expiry_manager = IdleConnectionManager(self.config['connections_max_idle_ms']) + self._sensors = None + if self.config['metrics']: + self._sensors = KafkaClientMetrics(self.config['metrics'], + self.config['metric_group_prefix'], + weakref.proxy(self._conns)) + + self._num_bootstrap_hosts = len(collect_hosts(self.config['bootstrap_servers'])) + + # Check Broker Version if not set explicitly + if self.config['api_version'] is None: + check_timeout = self.config['api_version_auto_timeout_ms'] / 1000 + self.config['api_version'] = self.check_version(timeout=check_timeout) + + def _can_bootstrap(self): + effective_failures = self._bootstrap_fails // self._num_bootstrap_hosts + backoff_factor = 2 ** effective_failures + backoff_ms = min(self.config['reconnect_backoff_ms'] * backoff_factor, + self.config['reconnect_backoff_max_ms']) + + backoff_ms *= random.uniform(0.8, 1.2) + + next_at = self._last_bootstrap + backoff_ms / 1000.0 + now = time.time() + if next_at > now: + return False + return True + + def _can_connect(self, node_id): + if node_id not in self._conns: + if self.cluster.broker_metadata(node_id): + return True + return False + conn = self._conns[node_id] + return conn.disconnected() and not conn.blacked_out() + + def _conn_state_change(self, node_id, sock, conn): + with self._lock: + if conn.connecting(): + # SSL connections can enter this state 2x (second during Handshake) + if node_id not in self._connecting: + self._connecting.add(node_id) + try: + self._selector.register(sock, selectors.EVENT_WRITE, conn) + except KeyError: + self._selector.modify(sock, selectors.EVENT_WRITE, conn) + + if self.cluster.is_bootstrap(node_id): + self._last_bootstrap = time.time() + + elif conn.connected(): + log.debug("Node %s connected", node_id) + if node_id in self._connecting: + self._connecting.remove(node_id) + + try: + self._selector.modify(sock, selectors.EVENT_READ, conn) + except KeyError: + self._selector.register(sock, selectors.EVENT_READ, conn) + + if self._sensors: + self._sensors.connection_created.record() + + self._idle_expiry_manager.update(node_id) + + if self.cluster.is_bootstrap(node_id): + self._bootstrap_fails = 0 + + else: + for node_id in list(self._conns.keys()): + if self.cluster.is_bootstrap(node_id): + self._conns.pop(node_id).close() + + # Connection failures imply that our metadata is stale, so let's refresh + elif conn.state is ConnectionStates.DISCONNECTED: + if node_id in self._connecting: + self._connecting.remove(node_id) + try: + self._selector.unregister(sock) + except KeyError: + pass + + if self._sensors: + self._sensors.connection_closed.record() + + idle_disconnect = False + if self._idle_expiry_manager.is_expired(node_id): + idle_disconnect = True + self._idle_expiry_manager.remove(node_id) + + # If the connection has already by popped from self._conns, + # we can assume the disconnect was intentional and not a failure + if node_id not in self._conns: + pass + + elif self.cluster.is_bootstrap(node_id): + self._bootstrap_fails += 1 + + elif self._refresh_on_disconnects and not self._closed and not idle_disconnect: + log.warning("Node %s connection failed -- refreshing metadata", node_id) + self.cluster.request_update() + + def maybe_connect(self, node_id, wakeup=True): + """Queues a node for asynchronous connection during the next .poll()""" + if self._can_connect(node_id): + self._connecting.add(node_id) + # Wakeup signal is useful in case another thread is + # blocked waiting for incoming network traffic while holding + # the client lock in poll(). + if wakeup: + self.wakeup() + return True + return False + + def _should_recycle_connection(self, conn): + # Never recycle unless disconnected + if not conn.disconnected(): + return False + + # Otherwise, only recycle when broker metadata has changed + broker = self.cluster.broker_metadata(conn.node_id) + if broker is None: + return False + + host, _, afi = get_ip_port_afi(broker.host) + if conn.host != host or conn.port != broker.port: + log.info("Broker metadata change detected for node %s" + " from %s:%s to %s:%s", conn.node_id, conn.host, conn.port, + broker.host, broker.port) + return True + + return False + + def _maybe_connect(self, node_id): + """Idempotent non-blocking connection attempt to the given node id.""" + with self._lock: + conn = self._conns.get(node_id) + + if conn is None: + broker = self.cluster.broker_metadata(node_id) + assert broker, 'Broker id %s not in current metadata' % (node_id,) + + log.debug("Initiating connection to node %s at %s:%s", + node_id, broker.host, broker.port) + host, port, afi = get_ip_port_afi(broker.host) + cb = WeakMethod(self._conn_state_change) + conn = BrokerConnection(host, broker.port, afi, + state_change_callback=cb, + node_id=node_id, + **self.config) + self._conns[node_id] = conn + + # Check if existing connection should be recreated because host/port changed + elif self._should_recycle_connection(conn): + self._conns.pop(node_id) + return False + + elif conn.connected(): + return True + + conn.connect() + return conn.connected() + + def ready(self, node_id, metadata_priority=True): + """Check whether a node is connected and ok to send more requests. + + Arguments: + node_id (int): the id of the node to check + metadata_priority (bool): Mark node as not-ready if a metadata + refresh is required. Default: True + + Returns: + bool: True if we are ready to send to the given node + """ + self.maybe_connect(node_id) + return self.is_ready(node_id, metadata_priority=metadata_priority) + + def connected(self, node_id): + """Return True iff the node_id is connected.""" + conn = self._conns.get(node_id) + if conn is None: + return False + return conn.connected() + + def _close(self): + if not self._closed: + self._closed = True + self._wake_r.close() + self._wake_w.close() + self._selector.close() + + def close(self, node_id=None): + """Close one or all broker connections. + + Arguments: + node_id (int, optional): the id of the node to close + """ + with self._lock: + if node_id is None: + self._close() + conns = list(self._conns.values()) + self._conns.clear() + for conn in conns: + conn.close() + elif node_id in self._conns: + self._conns.pop(node_id).close() + else: + log.warning("Node %s not found in current connection list; skipping", node_id) + return + + def __del__(self): + self._close() + + def is_disconnected(self, node_id): + """Check whether the node connection has been disconnected or failed. + + A disconnected node has either been closed or has failed. Connection + failures are usually transient and can be resumed in the next ready() + call, but there are cases where transient failures need to be caught + and re-acted upon. + + Arguments: + node_id (int): the id of the node to check + + Returns: + bool: True iff the node exists and is disconnected + """ + conn = self._conns.get(node_id) + if conn is None: + return False + return conn.disconnected() + + def connection_delay(self, node_id): + """ + Return the number of milliseconds to wait, based on the connection + state, before attempting to send data. When disconnected, this respects + the reconnect backoff time. When connecting, returns 0 to allow + non-blocking connect to finish. When connected, returns a very large + number to handle slow/stalled connections. + + Arguments: + node_id (int): The id of the node to check + + Returns: + int: The number of milliseconds to wait. + """ + conn = self._conns.get(node_id) + if conn is None: + return 0 + return conn.connection_delay() + + def is_ready(self, node_id, metadata_priority=True): + """Check whether a node is ready to send more requests. + + In addition to connection-level checks, this method also is used to + block additional requests from being sent during a metadata refresh. + + Arguments: + node_id (int): id of the node to check + metadata_priority (bool): Mark node as not-ready if a metadata + refresh is required. Default: True + + Returns: + bool: True if the node is ready and metadata is not refreshing + """ + if not self._can_send_request(node_id): + return False + + # if we need to update our metadata now declare all requests unready to + # make metadata requests first priority + if metadata_priority: + if self._metadata_refresh_in_progress: + return False + if self.cluster.ttl() == 0: + return False + return True + + def _can_send_request(self, node_id): + conn = self._conns.get(node_id) + if not conn: + return False + return conn.connected() and conn.can_send_more() + + def send(self, node_id, request, wakeup=True): + """Send a request to a specific node. Bytes are placed on an + internal per-connection send-queue. Actual network I/O will be + triggered in a subsequent call to .poll() + + Arguments: + node_id (int): destination node + request (Struct): request object (not-encoded) + wakeup (bool): optional flag to disable thread-wakeup + + Raises: + AssertionError: if node_id is not in current cluster metadata + + Returns: + Future: resolves to Response struct or Error + """ + conn = self._conns.get(node_id) + if not conn or not self._can_send_request(node_id): + self.maybe_connect(node_id, wakeup=wakeup) + return Future().failure(Errors.NodeNotReadyError(node_id)) + + # conn.send will queue the request internally + # we will need to call send_pending_requests() + # to trigger network I/O + future = conn.send(request, blocking=False) + self._sending.add(conn) + + # Wakeup signal is useful in case another thread is + # blocked waiting for incoming network traffic while holding + # the client lock in poll(). + if wakeup: + self.wakeup() + + return future + + def poll(self, timeout_ms=None, future=None): + """Try to read and write to sockets. + + This method will also attempt to complete node connections, refresh + stale metadata, and run previously-scheduled tasks. + + Arguments: + timeout_ms (int, optional): maximum amount of time to wait (in ms) + for at least one response. Must be non-negative. The actual + timeout will be the minimum of timeout, request timeout and + metadata timeout. Default: request_timeout_ms + future (Future, optional): if provided, blocks until future.is_done + + Returns: + list: responses received (can be empty) + """ + if future is not None: + timeout_ms = 100 + elif timeout_ms is None: + timeout_ms = self.config['request_timeout_ms'] + elif not isinstance(timeout_ms, (int, float)): + raise TypeError('Invalid type for timeout: %s' % type(timeout_ms)) + + # Loop for futures, break after first loop if None + responses = [] + while True: + with self._lock: + if self._closed: + break + + # Attempt to complete pending connections + for node_id in list(self._connecting): + self._maybe_connect(node_id) + + # Send a metadata request if needed + metadata_timeout_ms = self._maybe_refresh_metadata() + + # If we got a future that is already done, don't block in _poll + if future is not None and future.is_done: + timeout = 0 + else: + idle_connection_timeout_ms = self._idle_expiry_manager.next_check_ms() + timeout = min( + timeout_ms, + metadata_timeout_ms, + idle_connection_timeout_ms, + self.config['request_timeout_ms']) + # if there are no requests in flight, do not block longer than the retry backoff + if self.in_flight_request_count() == 0: + timeout = min(timeout, self.config['retry_backoff_ms']) + timeout = max(0, timeout) # avoid negative timeouts + + self._poll(timeout / 1000) + + # called without the lock to avoid deadlock potential + # if handlers need to acquire locks + responses.extend(self._fire_pending_completed_requests()) + + # If all we had was a timeout (future is None) - only do one poll + # If we do have a future, we keep looping until it is done + if future is None or future.is_done: + break + + return responses + + def _register_send_sockets(self): + while self._sending: + conn = self._sending.pop() + try: + key = self._selector.get_key(conn._sock) + events = key.events | selectors.EVENT_WRITE + self._selector.modify(key.fileobj, events, key.data) + except KeyError: + self._selector.register(conn._sock, selectors.EVENT_WRITE, conn) + + def _poll(self, timeout): + # This needs to be locked, but since it is only called from within the + # locked section of poll(), there is no additional lock acquisition here + processed = set() + + # Send pending requests first, before polling for responses + self._register_send_sockets() + + start_select = time.time() + ready = self._selector.select(timeout) + end_select = time.time() + if self._sensors: + self._sensors.select_time.record((end_select - start_select) * 1000000000) + + for key, events in ready: + if key.fileobj is self._wake_r: + self._clear_wake_fd() + continue + + # Send pending requests if socket is ready to write + if events & selectors.EVENT_WRITE: + conn = key.data + if conn.connecting(): + conn.connect() + else: + if conn.send_pending_requests_v2(): + # If send is complete, we dont need to track write readiness + # for this socket anymore + if key.events ^ selectors.EVENT_WRITE: + self._selector.modify( + key.fileobj, + key.events ^ selectors.EVENT_WRITE, + key.data) + else: + self._selector.unregister(key.fileobj) + + if not (events & selectors.EVENT_READ): + continue + conn = key.data + processed.add(conn) + + if not conn.in_flight_requests: + # if we got an EVENT_READ but there were no in-flight requests, one of + # two things has happened: + # + # 1. The remote end closed the connection (because it died, or because + # a firewall timed out, or whatever) + # 2. The protocol is out of sync. + # + # either way, we can no longer safely use this connection + # + # Do a 1-byte read to check protocol didnt get out of sync, and then close the conn + try: + unexpected_data = key.fileobj.recv(1) + if unexpected_data: # anything other than a 0-byte read means protocol issues + log.warning('Protocol out of sync on %r, closing', conn) + except socket.error: + pass + conn.close(Errors.KafkaConnectionError('Socket EVENT_READ without in-flight-requests')) + continue + + self._idle_expiry_manager.update(conn.node_id) + self._pending_completion.extend(conn.recv()) + + # Check for additional pending SSL bytes + if self.config['security_protocol'] in ('SSL', 'SASL_SSL'): + # TODO: optimize + for conn in self._conns.values(): + if conn not in processed and conn.connected() and conn._sock.pending(): + self._pending_completion.extend(conn.recv()) + + for conn in six.itervalues(self._conns): + if conn.requests_timed_out(): + log.warning('%s timed out after %s ms. Closing connection.', + conn, conn.config['request_timeout_ms']) + conn.close(error=Errors.RequestTimedOutError( + 'Request timed out after %s ms' % + conn.config['request_timeout_ms'])) + + if self._sensors: + self._sensors.io_time.record((time.time() - end_select) * 1000000000) + + self._maybe_close_oldest_connection() + + def in_flight_request_count(self, node_id=None): + """Get the number of in-flight requests for a node or all nodes. + + Arguments: + node_id (int, optional): a specific node to check. If unspecified, + return the total for all nodes + + Returns: + int: pending in-flight requests for the node, or all nodes if None + """ + if node_id is not None: + conn = self._conns.get(node_id) + if conn is None: + return 0 + return len(conn.in_flight_requests) + else: + return sum([len(conn.in_flight_requests) + for conn in list(self._conns.values())]) + + def _fire_pending_completed_requests(self): + responses = [] + while True: + try: + # We rely on deque.popleft remaining threadsafe + # to allow both the heartbeat thread and the main thread + # to process responses + response, future = self._pending_completion.popleft() + except IndexError: + break + future.success(response) + responses.append(response) + return responses + + def least_loaded_node(self): + """Choose the node with fewest outstanding requests, with fallbacks. + + This method will prefer a node with an existing connection and no + in-flight-requests. If no such node is found, a node will be chosen + randomly from disconnected nodes that are not "blacked out" (i.e., + are not subject to a reconnect backoff). If no node metadata has been + obtained, will return a bootstrap node (subject to exponential backoff). + + Returns: + node_id or None if no suitable node was found + """ + nodes = [broker.nodeId for broker in self.cluster.brokers()] + random.shuffle(nodes) + + inflight = float('inf') + found = None + for node_id in nodes: + conn = self._conns.get(node_id) + connected = conn is not None and conn.connected() + blacked_out = conn is not None and conn.blacked_out() + curr_inflight = len(conn.in_flight_requests) if conn is not None else 0 + if connected and curr_inflight == 0: + # if we find an established connection + # with no in-flight requests, we can stop right away + return node_id + elif not blacked_out and curr_inflight < inflight: + # otherwise if this is the best we have found so far, record that + inflight = curr_inflight + found = node_id + + return found + + def set_topics(self, topics): + """Set specific topics to track for metadata. + + Arguments: + topics (list of str): topics to check for metadata + + Returns: + Future: resolves after metadata request/response + """ + if set(topics).difference(self._topics): + future = self.cluster.request_update() + else: + future = Future().success(set(topics)) + self._topics = set(topics) + return future + + def add_topic(self, topic): + """Add a topic to the list of topics tracked via metadata. + + Arguments: + topic (str): topic to track + + Returns: + Future: resolves after metadata request/response + """ + if topic in self._topics: + return Future().success(set(self._topics)) + + self._topics.add(topic) + return self.cluster.request_update() + + # This method should be locked when running multi-threaded + def _maybe_refresh_metadata(self, wakeup=False): + """Send a metadata request if needed. + + Returns: + int: milliseconds until next refresh + """ + ttl = self.cluster.ttl() + wait_for_in_progress_ms = self.config['request_timeout_ms'] if self._metadata_refresh_in_progress else 0 + metadata_timeout = max(ttl, wait_for_in_progress_ms) + + if metadata_timeout > 0: + return metadata_timeout + + # Beware that the behavior of this method and the computation of + # timeouts for poll() are highly dependent on the behavior of + # least_loaded_node() + node_id = self.least_loaded_node() + if node_id is None: + log.debug("Give up sending metadata request since no node is available"); + return self.config['reconnect_backoff_ms'] + + if self._can_send_request(node_id): + topics = list(self._topics) + if not topics and self.cluster.is_bootstrap(node_id): + topics = list(self.config['bootstrap_topics_filter']) + + if self.cluster.need_all_topic_metadata or not topics: + topics = [] if self.config['api_version'] < (0, 10) else None + api_version = 0 if self.config['api_version'] < (0, 10) else 1 + request = MetadataRequest[api_version](topics) + log.debug("Sending metadata request %s to node %s", request, node_id) + future = self.send(node_id, request, wakeup=wakeup) + future.add_callback(self.cluster.update_metadata) + future.add_errback(self.cluster.failed_update) + + self._metadata_refresh_in_progress = True + def refresh_done(val_or_error): + self._metadata_refresh_in_progress = False + future.add_callback(refresh_done) + future.add_errback(refresh_done) + return self.config['request_timeout_ms'] + + # If there's any connection establishment underway, wait until it completes. This prevents + # the client from unnecessarily connecting to additional nodes while a previous connection + # attempt has not been completed. + if self._connecting: + return self.config['reconnect_backoff_ms'] + + if self.maybe_connect(node_id, wakeup=wakeup): + log.debug("Initializing connection to node %s for metadata request", node_id) + return self.config['reconnect_backoff_ms'] + + # connected but can't send more, OR connecting + # In either case we just need to wait for a network event + # to let us know the selected connection might be usable again. + return float('inf') + + def get_api_versions(self): + """Return the ApiVersions map, if available. + + Note: A call to check_version must previously have succeeded and returned + version 0.10.0 or later + + Returns: a map of dict mapping {api_key : (min_version, max_version)}, + or None if ApiVersion is not supported by the kafka cluster. + """ + return self._api_versions + + def check_version(self, node_id=None, timeout=2, strict=False): + """Attempt to guess the version of a Kafka broker. + + Note: It is possible that this method blocks longer than the + specified timeout. This can happen if the entire cluster + is down and the client enters a bootstrap backoff sleep. + This is only possible if node_id is None. + + Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ... + + Raises: + NodeNotReadyError (if node_id is provided) + NoBrokersAvailable (if node_id is None) + UnrecognizedBrokerVersion: please file bug if seen! + AssertionError (if strict=True): please file bug if seen! + """ + self._lock.acquire() + end = time.time() + timeout + while time.time() < end: + + # It is possible that least_loaded_node falls back to bootstrap, + # which can block for an increasing backoff period + try_node = node_id or self.least_loaded_node() + if try_node is None: + self._lock.release() + raise Errors.NoBrokersAvailable() + self._maybe_connect(try_node) + conn = self._conns[try_node] + + # We will intentionally cause socket failures + # These should not trigger metadata refresh + self._refresh_on_disconnects = False + try: + remaining = end - time.time() + version = conn.check_version(timeout=remaining, strict=strict, topics=list(self.config['bootstrap_topics_filter'])) + if version >= (0, 10, 0): + # cache the api versions map if it's available (starting + # in 0.10 cluster version) + self._api_versions = conn.get_api_versions() + self._lock.release() + return version + except Errors.NodeNotReadyError: + # Only raise to user if this is a node-specific request + if node_id is not None: + self._lock.release() + raise + finally: + self._refresh_on_disconnects = True + + # Timeout + else: + self._lock.release() + raise Errors.NoBrokersAvailable() + + def wakeup(self): + with self._wake_lock: + try: + self._wake_w.sendall(b'x') + except socket.timeout: + log.warning('Timeout to send to wakeup socket!') + raise Errors.KafkaTimeoutError() + except socket.error: + log.warning('Unable to send to wakeup socket!') + + def _clear_wake_fd(self): + # reading from wake socket should only happen in a single thread + while True: + try: + self._wake_r.recv(1024) + except socket.error: + break + + def _maybe_close_oldest_connection(self): + expired_connection = self._idle_expiry_manager.poll_expired_connection() + if expired_connection: + conn_id, ts = expired_connection + idle_ms = (time.time() - ts) * 1000 + log.info('Closing idle connection %s, last active %d ms ago', conn_id, idle_ms) + self.close(node_id=conn_id) + + def bootstrap_connected(self): + """Return True if a bootstrap node is connected""" + for node_id in self._conns: + if not self.cluster.is_bootstrap(node_id): + continue + if self._conns[node_id].connected(): + return True + else: + return False + + +# OrderedDict requires python2.7+ +try: + from collections import OrderedDict +except ImportError: + # If we dont have OrderedDict, we'll fallback to dict with O(n) priority reads + OrderedDict = dict + + +class IdleConnectionManager(object): + def __init__(self, connections_max_idle_ms): + if connections_max_idle_ms > 0: + self.connections_max_idle = connections_max_idle_ms / 1000 + else: + self.connections_max_idle = float('inf') + self.next_idle_close_check_time = None + self.update_next_idle_close_check_time(time.time()) + self.lru_connections = OrderedDict() + + def update(self, conn_id): + # order should reflect last-update + if conn_id in self.lru_connections: + del self.lru_connections[conn_id] + self.lru_connections[conn_id] = time.time() + + def remove(self, conn_id): + if conn_id in self.lru_connections: + del self.lru_connections[conn_id] + + def is_expired(self, conn_id): + if conn_id not in self.lru_connections: + return None + return time.time() >= self.lru_connections[conn_id] + self.connections_max_idle + + def next_check_ms(self): + now = time.time() + if not self.lru_connections: + return float('inf') + elif self.next_idle_close_check_time <= now: + return 0 + else: + return int((self.next_idle_close_check_time - now) * 1000) + + def update_next_idle_close_check_time(self, ts): + self.next_idle_close_check_time = ts + self.connections_max_idle + + def poll_expired_connection(self): + if time.time() < self.next_idle_close_check_time: + return None + + if not len(self.lru_connections): + return None + + oldest_conn_id = None + oldest_ts = None + if OrderedDict is dict: + for conn_id, ts in self.lru_connections.items(): + if oldest_conn_id is None or ts < oldest_ts: + oldest_conn_id = conn_id + oldest_ts = ts + else: + (oldest_conn_id, oldest_ts) = next(iter(self.lru_connections.items())) + + self.update_next_idle_close_check_time(oldest_ts) + + if time.time() >= oldest_ts + self.connections_max_idle: + return (oldest_conn_id, oldest_ts) + else: + return None + + +class KafkaClientMetrics(object): + def __init__(self, metrics, metric_group_prefix, conns): + self.metrics = metrics + self.metric_group_name = metric_group_prefix + '-metrics' + + self.connection_closed = metrics.sensor('connections-closed') + self.connection_closed.add(metrics.metric_name( + 'connection-close-rate', self.metric_group_name, + 'Connections closed per second in the window.'), Rate()) + self.connection_created = metrics.sensor('connections-created') + self.connection_created.add(metrics.metric_name( + 'connection-creation-rate', self.metric_group_name, + 'New connections established per second in the window.'), Rate()) + + self.select_time = metrics.sensor('select-time') + self.select_time.add(metrics.metric_name( + 'select-rate', self.metric_group_name, + 'Number of times the I/O layer checked for new I/O to perform per' + ' second'), Rate(sampled_stat=Count())) + self.select_time.add(metrics.metric_name( + 'io-wait-time-ns-avg', self.metric_group_name, + 'The average length of time the I/O thread spent waiting for a' + ' socket ready for reads or writes in nanoseconds.'), Avg()) + self.select_time.add(metrics.metric_name( + 'io-wait-ratio', self.metric_group_name, + 'The fraction of time the I/O thread spent waiting.'), + Rate(time_unit=TimeUnit.NANOSECONDS)) + + self.io_time = metrics.sensor('io-time') + self.io_time.add(metrics.metric_name( + 'io-time-ns-avg', self.metric_group_name, + 'The average length of time for I/O per select call in nanoseconds.'), + Avg()) + self.io_time.add(metrics.metric_name( + 'io-ratio', self.metric_group_name, + 'The fraction of time the I/O thread spent doing I/O'), + Rate(time_unit=TimeUnit.NANOSECONDS)) + + metrics.add_metric(metrics.metric_name( + 'connection-count', self.metric_group_name, + 'The current number of active connections.'), AnonMeasurable( + lambda config, now: len(conns))) diff --git a/testbed/dpkp__kafka-python/kafka/cluster.py b/testbed/dpkp__kafka-python/kafka/cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..438baf29d5137b92a72d110e8ba7ffa3407b640f --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/cluster.py @@ -0,0 +1,397 @@ +from __future__ import absolute_import + +import collections +import copy +import logging +import threading +import time + +from kafka.vendor import six + +from kafka import errors as Errors +from kafka.conn import collect_hosts +from kafka.future import Future +from kafka.structs import BrokerMetadata, PartitionMetadata, TopicPartition + +log = logging.getLogger(__name__) + + +class ClusterMetadata(object): + """ + A class to manage kafka cluster metadata. + + This class does not perform any IO. It simply updates internal state + given API responses (MetadataResponse, GroupCoordinatorResponse). + + Keyword Arguments: + retry_backoff_ms (int): Milliseconds to backoff when retrying on + errors. Default: 100. + metadata_max_age_ms (int): The period of time in milliseconds after + which we force a refresh of metadata even if we haven't seen any + partition leadership changes to proactively discover any new + brokers or partitions. Default: 300000 + bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' + strings) that the client should contact to bootstrap initial + cluster metadata. This does not have to be the full node list. + It just needs to have at least one broker that will respond to a + Metadata API Request. Default port is 9092. If no servers are + specified, will default to localhost:9092. + """ + DEFAULT_CONFIG = { + 'retry_backoff_ms': 100, + 'metadata_max_age_ms': 300000, + 'bootstrap_servers': [], + } + + def __init__(self, **configs): + self._brokers = {} # node_id -> BrokerMetadata + self._partitions = {} # topic -> partition -> PartitionMetadata + self._broker_partitions = collections.defaultdict(set) # node_id -> {TopicPartition...} + self._groups = {} # group_name -> node_id + self._last_refresh_ms = 0 + self._last_successful_refresh_ms = 0 + self._need_update = True + self._future = None + self._listeners = set() + self._lock = threading.Lock() + self.need_all_topic_metadata = False + self.unauthorized_topics = set() + self.internal_topics = set() + self.controller = None + + self.config = copy.copy(self.DEFAULT_CONFIG) + for key in self.config: + if key in configs: + self.config[key] = configs[key] + + self._bootstrap_brokers = self._generate_bootstrap_brokers() + self._coordinator_brokers = {} + + def _generate_bootstrap_brokers(self): + # collect_hosts does not perform DNS, so we should be fine to re-use + bootstrap_hosts = collect_hosts(self.config['bootstrap_servers']) + + brokers = {} + for i, (host, port, _) in enumerate(bootstrap_hosts): + node_id = 'bootstrap-%s' % i + brokers[node_id] = BrokerMetadata(node_id, host, port, None) + return brokers + + def is_bootstrap(self, node_id): + return node_id in self._bootstrap_brokers + + def brokers(self): + """Get all BrokerMetadata + + Returns: + set: {BrokerMetadata, ...} + """ + return set(self._brokers.values()) or set(self._bootstrap_brokers.values()) + + def broker_metadata(self, broker_id): + """Get BrokerMetadata + + Arguments: + broker_id (int): node_id for a broker to check + + Returns: + BrokerMetadata or None if not found + """ + return ( + self._brokers.get(broker_id) or + self._bootstrap_brokers.get(broker_id) or + self._coordinator_brokers.get(broker_id) + ) + + def partitions_for_topic(self, topic): + """Return set of all partitions for topic (whether available or not) + + Arguments: + topic (str): topic to check for partitions + + Returns: + set: {partition (int), ...} + """ + if topic not in self._partitions: + return None + return set(self._partitions[topic].keys()) + + def available_partitions_for_topic(self, topic): + """Return set of partitions with known leaders + + Arguments: + topic (str): topic to check for partitions + + Returns: + set: {partition (int), ...} + None if topic not found. + """ + if topic not in self._partitions: + return None + return set([partition for partition, metadata + in six.iteritems(self._partitions[topic]) + if metadata.leader != -1]) + + def leader_for_partition(self, partition): + """Return node_id of leader, -1 unavailable, None if unknown.""" + if partition.topic not in self._partitions: + return None + elif partition.partition not in self._partitions[partition.topic]: + return None + return self._partitions[partition.topic][partition.partition].leader + + def partitions_for_broker(self, broker_id): + """Return TopicPartitions for which the broker is a leader. + + Arguments: + broker_id (int): node id for a broker + + Returns: + set: {TopicPartition, ...} + None if the broker either has no partitions or does not exist. + """ + return self._broker_partitions.get(broker_id) + + def coordinator_for_group(self, group): + """Return node_id of group coordinator. + + Arguments: + group (str): name of consumer group + + Returns: + int: node_id for group coordinator + None if the group does not exist. + """ + return self._groups.get(group) + + def ttl(self): + """Milliseconds until metadata should be refreshed""" + now = time.time() * 1000 + if self._need_update: + ttl = 0 + else: + metadata_age = now - self._last_successful_refresh_ms + ttl = self.config['metadata_max_age_ms'] - metadata_age + + retry_age = now - self._last_refresh_ms + next_retry = self.config['retry_backoff_ms'] - retry_age + + return max(ttl, next_retry, 0) + + def refresh_backoff(self): + """Return milliseconds to wait before attempting to retry after failure""" + return self.config['retry_backoff_ms'] + + def request_update(self): + """Flags metadata for update, return Future() + + Actual update must be handled separately. This method will only + change the reported ttl() + + Returns: + kafka.future.Future (value will be the cluster object after update) + """ + with self._lock: + self._need_update = True + if not self._future or self._future.is_done: + self._future = Future() + return self._future + + def topics(self, exclude_internal_topics=True): + """Get set of known topics. + + Arguments: + exclude_internal_topics (bool): Whether records from internal topics + (such as offsets) should be exposed to the consumer. If set to + True the only way to receive records from an internal topic is + subscribing to it. Default True + + Returns: + set: {topic (str), ...} + """ + topics = set(self._partitions.keys()) + if exclude_internal_topics: + return topics - self.internal_topics + else: + return topics + + def failed_update(self, exception): + """Update cluster state given a failed MetadataRequest.""" + f = None + with self._lock: + if self._future: + f = self._future + self._future = None + if f: + f.failure(exception) + self._last_refresh_ms = time.time() * 1000 + + def update_metadata(self, metadata): + """Update cluster state given a MetadataResponse. + + Arguments: + metadata (MetadataResponse): broker response to a metadata request + + Returns: None + """ + # In the common case where we ask for a single topic and get back an + # error, we should fail the future + if len(metadata.topics) == 1 and metadata.topics[0][0] != 0: + error_code, topic = metadata.topics[0][:2] + error = Errors.for_code(error_code)(topic) + return self.failed_update(error) + + if not metadata.brokers: + log.warning("No broker metadata found in MetadataResponse -- ignoring.") + return self.failed_update(Errors.MetadataEmptyBrokerList(metadata)) + + _new_brokers = {} + for broker in metadata.brokers: + if metadata.API_VERSION == 0: + node_id, host, port = broker + rack = None + else: + node_id, host, port, rack = broker + _new_brokers.update({ + node_id: BrokerMetadata(node_id, host, port, rack) + }) + + if metadata.API_VERSION == 0: + _new_controller = None + else: + _new_controller = _new_brokers.get(metadata.controller_id) + + _new_partitions = {} + _new_broker_partitions = collections.defaultdict(set) + _new_unauthorized_topics = set() + _new_internal_topics = set() + + for topic_data in metadata.topics: + if metadata.API_VERSION == 0: + error_code, topic, partitions = topic_data + is_internal = False + else: + error_code, topic, is_internal, partitions = topic_data + if is_internal: + _new_internal_topics.add(topic) + error_type = Errors.for_code(error_code) + if error_type is Errors.NoError: + _new_partitions[topic] = {} + for p_error, partition, leader, replicas, isr in partitions: + _new_partitions[topic][partition] = PartitionMetadata( + topic=topic, partition=partition, leader=leader, + replicas=replicas, isr=isr, error=p_error) + if leader != -1: + _new_broker_partitions[leader].add( + TopicPartition(topic, partition)) + + # Specific topic errors can be ignored if this is a full metadata fetch + elif self.need_all_topic_metadata: + continue + + elif error_type is Errors.LeaderNotAvailableError: + log.warning("Topic %s is not available during auto-create" + " initialization", topic) + elif error_type is Errors.UnknownTopicOrPartitionError: + log.error("Topic %s not found in cluster metadata", topic) + elif error_type is Errors.TopicAuthorizationFailedError: + log.error("Topic %s is not authorized for this client", topic) + _new_unauthorized_topics.add(topic) + elif error_type is Errors.InvalidTopicError: + log.error("'%s' is not a valid topic name", topic) + else: + log.error("Error fetching metadata for topic %s: %s", + topic, error_type) + + with self._lock: + self._brokers = _new_brokers + self.controller = _new_controller + self._partitions = _new_partitions + self._broker_partitions = _new_broker_partitions + self.unauthorized_topics = _new_unauthorized_topics + self.internal_topics = _new_internal_topics + f = None + if self._future: + f = self._future + self._future = None + self._need_update = False + + now = time.time() * 1000 + self._last_refresh_ms = now + self._last_successful_refresh_ms = now + + if f: + f.success(self) + log.debug("Updated cluster metadata to %s", self) + + for listener in self._listeners: + listener(self) + + if self.need_all_topic_metadata: + # the listener may change the interested topics, + # which could cause another metadata refresh. + # If we have already fetched all topics, however, + # another fetch should be unnecessary. + self._need_update = False + + def add_listener(self, listener): + """Add a callback function to be called on each metadata update""" + self._listeners.add(listener) + + def remove_listener(self, listener): + """Remove a previously added listener callback""" + self._listeners.remove(listener) + + def add_group_coordinator(self, group, response): + """Update with metadata for a group coordinator + + Arguments: + group (str): name of group from GroupCoordinatorRequest + response (GroupCoordinatorResponse): broker response + + Returns: + string: coordinator node_id if metadata is updated, None on error + """ + log.debug("Updating coordinator for %s: %s", group, response) + error_type = Errors.for_code(response.error_code) + if error_type is not Errors.NoError: + log.error("GroupCoordinatorResponse error: %s", error_type) + self._groups[group] = -1 + return + + # Use a coordinator-specific node id so that group requests + # get a dedicated connection + node_id = 'coordinator-{}'.format(response.coordinator_id) + coordinator = BrokerMetadata( + node_id, + response.host, + response.port, + None) + + log.info("Group coordinator for %s is %s", group, coordinator) + self._coordinator_brokers[node_id] = coordinator + self._groups[group] = node_id + return node_id + + def with_partitions(self, partitions_to_add): + """Returns a copy of cluster metadata with partitions added""" + new_metadata = ClusterMetadata(**self.config) + new_metadata._brokers = copy.deepcopy(self._brokers) + new_metadata._partitions = copy.deepcopy(self._partitions) + new_metadata._broker_partitions = copy.deepcopy(self._broker_partitions) + new_metadata._groups = copy.deepcopy(self._groups) + new_metadata.internal_topics = copy.deepcopy(self.internal_topics) + new_metadata.unauthorized_topics = copy.deepcopy(self.unauthorized_topics) + + for partition in partitions_to_add: + new_metadata._partitions[partition.topic][partition.partition] = partition + + if partition.leader is not None and partition.leader != -1: + new_metadata._broker_partitions[partition.leader].add( + TopicPartition(partition.topic, partition.partition)) + + return new_metadata + + def __str__(self): + return 'ClusterMetadata(brokers: %d, topics: %d, groups: %d)' % \ + (len(self._brokers), len(self._partitions), len(self._groups)) diff --git a/testbed/dpkp__kafka-python/kafka/codec.py b/testbed/dpkp__kafka-python/kafka/codec.py new file mode 100644 index 0000000000000000000000000000000000000000..917400e743ab9dfafebd56057057547d1c40f3ff --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/codec.py @@ -0,0 +1,326 @@ +from __future__ import absolute_import + +import gzip +import io +import platform +import struct + +from kafka.vendor import six +from kafka.vendor.six.moves import range + +_XERIAL_V1_HEADER = (-126, b'S', b'N', b'A', b'P', b'P', b'Y', 0, 1, 1) +_XERIAL_V1_FORMAT = 'bccccccBii' +ZSTD_MAX_OUTPUT_SIZE = 1024 * 1024 + +try: + import snappy +except ImportError: + snappy = None + +try: + import zstandard as zstd +except ImportError: + zstd = None + +try: + import lz4.frame as lz4 + + def _lz4_compress(payload, **kwargs): + # Kafka does not support LZ4 dependent blocks + try: + # For lz4>=0.12.0 + kwargs.pop('block_linked', None) + return lz4.compress(payload, block_linked=False, **kwargs) + except TypeError: + # For earlier versions of lz4 + kwargs.pop('block_mode', None) + return lz4.compress(payload, block_mode=1, **kwargs) + +except ImportError: + lz4 = None + +try: + import lz4f +except ImportError: + lz4f = None + +try: + import lz4framed +except ImportError: + lz4framed = None + +try: + import xxhash +except ImportError: + xxhash = None + +PYPY = bool(platform.python_implementation() == 'PyPy') + +def has_gzip(): + return True + + +def has_snappy(): + return snappy is not None + + +def has_zstd(): + return zstd is not None + + +def has_lz4(): + if lz4 is not None: + return True + if lz4f is not None: + return True + if lz4framed is not None: + return True + return False + + +def gzip_encode(payload, compresslevel=None): + if not compresslevel: + compresslevel = 9 + + buf = io.BytesIO() + + # Gzip context manager introduced in python 2.7 + # so old-fashioned way until we decide to not support 2.6 + gzipper = gzip.GzipFile(fileobj=buf, mode="w", compresslevel=compresslevel) + try: + gzipper.write(payload) + finally: + gzipper.close() + + return buf.getvalue() + + +def gzip_decode(payload): + buf = io.BytesIO(payload) + + # Gzip context manager introduced in python 2.7 + # so old-fashioned way until we decide to not support 2.6 + gzipper = gzip.GzipFile(fileobj=buf, mode='r') + try: + return gzipper.read() + finally: + gzipper.close() + + +def snappy_encode(payload, xerial_compatible=True, xerial_blocksize=32*1024): + """Encodes the given data with snappy compression. + + If xerial_compatible is set then the stream is encoded in a fashion + compatible with the xerial snappy library. + + The block size (xerial_blocksize) controls how frequent the blocking occurs + 32k is the default in the xerial library. + + The format winds up being: + + + +-------------+------------+--------------+------------+--------------+ + | Header | Block1 len | Block1 data | Blockn len | Blockn data | + +-------------+------------+--------------+------------+--------------+ + | 16 bytes | BE int32 | snappy bytes | BE int32 | snappy bytes | + +-------------+------------+--------------+------------+--------------+ + + + It is important to note that the blocksize is the amount of uncompressed + data presented to snappy at each block, whereas the blocklen is the number + of bytes that will be present in the stream; so the length will always be + <= blocksize. + + """ + + if not has_snappy(): + raise NotImplementedError("Snappy codec is not available") + + if not xerial_compatible: + return snappy.compress(payload) + + out = io.BytesIO() + for fmt, dat in zip(_XERIAL_V1_FORMAT, _XERIAL_V1_HEADER): + out.write(struct.pack('!' + fmt, dat)) + + # Chunk through buffers to avoid creating intermediate slice copies + if PYPY: + # on pypy, snappy.compress() on a sliced buffer consumes the entire + # buffer... likely a python-snappy bug, so just use a slice copy + chunker = lambda payload, i, size: payload[i:size+i] + + elif six.PY2: + # Sliced buffer avoids additional copies + # pylint: disable-msg=undefined-variable + chunker = lambda payload, i, size: buffer(payload, i, size) + else: + # snappy.compress does not like raw memoryviews, so we have to convert + # tobytes, which is a copy... oh well. it's the thought that counts. + # pylint: disable-msg=undefined-variable + chunker = lambda payload, i, size: memoryview(payload)[i:size+i].tobytes() + + for chunk in (chunker(payload, i, xerial_blocksize) + for i in range(0, len(payload), xerial_blocksize)): + + block = snappy.compress(chunk) + block_size = len(block) + out.write(struct.pack('!i', block_size)) + out.write(block) + + return out.getvalue() + + +def _detect_xerial_stream(payload): + """Detects if the data given might have been encoded with the blocking mode + of the xerial snappy library. + + This mode writes a magic header of the format: + +--------+--------------+------------+---------+--------+ + | Marker | Magic String | Null / Pad | Version | Compat | + +--------+--------------+------------+---------+--------+ + | byte | c-string | byte | int32 | int32 | + +--------+--------------+------------+---------+--------+ + | -126 | 'SNAPPY' | \0 | | | + +--------+--------------+------------+---------+--------+ + + The pad appears to be to ensure that SNAPPY is a valid cstring + The version is the version of this format as written by xerial, + in the wild this is currently 1 as such we only support v1. + + Compat is there to claim the miniumum supported version that + can read a xerial block stream, presently in the wild this is + 1. + """ + + if len(payload) > 16: + header = struct.unpack('!' + _XERIAL_V1_FORMAT, bytes(payload)[:16]) + return header == _XERIAL_V1_HEADER + return False + + +def snappy_decode(payload): + if not has_snappy(): + raise NotImplementedError("Snappy codec is not available") + + if _detect_xerial_stream(payload): + # TODO ? Should become a fileobj ? + out = io.BytesIO() + byt = payload[16:] + length = len(byt) + cursor = 0 + + while cursor < length: + block_size = struct.unpack_from('!i', byt[cursor:])[0] + # Skip the block size + cursor += 4 + end = cursor + block_size + out.write(snappy.decompress(byt[cursor:end])) + cursor = end + + out.seek(0) + return out.read() + else: + return snappy.decompress(payload) + + +if lz4: + lz4_encode = _lz4_compress # pylint: disable-msg=no-member +elif lz4f: + lz4_encode = lz4f.compressFrame # pylint: disable-msg=no-member +elif lz4framed: + lz4_encode = lz4framed.compress # pylint: disable-msg=no-member +else: + lz4_encode = None + + +def lz4f_decode(payload): + """Decode payload using interoperable LZ4 framing. Requires Kafka >= 0.10""" + # pylint: disable-msg=no-member + ctx = lz4f.createDecompContext() + data = lz4f.decompressFrame(payload, ctx) + lz4f.freeDecompContext(ctx) + + # lz4f python module does not expose how much of the payload was + # actually read if the decompression was only partial. + if data['next'] != 0: + raise RuntimeError('lz4f unable to decompress full payload') + return data['decomp'] + + +if lz4: + lz4_decode = lz4.decompress # pylint: disable-msg=no-member +elif lz4f: + lz4_decode = lz4f_decode +elif lz4framed: + lz4_decode = lz4framed.decompress # pylint: disable-msg=no-member +else: + lz4_decode = None + + +def lz4_encode_old_kafka(payload): + """Encode payload for 0.8/0.9 brokers -- requires an incorrect header checksum.""" + assert xxhash is not None + data = lz4_encode(payload) + header_size = 7 + flg = data[4] + if not isinstance(flg, int): + flg = ord(flg) + + content_size_bit = ((flg >> 3) & 1) + if content_size_bit: + # Old kafka does not accept the content-size field + # so we need to discard it and reset the header flag + flg -= 8 + data = bytearray(data) + data[4] = flg + data = bytes(data) + payload = data[header_size+8:] + else: + payload = data[header_size:] + + # This is the incorrect hc + hc = xxhash.xxh32(data[0:header_size-1]).digest()[-2:-1] # pylint: disable-msg=no-member + + return b''.join([ + data[0:header_size-1], + hc, + payload + ]) + + +def lz4_decode_old_kafka(payload): + assert xxhash is not None + # Kafka's LZ4 code has a bug in its header checksum implementation + header_size = 7 + if isinstance(payload[4], int): + flg = payload[4] + else: + flg = ord(payload[4]) + content_size_bit = ((flg >> 3) & 1) + if content_size_bit: + header_size += 8 + + # This should be the correct hc + hc = xxhash.xxh32(payload[4:header_size-1]).digest()[-2:-1] # pylint: disable-msg=no-member + + munged_payload = b''.join([ + payload[0:header_size-1], + hc, + payload[header_size:] + ]) + return lz4_decode(munged_payload) + + +def zstd_encode(payload): + if not zstd: + raise NotImplementedError("Zstd codec is not available") + return zstd.ZstdCompressor().compress(payload) + + +def zstd_decode(payload): + if not zstd: + raise NotImplementedError("Zstd codec is not available") + try: + return zstd.ZstdDecompressor().decompress(payload) + except zstd.ZstdError: + return zstd.ZstdDecompressor().decompress(payload, max_output_size=ZSTD_MAX_OUTPUT_SIZE) diff --git a/testbed/dpkp__kafka-python/kafka/conn.py b/testbed/dpkp__kafka-python/kafka/conn.py new file mode 100644 index 0000000000000000000000000000000000000000..cac354875a2656c6ff5e3a09eaac52a5f05a8e31 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/conn.py @@ -0,0 +1,1534 @@ +from __future__ import absolute_import, division + +import copy +import errno +import io +import logging +from random import shuffle, uniform + +# selectors in stdlib as of py3.4 +try: + import selectors # pylint: disable=import-error +except ImportError: + # vendored backport module + from kafka.vendor import selectors34 as selectors + +import socket +import struct +import threading +import time + +from kafka.vendor import six + +import kafka.errors as Errors +from kafka.future import Future +from kafka.metrics.stats import Avg, Count, Max, Rate +from kafka.oauth.abstract import AbstractTokenProvider +from kafka.protocol.admin import SaslHandShakeRequest, DescribeAclsRequest_v2, DescribeClientQuotasRequest +from kafka.protocol.commit import OffsetFetchRequest +from kafka.protocol.offset import OffsetRequest +from kafka.protocol.produce import ProduceRequest +from kafka.protocol.metadata import MetadataRequest +from kafka.protocol.fetch import FetchRequest +from kafka.protocol.parser import KafkaProtocol +from kafka.protocol.types import Int32, Int8 +from kafka.scram import ScramClient +from kafka.version import __version__ + + +if six.PY2: + ConnectionError = socket.error + TimeoutError = socket.error + BlockingIOError = Exception + +log = logging.getLogger(__name__) + +DEFAULT_KAFKA_PORT = 9092 + +SASL_QOP_AUTH = 1 +SASL_QOP_AUTH_INT = 2 +SASL_QOP_AUTH_CONF = 4 + +try: + import ssl + ssl_available = True + try: + SSLEOFError = ssl.SSLEOFError + SSLWantReadError = ssl.SSLWantReadError + SSLWantWriteError = ssl.SSLWantWriteError + SSLZeroReturnError = ssl.SSLZeroReturnError + except AttributeError: + # support older ssl libraries + log.warning('Old SSL module detected.' + ' SSL error handling may not operate cleanly.' + ' Consider upgrading to Python 3.3 or 2.7.9') + SSLEOFError = ssl.SSLError + SSLWantReadError = ssl.SSLError + SSLWantWriteError = ssl.SSLError + SSLZeroReturnError = ssl.SSLError +except ImportError: + # support Python without ssl libraries + ssl_available = False + class SSLWantReadError(Exception): + pass + class SSLWantWriteError(Exception): + pass + +# needed for SASL_GSSAPI authentication: +try: + import gssapi + from gssapi.raw.misc import GSSError +except ImportError: + #no gssapi available, will disable gssapi mechanism + gssapi = None + GSSError = None + + +AFI_NAMES = { + socket.AF_UNSPEC: "unspecified", + socket.AF_INET: "IPv4", + socket.AF_INET6: "IPv6", +} + + +class ConnectionStates(object): + DISCONNECTING = '' + DISCONNECTED = '' + CONNECTING = '' + HANDSHAKE = '' + CONNECTED = '' + AUTHENTICATING = '' + + +class BrokerConnection(object): + """Initialize a Kafka broker connection + + Keyword Arguments: + client_id (str): a name for this client. This string is passed in + each request to servers and can be used to identify specific + server-side log entries that correspond to this client. Also + submitted to GroupCoordinator for logging with respect to + consumer group administration. Default: 'kafka-python-{version}' + reconnect_backoff_ms (int): The amount of time in milliseconds to + wait before attempting to reconnect to a given host. + Default: 50. + reconnect_backoff_max_ms (int): The maximum amount of time in + milliseconds to backoff/wait when reconnecting to a broker that has + repeatedly failed to connect. If provided, the backoff per host + will increase exponentially for each consecutive connection + failure, up to this maximum. Once the maximum is reached, + reconnection attempts will continue periodically with this fixed + rate. To avoid connection storms, a randomization factor of 0.2 + will be applied to the backoff resulting in a random range between + 20% below and 20% above the computed value. Default: 1000. + request_timeout_ms (int): Client request timeout in milliseconds. + Default: 30000. + max_in_flight_requests_per_connection (int): Requests are pipelined + to kafka brokers up to this number of maximum requests per + broker connection. Default: 5. + receive_buffer_bytes (int): The size of the TCP receive buffer + (SO_RCVBUF) to use when reading data. Default: None (relies on + system defaults). Java client defaults to 32768. + send_buffer_bytes (int): The size of the TCP send buffer + (SO_SNDBUF) to use when sending data. Default: None (relies on + system defaults). Java client defaults to 131072. + socket_options (list): List of tuple-arguments to socket.setsockopt + to apply to broker connection sockets. Default: + [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] + security_protocol (str): Protocol used to communicate with brokers. + Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL. + Default: PLAINTEXT. + ssl_context (ssl.SSLContext): pre-configured SSLContext for wrapping + socket connections. If provided, all other ssl_* configurations + will be ignored. Default: None. + ssl_check_hostname (bool): flag to configure whether ssl handshake + should verify that the certificate matches the brokers hostname. + default: True. + ssl_cafile (str): optional filename of ca file to use in certificate + verification. default: None. + ssl_certfile (str): optional filename of file in pem format containing + the client certificate, as well as any ca certificates needed to + establish the certificate's authenticity. default: None. + ssl_keyfile (str): optional filename containing the client private key. + default: None. + ssl_password (callable, str, bytes, bytearray): optional password or + callable function that returns a password, for decrypting the + client private key. Default: None. + ssl_crlfile (str): optional filename containing the CRL to check for + certificate expiration. By default, no CRL check is done. When + providing a file, only the leaf certificate will be checked against + this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+. + default: None. + ssl_ciphers (str): optionally set the available ciphers for ssl + connections. It should be a string in the OpenSSL cipher list + format. If no cipher can be selected (because compile-time options + or other configuration forbids use of all the specified ciphers), + an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers + api_version (tuple): Specify which Kafka API version to use. + Accepted values are: (0, 8, 0), (0, 8, 1), (0, 8, 2), (0, 9), + (0, 10). Default: (0, 8, 2) + api_version_auto_timeout_ms (int): number of milliseconds to throw a + timeout exception from the constructor when checking the broker + api version. Only applies if api_version is None + selector (selectors.BaseSelector): Provide a specific selector + implementation to use for I/O multiplexing. + Default: selectors.DefaultSelector + state_change_callback (callable): function to be called when the + connection state changes from CONNECTING to CONNECTED etc. + metrics (kafka.metrics.Metrics): Optionally provide a metrics + instance for capturing network IO stats. Default: None. + metric_group_prefix (str): Prefix for metric names. Default: '' + sasl_mechanism (str): Authentication mechanism when security_protocol + is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are: + PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512. + sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_kerberos_service_name (str): Service name to include in GSSAPI + sasl mechanism handshake. Default: 'kafka' + sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI + sasl mechanism handshake. Default: one of bootstrap servers + sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider + instance. (See kafka.oauth.abstract). Default: None + """ + + DEFAULT_CONFIG = { + 'client_id': 'kafka-python-' + __version__, + 'node_id': 0, + 'request_timeout_ms': 30000, + 'reconnect_backoff_ms': 50, + 'reconnect_backoff_max_ms': 1000, + 'max_in_flight_requests_per_connection': 5, + 'receive_buffer_bytes': None, + 'send_buffer_bytes': None, + 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)], + 'sock_chunk_bytes': 4096, # undocumented experimental option + 'sock_chunk_buffer_count': 1000, # undocumented experimental option + 'security_protocol': 'PLAINTEXT', + 'ssl_context': None, + 'ssl_check_hostname': True, + 'ssl_cafile': None, + 'ssl_certfile': None, + 'ssl_keyfile': None, + 'ssl_crlfile': None, + 'ssl_password': None, + 'ssl_ciphers': None, + 'api_version': (0, 8, 2), # default to most restrictive + 'selector': selectors.DefaultSelector, + 'state_change_callback': lambda node_id, sock, conn: True, + 'metrics': None, + 'metric_group_prefix': '', + 'sasl_mechanism': None, + 'sasl_plain_username': None, + 'sasl_plain_password': None, + 'sasl_kerberos_service_name': 'kafka', + 'sasl_kerberos_domain_name': None, + 'sasl_oauth_token_provider': None + } + SECURITY_PROTOCOLS = ('PLAINTEXT', 'SSL', 'SASL_PLAINTEXT', 'SASL_SSL') + SASL_MECHANISMS = ('PLAIN', 'GSSAPI', 'OAUTHBEARER', "SCRAM-SHA-256", "SCRAM-SHA-512") + + def __init__(self, host, port, afi, **configs): + self.host = host + self.port = port + self.afi = afi + self._sock_afi = afi + self._sock_addr = None + self._api_versions = None + + self.config = copy.copy(self.DEFAULT_CONFIG) + for key in self.config: + if key in configs: + self.config[key] = configs[key] + + self.node_id = self.config.pop('node_id') + + if self.config['receive_buffer_bytes'] is not None: + self.config['socket_options'].append( + (socket.SOL_SOCKET, socket.SO_RCVBUF, + self.config['receive_buffer_bytes'])) + if self.config['send_buffer_bytes'] is not None: + self.config['socket_options'].append( + (socket.SOL_SOCKET, socket.SO_SNDBUF, + self.config['send_buffer_bytes'])) + + assert self.config['security_protocol'] in self.SECURITY_PROTOCOLS, ( + 'security_protocol must be in ' + ', '.join(self.SECURITY_PROTOCOLS)) + + if self.config['security_protocol'] in ('SSL', 'SASL_SSL'): + assert ssl_available, "Python wasn't built with SSL support" + + if self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL'): + assert self.config['sasl_mechanism'] in self.SASL_MECHANISMS, ( + 'sasl_mechanism must be in ' + ', '.join(self.SASL_MECHANISMS)) + if self.config['sasl_mechanism'] in ('PLAIN', 'SCRAM-SHA-256', 'SCRAM-SHA-512'): + assert self.config['sasl_plain_username'] is not None, ( + 'sasl_plain_username required for PLAIN or SCRAM sasl' + ) + assert self.config['sasl_plain_password'] is not None, ( + 'sasl_plain_password required for PLAIN or SCRAM sasl' + ) + if self.config['sasl_mechanism'] == 'GSSAPI': + assert gssapi is not None, 'GSSAPI lib not available' + assert self.config['sasl_kerberos_service_name'] is not None, 'sasl_kerberos_service_name required for GSSAPI sasl' + if self.config['sasl_mechanism'] == 'OAUTHBEARER': + token_provider = self.config['sasl_oauth_token_provider'] + assert token_provider is not None, 'sasl_oauth_token_provider required for OAUTHBEARER sasl' + assert callable(getattr(token_provider, "token", None)), 'sasl_oauth_token_provider must implement method #token()' + # This is not a general lock / this class is not generally thread-safe yet + # However, to avoid pushing responsibility for maintaining + # per-connection locks to the upstream client, we will use this lock to + # make sure that access to the protocol buffer is synchronized + # when sends happen on multiple threads + self._lock = threading.Lock() + + # the protocol parser instance manages actual tracking of the + # sequence of in-flight requests to responses, which should + # function like a FIFO queue. For additional request data, + # including tracking request futures and timestamps, we + # can use a simple dictionary of correlation_id => request data + self.in_flight_requests = dict() + + self._protocol = KafkaProtocol( + client_id=self.config['client_id'], + api_version=self.config['api_version']) + self.state = ConnectionStates.DISCONNECTED + self._reset_reconnect_backoff() + self._sock = None + self._send_buffer = b'' + self._ssl_context = None + if self.config['ssl_context'] is not None: + self._ssl_context = self.config['ssl_context'] + self._sasl_auth_future = None + self.last_attempt = 0 + self._gai = [] + self._sensors = None + if self.config['metrics']: + self._sensors = BrokerConnectionMetrics(self.config['metrics'], + self.config['metric_group_prefix'], + self.node_id) + + def _dns_lookup(self): + self._gai = dns_lookup(self.host, self.port, self.afi) + if not self._gai: + log.error('DNS lookup failed for %s:%i (%s)', + self.host, self.port, self.afi) + return False + return True + + def _next_afi_sockaddr(self): + if not self._gai: + if not self._dns_lookup(): + return + afi, _, __, ___, sockaddr = self._gai.pop(0) + return (afi, sockaddr) + + def connect_blocking(self, timeout=float('inf')): + if self.connected(): + return True + timeout += time.time() + # First attempt to perform dns lookup + # note that the underlying interface, socket.getaddrinfo, + # has no explicit timeout so we may exceed the user-specified timeout + self._dns_lookup() + + # Loop once over all returned dns entries + selector = None + while self._gai: + while time.time() < timeout: + self.connect() + if self.connected(): + if selector is not None: + selector.close() + return True + elif self.connecting(): + if selector is None: + selector = self.config['selector']() + selector.register(self._sock, selectors.EVENT_WRITE) + selector.select(1) + elif self.disconnected(): + if selector is not None: + selector.close() + selector = None + break + else: + break + return False + + def connect(self): + """Attempt to connect and return ConnectionState""" + if self.state is ConnectionStates.DISCONNECTED and not self.blacked_out(): + self.last_attempt = time.time() + next_lookup = self._next_afi_sockaddr() + if not next_lookup: + self.close(Errors.KafkaConnectionError('DNS failure')) + return self.state + else: + log.debug('%s: creating new socket', self) + assert self._sock is None + self._sock_afi, self._sock_addr = next_lookup + self._sock = socket.socket(self._sock_afi, socket.SOCK_STREAM) + + for option in self.config['socket_options']: + log.debug('%s: setting socket option %s', self, option) + self._sock.setsockopt(*option) + + self._sock.setblocking(False) + self.state = ConnectionStates.CONNECTING + self.config['state_change_callback'](self.node_id, self._sock, self) + log.info('%s: connecting to %s:%d [%s %s]', self, self.host, + self.port, self._sock_addr, AFI_NAMES[self._sock_afi]) + + if self.state is ConnectionStates.CONNECTING: + # in non-blocking mode, use repeated calls to socket.connect_ex + # to check connection status + ret = None + try: + ret = self._sock.connect_ex(self._sock_addr) + except socket.error as err: + ret = err.errno + + # Connection succeeded + if not ret or ret == errno.EISCONN: + log.debug('%s: established TCP connection', self) + + if self.config['security_protocol'] in ('SSL', 'SASL_SSL'): + log.debug('%s: initiating SSL handshake', self) + self.state = ConnectionStates.HANDSHAKE + self.config['state_change_callback'](self.node_id, self._sock, self) + # _wrap_ssl can alter the connection state -- disconnects on failure + self._wrap_ssl() + + elif self.config['security_protocol'] == 'SASL_PLAINTEXT': + log.debug('%s: initiating SASL authentication', self) + self.state = ConnectionStates.AUTHENTICATING + self.config['state_change_callback'](self.node_id, self._sock, self) + + else: + # security_protocol PLAINTEXT + log.info('%s: Connection complete.', self) + self.state = ConnectionStates.CONNECTED + self._reset_reconnect_backoff() + self.config['state_change_callback'](self.node_id, self._sock, self) + + # Connection failed + # WSAEINVAL == 10022, but errno.WSAEINVAL is not available on non-win systems + elif ret not in (errno.EINPROGRESS, errno.EALREADY, errno.EWOULDBLOCK, 10022): + log.error('Connect attempt to %s returned error %s.' + ' Disconnecting.', self, ret) + errstr = errno.errorcode.get(ret, 'UNKNOWN') + self.close(Errors.KafkaConnectionError('{} {}'.format(ret, errstr))) + return self.state + + # Needs retry + else: + pass + + if self.state is ConnectionStates.HANDSHAKE: + if self._try_handshake(): + log.debug('%s: completed SSL handshake.', self) + if self.config['security_protocol'] == 'SASL_SSL': + log.debug('%s: initiating SASL authentication', self) + self.state = ConnectionStates.AUTHENTICATING + else: + log.info('%s: Connection complete.', self) + self.state = ConnectionStates.CONNECTED + self._reset_reconnect_backoff() + self.config['state_change_callback'](self.node_id, self._sock, self) + + if self.state is ConnectionStates.AUTHENTICATING: + assert self.config['security_protocol'] in ('SASL_PLAINTEXT', 'SASL_SSL') + if self._try_authenticate(): + # _try_authenticate has side-effects: possibly disconnected on socket errors + if self.state is ConnectionStates.AUTHENTICATING: + log.info('%s: Connection complete.', self) + self.state = ConnectionStates.CONNECTED + self._reset_reconnect_backoff() + self.config['state_change_callback'](self.node_id, self._sock, self) + + if self.state not in (ConnectionStates.CONNECTED, + ConnectionStates.DISCONNECTED): + # Connection timed out + request_timeout = self.config['request_timeout_ms'] / 1000.0 + if time.time() > request_timeout + self.last_attempt: + log.error('Connection attempt to %s timed out', self) + self.close(Errors.KafkaConnectionError('timeout')) + return self.state + + return self.state + + def _wrap_ssl(self): + assert self.config['security_protocol'] in ('SSL', 'SASL_SSL') + if self._ssl_context is None: + log.debug('%s: configuring default SSL Context', self) + self._ssl_context = ssl.SSLContext(ssl.PROTOCOL_SSLv23) # pylint: disable=no-member + self._ssl_context.options |= ssl.OP_NO_SSLv2 # pylint: disable=no-member + self._ssl_context.options |= ssl.OP_NO_SSLv3 # pylint: disable=no-member + self._ssl_context.verify_mode = ssl.CERT_OPTIONAL + if self.config['ssl_check_hostname']: + self._ssl_context.check_hostname = True + if self.config['ssl_cafile']: + log.info('%s: Loading SSL CA from %s', self, self.config['ssl_cafile']) + self._ssl_context.load_verify_locations(self.config['ssl_cafile']) + self._ssl_context.verify_mode = ssl.CERT_REQUIRED + else: + log.info('%s: Loading system default SSL CAs from %s', self, ssl.get_default_verify_paths()) + self._ssl_context.load_default_certs() + if self.config['ssl_certfile'] and self.config['ssl_keyfile']: + log.info('%s: Loading SSL Cert from %s', self, self.config['ssl_certfile']) + log.info('%s: Loading SSL Key from %s', self, self.config['ssl_keyfile']) + self._ssl_context.load_cert_chain( + certfile=self.config['ssl_certfile'], + keyfile=self.config['ssl_keyfile'], + password=self.config['ssl_password']) + if self.config['ssl_crlfile']: + if not hasattr(ssl, 'VERIFY_CRL_CHECK_LEAF'): + raise RuntimeError('This version of Python does not support ssl_crlfile!') + log.info('%s: Loading SSL CRL from %s', self, self.config['ssl_crlfile']) + self._ssl_context.load_verify_locations(self.config['ssl_crlfile']) + # pylint: disable=no-member + self._ssl_context.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF + if self.config['ssl_ciphers']: + log.info('%s: Setting SSL Ciphers: %s', self, self.config['ssl_ciphers']) + self._ssl_context.set_ciphers(self.config['ssl_ciphers']) + log.debug('%s: wrapping socket in ssl context', self) + try: + self._sock = self._ssl_context.wrap_socket( + self._sock, + server_hostname=self.host, + do_handshake_on_connect=False) + except ssl.SSLError as e: + log.exception('%s: Failed to wrap socket in SSLContext!', self) + self.close(e) + + def _try_handshake(self): + assert self.config['security_protocol'] in ('SSL', 'SASL_SSL') + try: + self._sock.do_handshake() + return True + # old ssl in python2.6 will swallow all SSLErrors here... + except (SSLWantReadError, SSLWantWriteError): + pass + except (SSLZeroReturnError, ConnectionError, TimeoutError, SSLEOFError): + log.warning('SSL connection closed by server during handshake.') + self.close(Errors.KafkaConnectionError('SSL connection closed by server during handshake')) + # Other SSLErrors will be raised to user + + return False + + def _try_authenticate(self): + assert self.config['api_version'] is None or self.config['api_version'] >= (0, 10) + + if self._sasl_auth_future is None: + # Build a SaslHandShakeRequest message + request = SaslHandShakeRequest[0](self.config['sasl_mechanism']) + future = Future() + sasl_response = self._send(request) + sasl_response.add_callback(self._handle_sasl_handshake_response, future) + sasl_response.add_errback(lambda f, e: f.failure(e), future) + self._sasl_auth_future = future + + for r, f in self.recv(): + f.success(r) + + # A connection error could trigger close() which will reset the future + if self._sasl_auth_future is None: + return False + elif self._sasl_auth_future.failed(): + ex = self._sasl_auth_future.exception + if not isinstance(ex, Errors.KafkaConnectionError): + raise ex # pylint: disable-msg=raising-bad-type + return self._sasl_auth_future.succeeded() + + def _handle_sasl_handshake_response(self, future, response): + error_type = Errors.for_code(response.error_code) + if error_type is not Errors.NoError: + error = error_type(self) + self.close(error=error) + return future.failure(error_type(self)) + + if self.config['sasl_mechanism'] not in response.enabled_mechanisms: + return future.failure( + Errors.UnsupportedSaslMechanismError( + 'Kafka broker does not support %s sasl mechanism. Enabled mechanisms are: %s' + % (self.config['sasl_mechanism'], response.enabled_mechanisms))) + elif self.config['sasl_mechanism'] == 'PLAIN': + return self._try_authenticate_plain(future) + elif self.config['sasl_mechanism'] == 'GSSAPI': + return self._try_authenticate_gssapi(future) + elif self.config['sasl_mechanism'] == 'OAUTHBEARER': + return self._try_authenticate_oauth(future) + elif self.config['sasl_mechanism'].startswith("SCRAM-SHA-"): + return self._try_authenticate_scram(future) + else: + return future.failure( + Errors.UnsupportedSaslMechanismError( + 'kafka-python does not support SASL mechanism %s' % + self.config['sasl_mechanism'])) + + def _send_bytes(self, data): + """Send some data via non-blocking IO + + Note: this method is not synchronized internally; you should + always hold the _lock before calling + + Returns: number of bytes + Raises: socket exception + """ + total_sent = 0 + while total_sent < len(data): + try: + sent_bytes = self._sock.send(data[total_sent:]) + total_sent += sent_bytes + except (SSLWantReadError, SSLWantWriteError): + break + except (ConnectionError, TimeoutError) as e: + if six.PY2 and e.errno == errno.EWOULDBLOCK: + break + raise + except BlockingIOError: + if six.PY3: + break + raise + return total_sent + + def _send_bytes_blocking(self, data): + self._sock.settimeout(self.config['request_timeout_ms'] / 1000) + total_sent = 0 + try: + while total_sent < len(data): + sent_bytes = self._sock.send(data[total_sent:]) + total_sent += sent_bytes + if total_sent != len(data): + raise ConnectionError('Buffer overrun during socket send') + return total_sent + finally: + self._sock.settimeout(0.0) + + def _recv_bytes_blocking(self, n): + self._sock.settimeout(self.config['request_timeout_ms'] / 1000) + try: + data = b'' + while len(data) < n: + fragment = self._sock.recv(n - len(data)) + if not fragment: + raise ConnectionError('Connection reset during recv') + data += fragment + return data + finally: + self._sock.settimeout(0.0) + + def _try_authenticate_plain(self, future): + if self.config['security_protocol'] == 'SASL_PLAINTEXT': + log.warning('%s: Sending username and password in the clear', self) + + data = b'' + # Send PLAIN credentials per RFC-4616 + msg = bytes('\0'.join([self.config['sasl_plain_username'], + self.config['sasl_plain_username'], + self.config['sasl_plain_password']]).encode('utf-8')) + size = Int32.encode(len(msg)) + + err = None + close = False + with self._lock: + if not self._can_send_recv(): + err = Errors.NodeNotReadyError(str(self)) + close = False + else: + try: + self._send_bytes_blocking(size + msg) + + # The server will send a zero sized message (that is Int32(0)) on success. + # The connection is closed on failure + data = self._recv_bytes_blocking(4) + + except (ConnectionError, TimeoutError) as e: + log.exception("%s: Error receiving reply from server", self) + err = Errors.KafkaConnectionError("%s: %s" % (self, e)) + close = True + + if err is not None: + if close: + self.close(error=err) + return future.failure(err) + + if data != b'\x00\x00\x00\x00': + error = Errors.AuthenticationFailedError('Unrecognized response during authentication') + return future.failure(error) + + log.info('%s: Authenticated as %s via PLAIN', self, self.config['sasl_plain_username']) + return future.success(True) + + def _try_authenticate_scram(self, future): + if self.config['security_protocol'] == 'SASL_PLAINTEXT': + log.warning('%s: Exchanging credentials in the clear', self) + + scram_client = ScramClient( + self.config['sasl_plain_username'], self.config['sasl_plain_password'], self.config['sasl_mechanism'] + ) + + err = None + close = False + with self._lock: + if not self._can_send_recv(): + err = Errors.NodeNotReadyError(str(self)) + close = False + else: + try: + client_first = scram_client.first_message().encode('utf-8') + size = Int32.encode(len(client_first)) + self._send_bytes_blocking(size + client_first) + + (data_len,) = struct.unpack('>i', self._recv_bytes_blocking(4)) + server_first = self._recv_bytes_blocking(data_len).decode('utf-8') + scram_client.process_server_first_message(server_first) + + client_final = scram_client.final_message().encode('utf-8') + size = Int32.encode(len(client_final)) + self._send_bytes_blocking(size + client_final) + + (data_len,) = struct.unpack('>i', self._recv_bytes_blocking(4)) + server_final = self._recv_bytes_blocking(data_len).decode('utf-8') + scram_client.process_server_final_message(server_final) + + except (ConnectionError, TimeoutError) as e: + log.exception("%s: Error receiving reply from server", self) + err = Errors.KafkaConnectionError("%s: %s" % (self, e)) + close = True + + if err is not None: + if close: + self.close(error=err) + return future.failure(err) + + log.info( + '%s: Authenticated as %s via %s', self, self.config['sasl_plain_username'], self.config['sasl_mechanism'] + ) + return future.success(True) + + def _try_authenticate_gssapi(self, future): + kerberos_damin_name = self.config['sasl_kerberos_domain_name'] or self.host + auth_id = self.config['sasl_kerberos_service_name'] + '@' + kerberos_damin_name + gssapi_name = gssapi.Name( + auth_id, + name_type=gssapi.NameType.hostbased_service + ).canonicalize(gssapi.MechType.kerberos) + log.debug('%s: GSSAPI name: %s', self, gssapi_name) + + err = None + close = False + with self._lock: + if not self._can_send_recv(): + err = Errors.NodeNotReadyError(str(self)) + close = False + else: + # Establish security context and negotiate protection level + # For reference RFC 2222, section 7.2.1 + try: + # Exchange tokens until authentication either succeeds or fails + client_ctx = gssapi.SecurityContext(name=gssapi_name, usage='initiate') + received_token = None + while not client_ctx.complete: + # calculate an output token from kafka token (or None if first iteration) + output_token = client_ctx.step(received_token) + + # pass output token to kafka, or send empty response if the security + # context is complete (output token is None in that case) + if output_token is None: + self._send_bytes_blocking(Int32.encode(0)) + else: + msg = output_token + size = Int32.encode(len(msg)) + self._send_bytes_blocking(size + msg) + + # The server will send a token back. Processing of this token either + # establishes a security context, or it needs further token exchange. + # The gssapi will be able to identify the needed next step. + # The connection is closed on failure. + header = self._recv_bytes_blocking(4) + (token_size,) = struct.unpack('>i', header) + received_token = self._recv_bytes_blocking(token_size) + + # Process the security layer negotiation token, sent by the server + # once the security context is established. + + # unwraps message containing supported protection levels and msg size + msg = client_ctx.unwrap(received_token).message + # Kafka currently doesn't support integrity or confidentiality security layers, so we + # simply set QoP to 'auth' only (first octet). We reuse the max message size proposed + # by the server + msg = Int8.encode(SASL_QOP_AUTH & Int8.decode(io.BytesIO(msg[0:1]))) + msg[1:] + # add authorization identity to the response, GSS-wrap and send it + msg = client_ctx.wrap(msg + auth_id.encode(), False).message + size = Int32.encode(len(msg)) + self._send_bytes_blocking(size + msg) + + except (ConnectionError, TimeoutError) as e: + log.exception("%s: Error receiving reply from server", self) + err = Errors.KafkaConnectionError("%s: %s" % (self, e)) + close = True + except Exception as e: + err = e + close = True + + if err is not None: + if close: + self.close(error=err) + return future.failure(err) + + log.info('%s: Authenticated as %s via GSSAPI', self, gssapi_name) + return future.success(True) + + def _try_authenticate_oauth(self, future): + data = b'' + + msg = bytes(self._build_oauth_client_request().encode("utf-8")) + size = Int32.encode(len(msg)) + + err = None + close = False + with self._lock: + if not self._can_send_recv(): + err = Errors.NodeNotReadyError(str(self)) + close = False + else: + try: + # Send SASL OAuthBearer request with OAuth token + self._send_bytes_blocking(size + msg) + + # The server will send a zero sized message (that is Int32(0)) on success. + # The connection is closed on failure + data = self._recv_bytes_blocking(4) + + except (ConnectionError, TimeoutError) as e: + log.exception("%s: Error receiving reply from server", self) + err = Errors.KafkaConnectionError("%s: %s" % (self, e)) + close = True + + if err is not None: + if close: + self.close(error=err) + return future.failure(err) + + if data != b'\x00\x00\x00\x00': + error = Errors.AuthenticationFailedError('Unrecognized response during authentication') + return future.failure(error) + + log.info('%s: Authenticated via OAuth', self) + return future.success(True) + + def _build_oauth_client_request(self): + token_provider = self.config['sasl_oauth_token_provider'] + return "n,,\x01auth=Bearer {}{}\x01\x01".format(token_provider.token(), self._token_extensions()) + + def _token_extensions(self): + """ + Return a string representation of the OPTIONAL key-value pairs that can be sent with an OAUTHBEARER + initial request. + """ + token_provider = self.config['sasl_oauth_token_provider'] + + # Only run if the #extensions() method is implemented by the clients Token Provider class + # Builds up a string separated by \x01 via a dict of key value pairs + if callable(getattr(token_provider, "extensions", None)) and len(token_provider.extensions()) > 0: + msg = "\x01".join(["{}={}".format(k, v) for k, v in token_provider.extensions().items()]) + return "\x01" + msg + else: + return "" + + def blacked_out(self): + """ + Return true if we are disconnected from the given node and can't + re-establish a connection yet + """ + if self.state is ConnectionStates.DISCONNECTED: + if time.time() < self.last_attempt + self._reconnect_backoff: + return True + return False + + def connection_delay(self): + """ + Return the number of milliseconds to wait, based on the connection + state, before attempting to send data. When disconnected, this respects + the reconnect backoff time. When connecting or connected, returns a very + large number to handle slow/stalled connections. + """ + time_waited = time.time() - (self.last_attempt or 0) + if self.state is ConnectionStates.DISCONNECTED: + return max(self._reconnect_backoff - time_waited, 0) * 1000 + else: + # When connecting or connected, we should be able to delay + # indefinitely since other events (connection or data acked) will + # cause a wakeup once data can be sent. + return float('inf') + + def connected(self): + """Return True iff socket is connected.""" + return self.state is ConnectionStates.CONNECTED + + def connecting(self): + """Returns True if still connecting (this may encompass several + different states, such as SSL handshake, authorization, etc).""" + return self.state in (ConnectionStates.CONNECTING, + ConnectionStates.HANDSHAKE, + ConnectionStates.AUTHENTICATING) + + def disconnected(self): + """Return True iff socket is closed""" + return self.state is ConnectionStates.DISCONNECTED + + def _reset_reconnect_backoff(self): + self._failures = 0 + self._reconnect_backoff = self.config['reconnect_backoff_ms'] / 1000.0 + + def _update_reconnect_backoff(self): + # Do not mark as failure if there are more dns entries available to try + if len(self._gai) > 0: + return + if self.config['reconnect_backoff_max_ms'] > self.config['reconnect_backoff_ms']: + self._failures += 1 + self._reconnect_backoff = self.config['reconnect_backoff_ms'] * 2 ** (self._failures - 1) + self._reconnect_backoff = min(self._reconnect_backoff, self.config['reconnect_backoff_max_ms']) + self._reconnect_backoff *= uniform(0.8, 1.2) + self._reconnect_backoff /= 1000.0 + log.debug('%s: reconnect backoff %s after %s failures', self, self._reconnect_backoff, self._failures) + + def _close_socket(self): + if hasattr(self, '_sock') and self._sock is not None: + self._sock.close() + self._sock = None + + def __del__(self): + self._close_socket() + + def close(self, error=None): + """Close socket and fail all in-flight-requests. + + Arguments: + error (Exception, optional): pending in-flight-requests + will be failed with this exception. + Default: kafka.errors.KafkaConnectionError. + """ + if self.state is ConnectionStates.DISCONNECTED: + return + with self._lock: + if self.state is ConnectionStates.DISCONNECTED: + return + log.info('%s: Closing connection. %s', self, error or '') + self._update_reconnect_backoff() + self._sasl_auth_future = None + self._protocol = KafkaProtocol( + client_id=self.config['client_id'], + api_version=self.config['api_version']) + self._send_buffer = b'' + if error is None: + error = Errors.Cancelled(str(self)) + ifrs = list(self.in_flight_requests.items()) + self.in_flight_requests.clear() + self.state = ConnectionStates.DISCONNECTED + # To avoid race conditions and/or deadlocks + # keep a reference to the socket but leave it + # open until after the state_change_callback + # This should give clients a change to deregister + # the socket fd from selectors cleanly. + sock = self._sock + self._sock = None + + # drop lock before state change callback and processing futures + self.config['state_change_callback'](self.node_id, sock, self) + sock.close() + for (_correlation_id, (future, _timestamp)) in ifrs: + future.failure(error) + + def _can_send_recv(self): + """Return True iff socket is ready for requests / responses""" + return self.state in (ConnectionStates.AUTHENTICATING, + ConnectionStates.CONNECTED) + + def send(self, request, blocking=True): + """Queue request for async network send, return Future()""" + future = Future() + if self.connecting(): + return future.failure(Errors.NodeNotReadyError(str(self))) + elif not self.connected(): + return future.failure(Errors.KafkaConnectionError(str(self))) + elif not self.can_send_more(): + return future.failure(Errors.TooManyInFlightRequests(str(self))) + return self._send(request, blocking=blocking) + + def _send(self, request, blocking=True): + future = Future() + with self._lock: + if not self._can_send_recv(): + # In this case, since we created the future above, + # we know there are no callbacks/errbacks that could fire w/ + # lock. So failing + returning inline should be safe + return future.failure(Errors.NodeNotReadyError(str(self))) + + correlation_id = self._protocol.send_request(request) + + log.debug('%s Request %d: %s', self, correlation_id, request) + if request.expect_response(): + sent_time = time.time() + assert correlation_id not in self.in_flight_requests, 'Correlation ID already in-flight!' + self.in_flight_requests[correlation_id] = (future, sent_time) + else: + future.success(None) + + # Attempt to replicate behavior from prior to introduction of + # send_pending_requests() / async sends + if blocking: + self.send_pending_requests() + + return future + + def send_pending_requests(self): + """Attempts to send pending requests messages via blocking IO + If all requests have been sent, return True + Otherwise, if the socket is blocked and there are more bytes to send, + return False. + """ + try: + with self._lock: + if not self._can_send_recv(): + return False + data = self._protocol.send_bytes() + total_bytes = self._send_bytes_blocking(data) + + if self._sensors: + self._sensors.bytes_sent.record(total_bytes) + return True + + except (ConnectionError, TimeoutError) as e: + log.exception("Error sending request data to %s", self) + error = Errors.KafkaConnectionError("%s: %s" % (self, e)) + self.close(error=error) + return False + + def send_pending_requests_v2(self): + """Attempts to send pending requests messages via non-blocking IO + If all requests have been sent, return True + Otherwise, if the socket is blocked and there are more bytes to send, + return False. + """ + try: + with self._lock: + if not self._can_send_recv(): + return False + + # _protocol.send_bytes returns encoded requests to send + # we send them via _send_bytes() + # and hold leftover bytes in _send_buffer + if not self._send_buffer: + self._send_buffer = self._protocol.send_bytes() + + total_bytes = 0 + if self._send_buffer: + total_bytes = self._send_bytes(self._send_buffer) + self._send_buffer = self._send_buffer[total_bytes:] + + if self._sensors: + self._sensors.bytes_sent.record(total_bytes) + # Return True iff send buffer is empty + return len(self._send_buffer) == 0 + + except (ConnectionError, TimeoutError, Exception) as e: + log.exception("Error sending request data to %s", self) + error = Errors.KafkaConnectionError("%s: %s" % (self, e)) + self.close(error=error) + return False + + def can_send_more(self): + """Return True unless there are max_in_flight_requests_per_connection.""" + max_ifrs = self.config['max_in_flight_requests_per_connection'] + return len(self.in_flight_requests) < max_ifrs + + def recv(self): + """Non-blocking network receive. + + Return list of (response, future) tuples + """ + responses = self._recv() + if not responses and self.requests_timed_out(): + log.warning('%s timed out after %s ms. Closing connection.', + self, self.config['request_timeout_ms']) + self.close(error=Errors.RequestTimedOutError( + 'Request timed out after %s ms' % + self.config['request_timeout_ms'])) + return () + + # augment responses w/ correlation_id, future, and timestamp + for i, (correlation_id, response) in enumerate(responses): + try: + with self._lock: + (future, timestamp) = self.in_flight_requests.pop(correlation_id) + except KeyError: + self.close(Errors.KafkaConnectionError('Received unrecognized correlation id')) + return () + latency_ms = (time.time() - timestamp) * 1000 + if self._sensors: + self._sensors.request_time.record(latency_ms) + + log.debug('%s Response %d (%s ms): %s', self, correlation_id, latency_ms, response) + responses[i] = (response, future) + + return responses + + def _recv(self): + """Take all available bytes from socket, return list of any responses from parser""" + recvd = [] + err = None + with self._lock: + if not self._can_send_recv(): + log.warning('%s cannot recv: socket not connected', self) + return () + + while len(recvd) < self.config['sock_chunk_buffer_count']: + try: + data = self._sock.recv(self.config['sock_chunk_bytes']) + # We expect socket.recv to raise an exception if there are no + # bytes available to read from the socket in non-blocking mode. + # but if the socket is disconnected, we will get empty data + # without an exception raised + if not data: + log.error('%s: socket disconnected', self) + err = Errors.KafkaConnectionError('socket disconnected') + break + else: + recvd.append(data) + + except (SSLWantReadError, SSLWantWriteError): + break + except (ConnectionError, TimeoutError) as e: + if six.PY2 and e.errno == errno.EWOULDBLOCK: + break + log.exception('%s: Error receiving network data' + ' closing socket', self) + err = Errors.KafkaConnectionError(e) + break + except BlockingIOError: + if six.PY3: + break + # For PY2 this is a catchall and should be re-raised + raise + + # Only process bytes if there was no connection exception + if err is None: + recvd_data = b''.join(recvd) + if self._sensors: + self._sensors.bytes_received.record(len(recvd_data)) + + # We need to keep the lock through protocol receipt + # so that we ensure that the processed byte order is the + # same as the received byte order + try: + return self._protocol.receive_bytes(recvd_data) + except Errors.KafkaProtocolError as e: + err = e + + self.close(error=err) + return () + + def requests_timed_out(self): + with self._lock: + if self.in_flight_requests: + get_timestamp = lambda v: v[1] + oldest_at = min(map(get_timestamp, + self.in_flight_requests.values())) + timeout = self.config['request_timeout_ms'] / 1000.0 + if time.time() >= oldest_at + timeout: + return True + return False + + def _handle_api_version_response(self, response): + error_type = Errors.for_code(response.error_code) + assert error_type is Errors.NoError, "API version check failed" + self._api_versions = dict([ + (api_key, (min_version, max_version)) + for api_key, min_version, max_version in response.api_versions + ]) + return self._api_versions + + def get_api_versions(self): + if self._api_versions is not None: + return self._api_versions + + version = self.check_version() + if version < (0, 10, 0): + raise Errors.UnsupportedVersionError( + "ApiVersion not supported by cluster version {} < 0.10.0" + .format(version)) + # _api_versions is set as a side effect of check_versions() on a cluster + # that supports 0.10.0 or later + return self._api_versions + + def _infer_broker_version_from_api_versions(self, api_versions): + # The logic here is to check the list of supported request versions + # in reverse order. As soon as we find one that works, return it + test_cases = [ + # format (, ) + ((2, 6, 0), DescribeClientQuotasRequest[0]), + ((2, 5, 0), DescribeAclsRequest_v2), + ((2, 4, 0), ProduceRequest[8]), + ((2, 3, 0), FetchRequest[11]), + ((2, 2, 0), OffsetRequest[5]), + ((2, 1, 0), FetchRequest[10]), + ((2, 0, 0), FetchRequest[8]), + ((1, 1, 0), FetchRequest[7]), + ((1, 0, 0), MetadataRequest[5]), + ((0, 11, 0), MetadataRequest[4]), + ((0, 10, 2), OffsetFetchRequest[2]), + ((0, 10, 1), MetadataRequest[2]), + ] + + # Get the best match of test cases + for broker_version, struct in sorted(test_cases, reverse=True): + if struct.API_KEY not in api_versions: + continue + min_version, max_version = api_versions[struct.API_KEY] + if min_version <= struct.API_VERSION <= max_version: + return broker_version + + # We know that ApiVersionResponse is only supported in 0.10+ + # so if all else fails, choose that + return (0, 10, 0) + + def check_version(self, timeout=2, strict=False, topics=[]): + """Attempt to guess the broker version. + + Note: This is a blocking call. + + Returns: version tuple, i.e. (0, 10), (0, 9), (0, 8, 2), ... + """ + timeout_at = time.time() + timeout + log.info('Probing node %s broker version', self.node_id) + # Monkeypatch some connection configurations to avoid timeouts + override_config = { + 'request_timeout_ms': timeout * 1000, + 'max_in_flight_requests_per_connection': 5 + } + stashed = {} + for key in override_config: + stashed[key] = self.config[key] + self.config[key] = override_config[key] + + def reset_override_configs(): + for key in stashed: + self.config[key] = stashed[key] + + # kafka kills the connection when it doesn't recognize an API request + # so we can send a test request and then follow immediately with a + # vanilla MetadataRequest. If the server did not recognize the first + # request, both will be failed with a ConnectionError that wraps + # socket.error (32, 54, or 104) + from kafka.protocol.admin import ApiVersionRequest, ListGroupsRequest + from kafka.protocol.commit import OffsetFetchRequest, GroupCoordinatorRequest + + test_cases = [ + # All cases starting from 0.10 will be based on ApiVersionResponse + ((0, 10), ApiVersionRequest[0]()), + ((0, 9), ListGroupsRequest[0]()), + ((0, 8, 2), GroupCoordinatorRequest[0]('kafka-python-default-group')), + ((0, 8, 1), OffsetFetchRequest[0]('kafka-python-default-group', [])), + ((0, 8, 0), MetadataRequest[0](topics)), + ] + + for version, request in test_cases: + if not self.connect_blocking(timeout_at - time.time()): + reset_override_configs() + raise Errors.NodeNotReadyError() + f = self.send(request) + # HACK: sleeping to wait for socket to send bytes + time.sleep(0.1) + # when broker receives an unrecognized request API + # it abruptly closes our socket. + # so we attempt to send a second request immediately + # that we believe it will definitely recognize (metadata) + # the attempt to write to a disconnected socket should + # immediately fail and allow us to infer that the prior + # request was unrecognized + mr = self.send(MetadataRequest[0](topics)) + + selector = self.config['selector']() + selector.register(self._sock, selectors.EVENT_READ) + while not (f.is_done and mr.is_done): + selector.select(1) + for response, future in self.recv(): + future.success(response) + selector.close() + + if f.succeeded(): + if isinstance(request, ApiVersionRequest[0]): + # Starting from 0.10 kafka broker we determine version + # by looking at ApiVersionResponse + api_versions = self._handle_api_version_response(f.value) + version = self._infer_broker_version_from_api_versions(api_versions) + log.info('Broker version identified as %s', '.'.join(map(str, version))) + log.info('Set configuration api_version=%s to skip auto' + ' check_version requests on startup', version) + break + + # Only enable strict checking to verify that we understand failure + # modes. For most users, the fact that the request failed should be + # enough to rule out a particular broker version. + if strict: + # If the socket flush hack did not work (which should force the + # connection to close and fail all pending requests), then we + # get a basic Request Timeout. This is not ideal, but we'll deal + if isinstance(f.exception, Errors.RequestTimedOutError): + pass + + # 0.9 brokers do not close the socket on unrecognized api + # requests (bug...). In this case we expect to see a correlation + # id mismatch + elif (isinstance(f.exception, Errors.CorrelationIdError) and + version == (0, 10)): + pass + elif six.PY2: + assert isinstance(f.exception.args[0], socket.error) + assert f.exception.args[0].errno in (32, 54, 104) + else: + assert isinstance(f.exception.args[0], ConnectionError) + log.info("Broker is not v%s -- it did not recognize %s", + version, request.__class__.__name__) + else: + reset_override_configs() + raise Errors.UnrecognizedBrokerVersion() + + reset_override_configs() + return version + + def __str__(self): + return "" % ( + self.node_id, self.host, self.port, self.state, + AFI_NAMES[self._sock_afi], self._sock_addr) + + +class BrokerConnectionMetrics(object): + def __init__(self, metrics, metric_group_prefix, node_id): + self.metrics = metrics + + # Any broker may have registered summary metrics already + # but if not, we need to create them so we can set as parents below + all_conns_transferred = metrics.get_sensor('bytes-sent-received') + if not all_conns_transferred: + metric_group_name = metric_group_prefix + '-metrics' + + bytes_transferred = metrics.sensor('bytes-sent-received') + bytes_transferred.add(metrics.metric_name( + 'network-io-rate', metric_group_name, + 'The average number of network operations (reads or writes) on all' + ' connections per second.'), Rate(sampled_stat=Count())) + + bytes_sent = metrics.sensor('bytes-sent', + parents=[bytes_transferred]) + bytes_sent.add(metrics.metric_name( + 'outgoing-byte-rate', metric_group_name, + 'The average number of outgoing bytes sent per second to all' + ' servers.'), Rate()) + bytes_sent.add(metrics.metric_name( + 'request-rate', metric_group_name, + 'The average number of requests sent per second.'), + Rate(sampled_stat=Count())) + bytes_sent.add(metrics.metric_name( + 'request-size-avg', metric_group_name, + 'The average size of all requests in the window.'), Avg()) + bytes_sent.add(metrics.metric_name( + 'request-size-max', metric_group_name, + 'The maximum size of any request sent in the window.'), Max()) + + bytes_received = metrics.sensor('bytes-received', + parents=[bytes_transferred]) + bytes_received.add(metrics.metric_name( + 'incoming-byte-rate', metric_group_name, + 'Bytes/second read off all sockets'), Rate()) + bytes_received.add(metrics.metric_name( + 'response-rate', metric_group_name, + 'Responses received sent per second.'), + Rate(sampled_stat=Count())) + + request_latency = metrics.sensor('request-latency') + request_latency.add(metrics.metric_name( + 'request-latency-avg', metric_group_name, + 'The average request latency in ms.'), + Avg()) + request_latency.add(metrics.metric_name( + 'request-latency-max', metric_group_name, + 'The maximum request latency in ms.'), + Max()) + + # if one sensor of the metrics has been registered for the connection, + # then all other sensors should have been registered; and vice versa + node_str = 'node-{0}'.format(node_id) + node_sensor = metrics.get_sensor(node_str + '.bytes-sent') + if not node_sensor: + metric_group_name = metric_group_prefix + '-node-metrics.' + node_str + + bytes_sent = metrics.sensor( + node_str + '.bytes-sent', + parents=[metrics.get_sensor('bytes-sent')]) + bytes_sent.add(metrics.metric_name( + 'outgoing-byte-rate', metric_group_name, + 'The average number of outgoing bytes sent per second.'), + Rate()) + bytes_sent.add(metrics.metric_name( + 'request-rate', metric_group_name, + 'The average number of requests sent per second.'), + Rate(sampled_stat=Count())) + bytes_sent.add(metrics.metric_name( + 'request-size-avg', metric_group_name, + 'The average size of all requests in the window.'), + Avg()) + bytes_sent.add(metrics.metric_name( + 'request-size-max', metric_group_name, + 'The maximum size of any request sent in the window.'), + Max()) + + bytes_received = metrics.sensor( + node_str + '.bytes-received', + parents=[metrics.get_sensor('bytes-received')]) + bytes_received.add(metrics.metric_name( + 'incoming-byte-rate', metric_group_name, + 'Bytes/second read off node-connection socket'), + Rate()) + bytes_received.add(metrics.metric_name( + 'response-rate', metric_group_name, + 'The average number of responses received per second.'), + Rate(sampled_stat=Count())) + + request_time = metrics.sensor( + node_str + '.latency', + parents=[metrics.get_sensor('request-latency')]) + request_time.add(metrics.metric_name( + 'request-latency-avg', metric_group_name, + 'The average request latency in ms.'), + Avg()) + request_time.add(metrics.metric_name( + 'request-latency-max', metric_group_name, + 'The maximum request latency in ms.'), + Max()) + + self.bytes_sent = metrics.sensor(node_str + '.bytes-sent') + self.bytes_received = metrics.sensor(node_str + '.bytes-received') + self.request_time = metrics.sensor(node_str + '.latency') + + +def _address_family(address): + """ + Attempt to determine the family of an address (or hostname) + + :return: either socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC if the address family + could not be determined + """ + if address.startswith('[') and address.endswith(']'): + return socket.AF_INET6 + for af in (socket.AF_INET, socket.AF_INET6): + try: + socket.inet_pton(af, address) + return af + except (ValueError, AttributeError, socket.error): + continue + return socket.AF_UNSPEC + + +def get_ip_port_afi(host_and_port_str): + """ + Parse the IP and port from a string in the format of: + + * host_or_ip <- Can be either IPv4 address literal or hostname/fqdn + * host_or_ipv4:port <- Can be either IPv4 address literal or hostname/fqdn + * [host_or_ip] <- IPv6 address literal + * [host_or_ip]:port. <- IPv6 address literal + + .. note:: IPv6 address literals with ports *must* be enclosed in brackets + + .. note:: If the port is not specified, default will be returned. + + :return: tuple (host, port, afi), afi will be socket.AF_INET or socket.AF_INET6 or socket.AF_UNSPEC + """ + host_and_port_str = host_and_port_str.strip() + if host_and_port_str.startswith('['): + af = socket.AF_INET6 + host, rest = host_and_port_str[1:].split(']') + if rest: + port = int(rest[1:]) + else: + port = DEFAULT_KAFKA_PORT + return host, port, af + else: + if ':' not in host_and_port_str: + af = _address_family(host_and_port_str) + return host_and_port_str, DEFAULT_KAFKA_PORT, af + else: + # now we have something with a colon in it and no square brackets. It could be + # either an IPv6 address literal (e.g., "::1") or an IP:port pair or a host:port pair + try: + # if it decodes as an IPv6 address, use that + socket.inet_pton(socket.AF_INET6, host_and_port_str) + return host_and_port_str, DEFAULT_KAFKA_PORT, socket.AF_INET6 + except AttributeError: + log.warning('socket.inet_pton not available on this platform.' + ' consider `pip install win_inet_pton`') + pass + except (ValueError, socket.error): + # it's a host:port pair + pass + host, port = host_and_port_str.rsplit(':', 1) + port = int(port) + + af = _address_family(host) + return host, port, af + + +def collect_hosts(hosts, randomize=True): + """ + Collects a comma-separated set of hosts (host:port) and optionally + randomize the returned list. + """ + + if isinstance(hosts, six.string_types): + hosts = hosts.strip().split(',') + + result = [] + afi = socket.AF_INET + for host_port in hosts: + + host, port, afi = get_ip_port_afi(host_port) + + if port < 0: + port = DEFAULT_KAFKA_PORT + + result.append((host, port, afi)) + + if randomize: + shuffle(result) + + return result + + +def is_inet_4_or_6(gai): + """Given a getaddrinfo struct, return True iff ipv4 or ipv6""" + return gai[0] in (socket.AF_INET, socket.AF_INET6) + + +def dns_lookup(host, port, afi=socket.AF_UNSPEC): + """Returns a list of getaddrinfo structs, optionally filtered to an afi (ipv4 / ipv6)""" + # XXX: all DNS functions in Python are blocking. If we really + # want to be non-blocking here, we need to use a 3rd-party + # library like python-adns, or move resolution onto its + # own thread. This will be subject to the default libc + # name resolution timeout (5s on most Linux boxes) + try: + return list(filter(is_inet_4_or_6, + socket.getaddrinfo(host, port, afi, + socket.SOCK_STREAM))) + except socket.gaierror as ex: + log.warning('DNS lookup failed for %s:%d,' + ' exception was %s. Is your' + ' advertised.listeners (called' + ' advertised.host.name before Kafka 9)' + ' correct and resolvable?', + host, port, ex) + return [] diff --git a/testbed/dpkp__kafka-python/kafka/errors.py b/testbed/dpkp__kafka-python/kafka/errors.py new file mode 100644 index 0000000000000000000000000000000000000000..b33cf51e248491cf6f21472fc2c8c2f7360ce6cc --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/errors.py @@ -0,0 +1,538 @@ +from __future__ import absolute_import + +import inspect +import sys + + +class KafkaError(RuntimeError): + retriable = False + # whether metadata should be refreshed on error + invalid_metadata = False + + def __str__(self): + if not self.args: + return self.__class__.__name__ + return '{0}: {1}'.format(self.__class__.__name__, + super(KafkaError, self).__str__()) + + +class IllegalStateError(KafkaError): + pass + + +class IllegalArgumentError(KafkaError): + pass + + +class NoBrokersAvailable(KafkaError): + retriable = True + invalid_metadata = True + + +class NodeNotReadyError(KafkaError): + retriable = True + + +class KafkaProtocolError(KafkaError): + retriable = True + + +class CorrelationIdError(KafkaProtocolError): + retriable = True + + +class Cancelled(KafkaError): + retriable = True + + +class TooManyInFlightRequests(KafkaError): + retriable = True + + +class StaleMetadata(KafkaError): + retriable = True + invalid_metadata = True + + +class MetadataEmptyBrokerList(KafkaError): + retriable = True + + +class UnrecognizedBrokerVersion(KafkaError): + pass + + +class IncompatibleBrokerVersion(KafkaError): + pass + + +class CommitFailedError(KafkaError): + def __init__(self, *args, **kwargs): + super(CommitFailedError, self).__init__( + """Commit cannot be completed since the group has already + rebalanced and assigned the partitions to another member. + This means that the time between subsequent calls to poll() + was longer than the configured max_poll_interval_ms, which + typically implies that the poll loop is spending too much + time message processing. You can address this either by + increasing the rebalance timeout with max_poll_interval_ms, + or by reducing the maximum size of batches returned in poll() + with max_poll_records. + """, *args, **kwargs) + + +class AuthenticationMethodNotSupported(KafkaError): + pass + + +class AuthenticationFailedError(KafkaError): + retriable = False + + +class BrokerResponseError(KafkaError): + errno = None + message = None + description = None + + def __str__(self): + """Add errno to standard KafkaError str""" + return '[Error {0}] {1}'.format( + self.errno, + super(BrokerResponseError, self).__str__()) + + +class NoError(BrokerResponseError): + errno = 0 + message = 'NO_ERROR' + description = 'No error--it worked!' + + +class UnknownError(BrokerResponseError): + errno = -1 + message = 'UNKNOWN' + description = 'An unexpected server error.' + + +class OffsetOutOfRangeError(BrokerResponseError): + errno = 1 + message = 'OFFSET_OUT_OF_RANGE' + description = ('The requested offset is outside the range of offsets' + ' maintained by the server for the given topic/partition.') + + +class CorruptRecordException(BrokerResponseError): + errno = 2 + message = 'CORRUPT_MESSAGE' + description = ('This message has failed its CRC checksum, exceeds the' + ' valid size, or is otherwise corrupt.') + +# Backward compatibility +InvalidMessageError = CorruptRecordException + + +class UnknownTopicOrPartitionError(BrokerResponseError): + errno = 3 + message = 'UNKNOWN_TOPIC_OR_PARTITION' + description = ('This request is for a topic or partition that does not' + ' exist on this broker.') + retriable = True + invalid_metadata = True + + +class InvalidFetchRequestError(BrokerResponseError): + errno = 4 + message = 'INVALID_FETCH_SIZE' + description = 'The message has a negative size.' + + +class LeaderNotAvailableError(BrokerResponseError): + errno = 5 + message = 'LEADER_NOT_AVAILABLE' + description = ('This error is thrown if we are in the middle of a' + ' leadership election and there is currently no leader for' + ' this partition and hence it is unavailable for writes.') + retriable = True + invalid_metadata = True + + +class NotLeaderForPartitionError(BrokerResponseError): + errno = 6 + message = 'NOT_LEADER_FOR_PARTITION' + description = ('This error is thrown if the client attempts to send' + ' messages to a replica that is not the leader for some' + ' partition. It indicates that the clients metadata is out' + ' of date.') + retriable = True + invalid_metadata = True + + +class RequestTimedOutError(BrokerResponseError): + errno = 7 + message = 'REQUEST_TIMED_OUT' + description = ('This error is thrown if the request exceeds the' + ' user-specified time limit in the request.') + retriable = True + + +class BrokerNotAvailableError(BrokerResponseError): + errno = 8 + message = 'BROKER_NOT_AVAILABLE' + description = ('This is not a client facing error and is used mostly by' + ' tools when a broker is not alive.') + + +class ReplicaNotAvailableError(BrokerResponseError): + errno = 9 + message = 'REPLICA_NOT_AVAILABLE' + description = ('If replica is expected on a broker, but is not (this can be' + ' safely ignored).') + + +class MessageSizeTooLargeError(BrokerResponseError): + errno = 10 + message = 'MESSAGE_SIZE_TOO_LARGE' + description = ('The server has a configurable maximum message size to avoid' + ' unbounded memory allocation. This error is thrown if the' + ' client attempt to produce a message larger than this' + ' maximum.') + + +class StaleControllerEpochError(BrokerResponseError): + errno = 11 + message = 'STALE_CONTROLLER_EPOCH' + description = 'Internal error code for broker-to-broker communication.' + + +class OffsetMetadataTooLargeError(BrokerResponseError): + errno = 12 + message = 'OFFSET_METADATA_TOO_LARGE' + description = ('If you specify a string larger than configured maximum for' + ' offset metadata.') + + +# TODO is this deprecated? https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-ErrorCodes +class StaleLeaderEpochCodeError(BrokerResponseError): + errno = 13 + message = 'STALE_LEADER_EPOCH_CODE' + + +class GroupLoadInProgressError(BrokerResponseError): + errno = 14 + message = 'OFFSETS_LOAD_IN_PROGRESS' + description = ('The broker returns this error code for an offset fetch' + ' request if it is still loading offsets (after a leader' + ' change for that offsets topic partition), or in response' + ' to group membership requests (such as heartbeats) when' + ' group metadata is being loaded by the coordinator.') + retriable = True + + +class GroupCoordinatorNotAvailableError(BrokerResponseError): + errno = 15 + message = 'CONSUMER_COORDINATOR_NOT_AVAILABLE' + description = ('The broker returns this error code for group coordinator' + ' requests, offset commits, and most group management' + ' requests if the offsets topic has not yet been created, or' + ' if the group coordinator is not active.') + retriable = True + + +class NotCoordinatorForGroupError(BrokerResponseError): + errno = 16 + message = 'NOT_COORDINATOR_FOR_CONSUMER' + description = ('The broker returns this error code if it receives an offset' + ' fetch or commit request for a group that it is not a' + ' coordinator for.') + retriable = True + + +class InvalidTopicError(BrokerResponseError): + errno = 17 + message = 'INVALID_TOPIC' + description = ('For a request which attempts to access an invalid topic' + ' (e.g. one which has an illegal name), or if an attempt' + ' is made to write to an internal topic (such as the' + ' consumer offsets topic).') + + +class RecordListTooLargeError(BrokerResponseError): + errno = 18 + message = 'RECORD_LIST_TOO_LARGE' + description = ('If a message batch in a produce request exceeds the maximum' + ' configured segment size.') + + +class NotEnoughReplicasError(BrokerResponseError): + errno = 19 + message = 'NOT_ENOUGH_REPLICAS' + description = ('Returned from a produce request when the number of in-sync' + ' replicas is lower than the configured minimum and' + ' requiredAcks is -1.') + retriable = True + + +class NotEnoughReplicasAfterAppendError(BrokerResponseError): + errno = 20 + message = 'NOT_ENOUGH_REPLICAS_AFTER_APPEND' + description = ('Returned from a produce request when the message was' + ' written to the log, but with fewer in-sync replicas than' + ' required.') + retriable = True + + +class InvalidRequiredAcksError(BrokerResponseError): + errno = 21 + message = 'INVALID_REQUIRED_ACKS' + description = ('Returned from a produce request if the requested' + ' requiredAcks is invalid (anything other than -1, 1, or 0).') + + +class IllegalGenerationError(BrokerResponseError): + errno = 22 + message = 'ILLEGAL_GENERATION' + description = ('Returned from group membership requests (such as heartbeats)' + ' when the generation id provided in the request is not the' + ' current generation.') + + +class InconsistentGroupProtocolError(BrokerResponseError): + errno = 23 + message = 'INCONSISTENT_GROUP_PROTOCOL' + description = ('Returned in join group when the member provides a protocol' + ' type or set of protocols which is not compatible with the' + ' current group.') + + +class InvalidGroupIdError(BrokerResponseError): + errno = 24 + message = 'INVALID_GROUP_ID' + description = 'Returned in join group when the groupId is empty or null.' + + +class UnknownMemberIdError(BrokerResponseError): + errno = 25 + message = 'UNKNOWN_MEMBER_ID' + description = ('Returned from group requests (offset commits/fetches,' + ' heartbeats, etc) when the memberId is not in the current' + ' generation.') + + +class InvalidSessionTimeoutError(BrokerResponseError): + errno = 26 + message = 'INVALID_SESSION_TIMEOUT' + description = ('Return in join group when the requested session timeout is' + ' outside of the allowed range on the broker') + + +class RebalanceInProgressError(BrokerResponseError): + errno = 27 + message = 'REBALANCE_IN_PROGRESS' + description = ('Returned in heartbeat requests when the coordinator has' + ' begun rebalancing the group. This indicates to the client' + ' that it should rejoin the group.') + + +class InvalidCommitOffsetSizeError(BrokerResponseError): + errno = 28 + message = 'INVALID_COMMIT_OFFSET_SIZE' + description = ('This error indicates that an offset commit was rejected' + ' because of oversize metadata.') + + +class TopicAuthorizationFailedError(BrokerResponseError): + errno = 29 + message = 'TOPIC_AUTHORIZATION_FAILED' + description = ('Returned by the broker when the client is not authorized to' + ' access the requested topic.') + + +class GroupAuthorizationFailedError(BrokerResponseError): + errno = 30 + message = 'GROUP_AUTHORIZATION_FAILED' + description = ('Returned by the broker when the client is not authorized to' + ' access a particular groupId.') + + +class ClusterAuthorizationFailedError(BrokerResponseError): + errno = 31 + message = 'CLUSTER_AUTHORIZATION_FAILED' + description = ('Returned by the broker when the client is not authorized to' + ' use an inter-broker or administrative API.') + + +class InvalidTimestampError(BrokerResponseError): + errno = 32 + message = 'INVALID_TIMESTAMP' + description = 'The timestamp of the message is out of acceptable range.' + + +class UnsupportedSaslMechanismError(BrokerResponseError): + errno = 33 + message = 'UNSUPPORTED_SASL_MECHANISM' + description = 'The broker does not support the requested SASL mechanism.' + + +class IllegalSaslStateError(BrokerResponseError): + errno = 34 + message = 'ILLEGAL_SASL_STATE' + description = 'Request is not valid given the current SASL state.' + + +class UnsupportedVersionError(BrokerResponseError): + errno = 35 + message = 'UNSUPPORTED_VERSION' + description = 'The version of API is not supported.' + + +class TopicAlreadyExistsError(BrokerResponseError): + errno = 36 + message = 'TOPIC_ALREADY_EXISTS' + description = 'Topic with this name already exists.' + + +class InvalidPartitionsError(BrokerResponseError): + errno = 37 + message = 'INVALID_PARTITIONS' + description = 'Number of partitions is invalid.' + + +class InvalidReplicationFactorError(BrokerResponseError): + errno = 38 + message = 'INVALID_REPLICATION_FACTOR' + description = 'Replication-factor is invalid.' + + +class InvalidReplicationAssignmentError(BrokerResponseError): + errno = 39 + message = 'INVALID_REPLICATION_ASSIGNMENT' + description = 'Replication assignment is invalid.' + + +class InvalidConfigurationError(BrokerResponseError): + errno = 40 + message = 'INVALID_CONFIG' + description = 'Configuration is invalid.' + + +class NotControllerError(BrokerResponseError): + errno = 41 + message = 'NOT_CONTROLLER' + description = 'This is not the correct controller for this cluster.' + retriable = True + + +class InvalidRequestError(BrokerResponseError): + errno = 42 + message = 'INVALID_REQUEST' + description = ('This most likely occurs because of a request being' + ' malformed by the client library or the message was' + ' sent to an incompatible broker. See the broker logs' + ' for more details.') + + +class UnsupportedForMessageFormatError(BrokerResponseError): + errno = 43 + message = 'UNSUPPORTED_FOR_MESSAGE_FORMAT' + description = ('The message format version on the broker does not' + ' support this request.') + + +class PolicyViolationError(BrokerResponseError): + errno = 44 + message = 'POLICY_VIOLATION' + description = 'Request parameters do not satisfy the configured policy.' + + +class SecurityDisabledError(BrokerResponseError): + errno = 54 + message = 'SECURITY_DISABLED' + description = 'Security features are disabled.' + + +class NonEmptyGroupError(BrokerResponseError): + errno = 68 + message = 'NON_EMPTY_GROUP' + description = 'The group is not empty.' + + +class GroupIdNotFoundError(BrokerResponseError): + errno = 69 + message = 'GROUP_ID_NOT_FOUND' + description = 'The group id does not exist.' + + +class KafkaUnavailableError(KafkaError): + pass + + +class KafkaTimeoutError(KafkaError): + pass + + +class FailedPayloadsError(KafkaError): + def __init__(self, payload, *args): + super(FailedPayloadsError, self).__init__(*args) + self.payload = payload + + +class KafkaConnectionError(KafkaError): + retriable = True + invalid_metadata = True + + +class ProtocolError(KafkaError): + pass + + +class UnsupportedCodecError(KafkaError): + pass + + +class KafkaConfigurationError(KafkaError): + pass + + +class QuotaViolationError(KafkaError): + pass + + +class AsyncProducerQueueFull(KafkaError): + def __init__(self, failed_msgs, *args): + super(AsyncProducerQueueFull, self).__init__(*args) + self.failed_msgs = failed_msgs + + +def _iter_broker_errors(): + for name, obj in inspect.getmembers(sys.modules[__name__]): + if inspect.isclass(obj) and issubclass(obj, BrokerResponseError) and obj != BrokerResponseError: + yield obj + + +kafka_errors = dict([(x.errno, x) for x in _iter_broker_errors()]) + + +def for_code(error_code): + return kafka_errors.get(error_code, UnknownError) + + +def check_error(response): + if isinstance(response, Exception): + raise response + if response.error: + error_class = kafka_errors.get(response.error, UnknownError) + raise error_class(response) + + +RETRY_BACKOFF_ERROR_TYPES = ( + KafkaUnavailableError, LeaderNotAvailableError, + KafkaConnectionError, FailedPayloadsError +) + + +RETRY_REFRESH_ERROR_TYPES = ( + NotLeaderForPartitionError, UnknownTopicOrPartitionError, + LeaderNotAvailableError, KafkaConnectionError +) + + +RETRY_ERROR_TYPES = RETRY_BACKOFF_ERROR_TYPES + RETRY_REFRESH_ERROR_TYPES diff --git a/testbed/dpkp__kafka-python/kafka/future.py b/testbed/dpkp__kafka-python/kafka/future.py new file mode 100644 index 0000000000000000000000000000000000000000..d0f3c66581f730d1b9c1e5e74662004e96651302 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/future.py @@ -0,0 +1,83 @@ +from __future__ import absolute_import + +import functools +import logging + +log = logging.getLogger(__name__) + + +class Future(object): + error_on_callbacks = False # and errbacks + + def __init__(self): + self.is_done = False + self.value = None + self.exception = None + self._callbacks = [] + self._errbacks = [] + + def succeeded(self): + return self.is_done and not bool(self.exception) + + def failed(self): + return self.is_done and bool(self.exception) + + def retriable(self): + try: + return self.exception.retriable + except AttributeError: + return False + + def success(self, value): + assert not self.is_done, 'Future is already complete' + self.value = value + self.is_done = True + if self._callbacks: + self._call_backs('callback', self._callbacks, self.value) + return self + + def failure(self, e): + assert not self.is_done, 'Future is already complete' + self.exception = e if type(e) is not type else e() + assert isinstance(self.exception, BaseException), ( + 'future failed without an exception') + self.is_done = True + self._call_backs('errback', self._errbacks, self.exception) + return self + + def add_callback(self, f, *args, **kwargs): + if args or kwargs: + f = functools.partial(f, *args, **kwargs) + if self.is_done and not self.exception: + self._call_backs('callback', [f], self.value) + else: + self._callbacks.append(f) + return self + + def add_errback(self, f, *args, **kwargs): + if args or kwargs: + f = functools.partial(f, *args, **kwargs) + if self.is_done and self.exception: + self._call_backs('errback', [f], self.exception) + else: + self._errbacks.append(f) + return self + + def add_both(self, f, *args, **kwargs): + self.add_callback(f, *args, **kwargs) + self.add_errback(f, *args, **kwargs) + return self + + def chain(self, future): + self.add_callback(future.success) + self.add_errback(future.failure) + return self + + def _call_backs(self, back_type, backs, value): + for f in backs: + try: + f(value) + except Exception as e: + log.exception('Error processing %s', back_type) + if self.error_on_callbacks: + raise e diff --git a/testbed/dpkp__kafka-python/kafka/metrics/measurable.py b/testbed/dpkp__kafka-python/kafka/metrics/measurable.py new file mode 100644 index 0000000000000000000000000000000000000000..b06d4d789ba456af66fbf6682ac22be13869d15a --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/metrics/measurable.py @@ -0,0 +1,29 @@ +from __future__ import absolute_import + +import abc + + +class AbstractMeasurable(object): + """A measurable quantity that can be registered as a metric""" + @abc.abstractmethod + def measure(self, config, now): + """ + Measure this quantity and return the result + + Arguments: + config (MetricConfig): The configuration for this metric + now (int): The POSIX time in milliseconds the measurement + is being taken + + Returns: + The measured value + """ + raise NotImplementedError + + +class AnonMeasurable(AbstractMeasurable): + def __init__(self, measure_fn): + self._measure_fn = measure_fn + + def measure(self, config, now): + return float(self._measure_fn(config, now)) diff --git a/testbed/dpkp__kafka-python/kafka/metrics/stat.py b/testbed/dpkp__kafka-python/kafka/metrics/stat.py new file mode 100644 index 0000000000000000000000000000000000000000..9fd2f01ec5a3178eeff38a1da6d95a0f8bb6c2db --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/metrics/stat.py @@ -0,0 +1,23 @@ +from __future__ import absolute_import + +import abc + + +class AbstractStat(object): + """ + An AbstractStat is a quantity such as average, max, etc that is computed + off the stream of updates to a sensor + """ + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def record(self, config, value, time_ms): + """ + Record the given value + + Arguments: + config (MetricConfig): The configuration to use for this metric + value (float): The value to record + timeMs (int): The POSIX time in milliseconds this value occurred + """ + raise NotImplementedError diff --git a/testbed/dpkp__kafka-python/kafka/metrics/stats/sensor.py b/testbed/dpkp__kafka-python/kafka/metrics/stats/sensor.py new file mode 100644 index 0000000000000000000000000000000000000000..571723f974d003852b6099a7ac958977bfa982bd --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/metrics/stats/sensor.py @@ -0,0 +1,134 @@ +from __future__ import absolute_import + +import threading +import time + +from kafka.errors import QuotaViolationError +from kafka.metrics import KafkaMetric + + +class Sensor(object): + """ + A sensor applies a continuous sequence of numerical values + to a set of associated metrics. For example a sensor on + message size would record a sequence of message sizes using + the `record(double)` api and would maintain a set + of metrics about request sizes such as the average or max. + """ + def __init__(self, registry, name, parents, config, + inactive_sensor_expiration_time_seconds): + if not name: + raise ValueError('name must be non-empty') + self._lock = threading.RLock() + self._registry = registry + self._name = name + self._parents = parents or [] + self._metrics = [] + self._stats = [] + self._config = config + self._inactive_sensor_expiration_time_ms = ( + inactive_sensor_expiration_time_seconds * 1000) + self._last_record_time = time.time() * 1000 + self._check_forest(set()) + + def _check_forest(self, sensors): + """Validate that this sensor doesn't end up referencing itself.""" + if self in sensors: + raise ValueError('Circular dependency in sensors: %s is its own' + 'parent.' % (self.name,)) + sensors.add(self) + for parent in self._parents: + parent._check_forest(sensors) + + @property + def name(self): + """ + The name this sensor is registered with. + This name will be unique among all registered sensors. + """ + return self._name + + @property + def metrics(self): + return tuple(self._metrics) + + def record(self, value=1.0, time_ms=None): + """ + Record a value at a known time. + Arguments: + value (double): The value we are recording + time_ms (int): A POSIX timestamp in milliseconds. + Default: The time when record() is evaluated (now) + + Raises: + QuotaViolationException: if recording this value moves a + metric beyond its configured maximum or minimum bound + """ + if time_ms is None: + time_ms = time.time() * 1000 + self._last_record_time = time_ms + with self._lock: # XXX high volume, might be performance issue + # increment all the stats + for stat in self._stats: + stat.record(self._config, value, time_ms) + self._check_quotas(time_ms) + for parent in self._parents: + parent.record(value, time_ms) + + def _check_quotas(self, time_ms): + """ + Check if we have violated our quota for any metric that + has a configured quota + """ + for metric in self._metrics: + if metric.config and metric.config.quota: + value = metric.value(time_ms) + if not metric.config.quota.is_acceptable(value): + raise QuotaViolationError("'%s' violated quota. Actual: " + "%d, Threshold: %d" % + (metric.metric_name, + value, + metric.config.quota.bound)) + + def add_compound(self, compound_stat, config=None): + """ + Register a compound statistic with this sensor which + yields multiple measurable quantities (like a histogram) + + Arguments: + stat (AbstractCompoundStat): The stat to register + config (MetricConfig): The configuration for this stat. + If None then the stat will use the default configuration + for this sensor. + """ + if not compound_stat: + raise ValueError('compound stat must be non-empty') + self._stats.append(compound_stat) + for named_measurable in compound_stat.stats(): + metric = KafkaMetric(named_measurable.name, named_measurable.stat, + config or self._config) + self._registry.register_metric(metric) + self._metrics.append(metric) + + def add(self, metric_name, stat, config=None): + """ + Register a metric with this sensor + + Arguments: + metric_name (MetricName): The name of the metric + stat (AbstractMeasurableStat): The statistic to keep + config (MetricConfig): A special configuration for this metric. + If None use the sensor default configuration. + """ + with self._lock: + metric = KafkaMetric(metric_name, stat, config or self._config) + self._registry.register_metric(metric) + self._metrics.append(metric) + self._stats.append(stat) + + def has_expired(self): + """ + Return True if the Sensor is eligible for removal due to inactivity. + """ + return ((time.time() * 1000 - self._last_record_time) > + self._inactive_sensor_expiration_time_ms) diff --git a/testbed/dpkp__kafka-python/kafka/oauth/__init__.py b/testbed/dpkp__kafka-python/kafka/oauth/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8c8349564d8b7b055add18cd1ca2d7e64c40bec6 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/oauth/__init__.py @@ -0,0 +1,3 @@ +from __future__ import absolute_import + +from kafka.oauth.abstract import AbstractTokenProvider diff --git a/testbed/dpkp__kafka-python/kafka/oauth/abstract.py b/testbed/dpkp__kafka-python/kafka/oauth/abstract.py new file mode 100644 index 0000000000000000000000000000000000000000..8d89ff51d24d8fd1cd447931611ed3475bd9e780 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/oauth/abstract.py @@ -0,0 +1,42 @@ +from __future__ import absolute_import + +import abc + +# This statement is compatible with both Python 2.7 & 3+ +ABC = abc.ABCMeta('ABC', (object,), {'__slots__': ()}) + +class AbstractTokenProvider(ABC): + """ + A Token Provider must be used for the SASL OAuthBearer protocol. + + The implementation should ensure token reuse so that multiple + calls at connect time do not create multiple tokens. The implementation + should also periodically refresh the token in order to guarantee + that each call returns an unexpired token. A timeout error should + be returned after a short period of inactivity so that the + broker can log debugging info and retry. + + Token Providers MUST implement the token() method + """ + + def __init__(self, **config): + pass + + @abc.abstractmethod + def token(self): + """ + Returns a (str) ID/Access Token to be sent to the Kafka + client. + """ + pass + + def extensions(self): + """ + This is an OPTIONAL method that may be implemented. + + Returns a map of key-value pairs that can + be sent with the SASL/OAUTHBEARER initial client request. If + not implemented, the values are ignored. This feature is only available + in Kafka >= 2.1.0. + """ + return {} diff --git a/testbed/dpkp__kafka-python/kafka/partitioner/default.py b/testbed/dpkp__kafka-python/kafka/partitioner/default.py new file mode 100644 index 0000000000000000000000000000000000000000..d0914c682bb42c1dc53a1ae2bebfa5001a56c73c --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/partitioner/default.py @@ -0,0 +1,102 @@ +from __future__ import absolute_import + +import random + +from kafka.vendor import six + + +class DefaultPartitioner(object): + """Default partitioner. + + Hashes key to partition using murmur2 hashing (from java client) + If key is None, selects partition randomly from available, + or from all partitions if none are currently available + """ + @classmethod + def __call__(cls, key, all_partitions, available): + """ + Get the partition corresponding to key + :param key: partitioning key + :param all_partitions: list of all partitions sorted by partition ID + :param available: list of available partitions in no particular order + :return: one of the values from all_partitions or available + """ + if key is None: + if available: + return random.choice(available) + return random.choice(all_partitions) + + idx = murmur2(key) + idx &= 0x7fffffff + idx %= len(all_partitions) + return all_partitions[idx] + + +# https://github.com/apache/kafka/blob/0.8.2/clients/src/main/java/org/apache/kafka/common/utils/Utils.java#L244 +def murmur2(data): + """Pure-python Murmur2 implementation. + + Based on java client, see org.apache.kafka.common.utils.Utils.murmur2 + + Args: + data (bytes): opaque bytes + + Returns: MurmurHash2 of data + """ + # Python2 bytes is really a str, causing the bitwise operations below to fail + # so convert to bytearray. + if six.PY2: + data = bytearray(bytes(data)) + + length = len(data) + seed = 0x9747b28c + # 'm' and 'r' are mixing constants generated offline. + # They're not really 'magic', they just happen to work well. + m = 0x5bd1e995 + r = 24 + + # Initialize the hash to a random value + h = seed ^ length + length4 = length // 4 + + for i in range(length4): + i4 = i * 4 + k = ((data[i4 + 0] & 0xff) + + ((data[i4 + 1] & 0xff) << 8) + + ((data[i4 + 2] & 0xff) << 16) + + ((data[i4 + 3] & 0xff) << 24)) + k &= 0xffffffff + k *= m + k &= 0xffffffff + k ^= (k % 0x100000000) >> r # k ^= k >>> r + k &= 0xffffffff + k *= m + k &= 0xffffffff + + h *= m + h &= 0xffffffff + h ^= k + h &= 0xffffffff + + # Handle the last few bytes of the input array + extra_bytes = length % 4 + if extra_bytes >= 3: + h ^= (data[(length & ~3) + 2] & 0xff) << 16 + h &= 0xffffffff + if extra_bytes >= 2: + h ^= (data[(length & ~3) + 1] & 0xff) << 8 + h &= 0xffffffff + if extra_bytes >= 1: + h ^= (data[length & ~3] & 0xff) + h &= 0xffffffff + h *= m + h &= 0xffffffff + + h ^= (h % 0x100000000) >> 13 # h >>> 13; + h &= 0xffffffff + h *= m + h &= 0xffffffff + h ^= (h % 0x100000000) >> 15 # h >>> 15; + h &= 0xffffffff + + return h diff --git a/testbed/dpkp__kafka-python/kafka/producer/__init__.py b/testbed/dpkp__kafka-python/kafka/producer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..576c772a0ebf87503229f694979174730ed93c1f --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/producer/__init__.py @@ -0,0 +1,7 @@ +from __future__ import absolute_import + +from kafka.producer.kafka import KafkaProducer + +__all__ = [ + 'KafkaProducer' +] diff --git a/testbed/dpkp__kafka-python/kafka/producer/future.py b/testbed/dpkp__kafka-python/kafka/producer/future.py new file mode 100644 index 0000000000000000000000000000000000000000..07fa4adb4a4a372d84e70f00ddcb31526a8f365f --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/producer/future.py @@ -0,0 +1,71 @@ +from __future__ import absolute_import + +import collections +import threading + +from kafka import errors as Errors +from kafka.future import Future + + +class FutureProduceResult(Future): + def __init__(self, topic_partition): + super(FutureProduceResult, self).__init__() + self.topic_partition = topic_partition + self._latch = threading.Event() + + def success(self, value): + ret = super(FutureProduceResult, self).success(value) + self._latch.set() + return ret + + def failure(self, error): + ret = super(FutureProduceResult, self).failure(error) + self._latch.set() + return ret + + def wait(self, timeout=None): + # wait() on python2.6 returns None instead of the flag value + return self._latch.wait(timeout) or self._latch.is_set() + + +class FutureRecordMetadata(Future): + def __init__(self, produce_future, relative_offset, timestamp_ms, checksum, serialized_key_size, serialized_value_size, serialized_header_size): + super(FutureRecordMetadata, self).__init__() + self._produce_future = produce_future + # packing args as a tuple is a minor speed optimization + self.args = (relative_offset, timestamp_ms, checksum, serialized_key_size, serialized_value_size, serialized_header_size) + produce_future.add_callback(self._produce_success) + produce_future.add_errback(self.failure) + + def _produce_success(self, offset_and_timestamp): + offset, produce_timestamp_ms, log_start_offset = offset_and_timestamp + + # Unpacking from args tuple is minor speed optimization + (relative_offset, timestamp_ms, checksum, + serialized_key_size, serialized_value_size, serialized_header_size) = self.args + + # None is when Broker does not support the API (<0.10) and + # -1 is when the broker is configured for CREATE_TIME timestamps + if produce_timestamp_ms is not None and produce_timestamp_ms != -1: + timestamp_ms = produce_timestamp_ms + if offset != -1 and relative_offset is not None: + offset += relative_offset + tp = self._produce_future.topic_partition + metadata = RecordMetadata(tp[0], tp[1], tp, offset, timestamp_ms, log_start_offset, + checksum, serialized_key_size, + serialized_value_size, serialized_header_size) + self.success(metadata) + + def get(self, timeout=None): + if not self.is_done and not self._produce_future.wait(timeout): + raise Errors.KafkaTimeoutError( + "Timeout after waiting for %s secs." % (timeout,)) + assert self.is_done + if self.failed(): + raise self.exception # pylint: disable-msg=raising-bad-type + return self.value + + +RecordMetadata = collections.namedtuple( + 'RecordMetadata', ['topic', 'partition', 'topic_partition', 'offset', 'timestamp', 'log_start_offset', + 'checksum', 'serialized_key_size', 'serialized_value_size', 'serialized_header_size']) diff --git a/testbed/dpkp__kafka-python/kafka/producer/kafka.py b/testbed/dpkp__kafka-python/kafka/producer/kafka.py new file mode 100644 index 0000000000000000000000000000000000000000..cde26b008ce418dd980c87aa1fcd127530f65b21 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/producer/kafka.py @@ -0,0 +1,749 @@ +from __future__ import absolute_import + +import atexit +import copy +import logging +import socket +import threading +import time +import weakref + +from kafka.vendor import six + +import kafka.errors as Errors +from kafka.client_async import KafkaClient, selectors +from kafka.codec import has_gzip, has_snappy, has_lz4, has_zstd +from kafka.metrics import MetricConfig, Metrics +from kafka.partitioner.default import DefaultPartitioner +from kafka.producer.future import FutureRecordMetadata, FutureProduceResult +from kafka.producer.record_accumulator import AtomicInteger, RecordAccumulator +from kafka.producer.sender import Sender +from kafka.record.default_records import DefaultRecordBatchBuilder +from kafka.record.legacy_records import LegacyRecordBatchBuilder +from kafka.serializer import Serializer +from kafka.structs import TopicPartition + + +log = logging.getLogger(__name__) +PRODUCER_CLIENT_ID_SEQUENCE = AtomicInteger() + + +class KafkaProducer(object): + """A Kafka client that publishes records to the Kafka cluster. + + The producer is thread safe and sharing a single producer instance across + threads will generally be faster than having multiple instances. + + The producer consists of a pool of buffer space that holds records that + haven't yet been transmitted to the server as well as a background I/O + thread that is responsible for turning these records into requests and + transmitting them to the cluster. + + :meth:`~kafka.KafkaProducer.send` is asynchronous. When called it adds the + record to a buffer of pending record sends and immediately returns. This + allows the producer to batch together individual records for efficiency. + + The 'acks' config controls the criteria under which requests are considered + complete. The "all" setting will result in blocking on the full commit of + the record, the slowest but most durable setting. + + If the request fails, the producer can automatically retry, unless + 'retries' is configured to 0. Enabling retries also opens up the + possibility of duplicates (see the documentation on message + delivery semantics for details: + https://kafka.apache.org/documentation.html#semantics + ). + + The producer maintains buffers of unsent records for each partition. These + buffers are of a size specified by the 'batch_size' config. Making this + larger can result in more batching, but requires more memory (since we will + generally have one of these buffers for each active partition). + + By default a buffer is available to send immediately even if there is + additional unused space in the buffer. However if you want to reduce the + number of requests you can set 'linger_ms' to something greater than 0. + This will instruct the producer to wait up to that number of milliseconds + before sending a request in hope that more records will arrive to fill up + the same batch. This is analogous to Nagle's algorithm in TCP. Note that + records that arrive close together in time will generally batch together + even with linger_ms=0 so under heavy load batching will occur regardless of + the linger configuration; however setting this to something larger than 0 + can lead to fewer, more efficient requests when not under maximal load at + the cost of a small amount of latency. + + The buffer_memory controls the total amount of memory available to the + producer for buffering. If records are sent faster than they can be + transmitted to the server then this buffer space will be exhausted. When + the buffer space is exhausted additional send calls will block. + + The key_serializer and value_serializer instruct how to turn the key and + value objects the user provides into bytes. + + Keyword Arguments: + bootstrap_servers: 'host[:port]' string (or list of 'host[:port]' + strings) that the producer should contact to bootstrap initial + cluster metadata. This does not have to be the full node list. + It just needs to have at least one broker that will respond to a + Metadata API Request. Default port is 9092. If no servers are + specified, will default to localhost:9092. + client_id (str): a name for this client. This string is passed in + each request to servers and can be used to identify specific + server-side log entries that correspond to this client. + Default: 'kafka-python-producer-#' (appended with a unique number + per instance) + key_serializer (callable): used to convert user-supplied keys to bytes + If not None, called as f(key), should return bytes. Default: None. + value_serializer (callable): used to convert user-supplied message + values to bytes. If not None, called as f(value), should return + bytes. Default: None. + acks (0, 1, 'all'): The number of acknowledgments the producer requires + the leader to have received before considering a request complete. + This controls the durability of records that are sent. The + following settings are common: + + 0: Producer will not wait for any acknowledgment from the server. + The message will immediately be added to the socket + buffer and considered sent. No guarantee can be made that the + server has received the record in this case, and the retries + configuration will not take effect (as the client won't + generally know of any failures). The offset given back for each + record will always be set to -1. + 1: Wait for leader to write the record to its local log only. + Broker will respond without awaiting full acknowledgement from + all followers. In this case should the leader fail immediately + after acknowledging the record but before the followers have + replicated it then the record will be lost. + all: Wait for the full set of in-sync replicas to write the record. + This guarantees that the record will not be lost as long as at + least one in-sync replica remains alive. This is the strongest + available guarantee. + If unset, defaults to acks=1. + compression_type (str): The compression type for all data generated by + the producer. Valid values are 'gzip', 'snappy', 'lz4', 'zstd' or None. + Compression is of full batches of data, so the efficacy of batching + will also impact the compression ratio (more batching means better + compression). Default: None. + retries (int): Setting a value greater than zero will cause the client + to resend any record whose send fails with a potentially transient + error. Note that this retry is no different than if the client + resent the record upon receiving the error. Allowing retries + without setting max_in_flight_requests_per_connection to 1 will + potentially change the ordering of records because if two batches + are sent to a single partition, and the first fails and is retried + but the second succeeds, then the records in the second batch may + appear first. + Default: 0. + batch_size (int): Requests sent to brokers will contain multiple + batches, one for each partition with data available to be sent. + A small batch size will make batching less common and may reduce + throughput (a batch size of zero will disable batching entirely). + Default: 16384 + linger_ms (int): The producer groups together any records that arrive + in between request transmissions into a single batched request. + Normally this occurs only under load when records arrive faster + than they can be sent out. However in some circumstances the client + may want to reduce the number of requests even under moderate load. + This setting accomplishes this by adding a small amount of + artificial delay; that is, rather than immediately sending out a + record the producer will wait for up to the given delay to allow + other records to be sent so that the sends can be batched together. + This can be thought of as analogous to Nagle's algorithm in TCP. + This setting gives the upper bound on the delay for batching: once + we get batch_size worth of records for a partition it will be sent + immediately regardless of this setting, however if we have fewer + than this many bytes accumulated for this partition we will + 'linger' for the specified time waiting for more records to show + up. This setting defaults to 0 (i.e. no delay). Setting linger_ms=5 + would have the effect of reducing the number of requests sent but + would add up to 5ms of latency to records sent in the absence of + load. Default: 0. + partitioner (callable): Callable used to determine which partition + each message is assigned to. Called (after key serialization): + partitioner(key_bytes, all_partitions, available_partitions). + The default partitioner implementation hashes each non-None key + using the same murmur2 algorithm as the java client so that + messages with the same key are assigned to the same partition. + When a key is None, the message is delivered to a random partition + (filtered to partitions with available leaders only, if possible). + buffer_memory (int): The total bytes of memory the producer should use + to buffer records waiting to be sent to the server. If records are + sent faster than they can be delivered to the server the producer + will block up to max_block_ms, raising an exception on timeout. + In the current implementation, this setting is an approximation. + Default: 33554432 (32MB) + connections_max_idle_ms: Close idle connections after the number of + milliseconds specified by this config. The broker closes idle + connections after connections.max.idle.ms, so this avoids hitting + unexpected socket disconnected errors on the client. + Default: 540000 + max_block_ms (int): Number of milliseconds to block during + :meth:`~kafka.KafkaProducer.send` and + :meth:`~kafka.KafkaProducer.partitions_for`. These methods can be + blocked either because the buffer is full or metadata unavailable. + Blocking in the user-supplied serializers or partitioner will not be + counted against this timeout. Default: 60000. + max_request_size (int): The maximum size of a request. This is also + effectively a cap on the maximum record size. Note that the server + has its own cap on record size which may be different from this. + This setting will limit the number of record batches the producer + will send in a single request to avoid sending huge requests. + Default: 1048576. + metadata_max_age_ms (int): The period of time in milliseconds after + which we force a refresh of metadata even if we haven't seen any + partition leadership changes to proactively discover any new + brokers or partitions. Default: 300000 + retry_backoff_ms (int): Milliseconds to backoff when retrying on + errors. Default: 100. + request_timeout_ms (int): Client request timeout in milliseconds. + Default: 30000. + receive_buffer_bytes (int): The size of the TCP receive buffer + (SO_RCVBUF) to use when reading data. Default: None (relies on + system defaults). Java client defaults to 32768. + send_buffer_bytes (int): The size of the TCP send buffer + (SO_SNDBUF) to use when sending data. Default: None (relies on + system defaults). Java client defaults to 131072. + socket_options (list): List of tuple-arguments to socket.setsockopt + to apply to broker connection sockets. Default: + [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)] + reconnect_backoff_ms (int): The amount of time in milliseconds to + wait before attempting to reconnect to a given host. + Default: 50. + reconnect_backoff_max_ms (int): The maximum amount of time in + milliseconds to backoff/wait when reconnecting to a broker that has + repeatedly failed to connect. If provided, the backoff per host + will increase exponentially for each consecutive connection + failure, up to this maximum. Once the maximum is reached, + reconnection attempts will continue periodically with this fixed + rate. To avoid connection storms, a randomization factor of 0.2 + will be applied to the backoff resulting in a random range between + 20% below and 20% above the computed value. Default: 1000. + max_in_flight_requests_per_connection (int): Requests are pipelined + to kafka brokers up to this number of maximum requests per + broker connection. Note that if this setting is set to be greater + than 1 and there are failed sends, there is a risk of message + re-ordering due to retries (i.e., if retries are enabled). + Default: 5. + security_protocol (str): Protocol used to communicate with brokers. + Valid values are: PLAINTEXT, SSL, SASL_PLAINTEXT, SASL_SSL. + Default: PLAINTEXT. + ssl_context (ssl.SSLContext): pre-configured SSLContext for wrapping + socket connections. If provided, all other ssl_* configurations + will be ignored. Default: None. + ssl_check_hostname (bool): flag to configure whether ssl handshake + should verify that the certificate matches the brokers hostname. + default: true. + ssl_cafile (str): optional filename of ca file to use in certificate + veriication. default: none. + ssl_certfile (str): optional filename of file in pem format containing + the client certificate, as well as any ca certificates needed to + establish the certificate's authenticity. default: none. + ssl_keyfile (str): optional filename containing the client private key. + default: none. + ssl_password (str): optional password to be used when loading the + certificate chain. default: none. + ssl_crlfile (str): optional filename containing the CRL to check for + certificate expiration. By default, no CRL check is done. When + providing a file, only the leaf certificate will be checked against + this CRL. The CRL can only be checked with Python 3.4+ or 2.7.9+. + default: none. + ssl_ciphers (str): optionally set the available ciphers for ssl + connections. It should be a string in the OpenSSL cipher list + format. If no cipher can be selected (because compile-time options + or other configuration forbids use of all the specified ciphers), + an ssl.SSLError will be raised. See ssl.SSLContext.set_ciphers + api_version (tuple): Specify which Kafka API version to use. If set to + None, the client will attempt to infer the broker version by probing + various APIs. Example: (0, 10, 2). Default: None + api_version_auto_timeout_ms (int): number of milliseconds to throw a + timeout exception from the constructor when checking the broker + api version. Only applies if api_version set to None. + metric_reporters (list): A list of classes to use as metrics reporters. + Implementing the AbstractMetricsReporter interface allows plugging + in classes that will be notified of new metric creation. Default: [] + metrics_num_samples (int): The number of samples maintained to compute + metrics. Default: 2 + metrics_sample_window_ms (int): The maximum age in milliseconds of + samples used to compute metrics. Default: 30000 + selector (selectors.BaseSelector): Provide a specific selector + implementation to use for I/O multiplexing. + Default: selectors.DefaultSelector + sasl_mechanism (str): Authentication mechanism when security_protocol + is configured for SASL_PLAINTEXT or SASL_SSL. Valid values are: + PLAIN, GSSAPI, OAUTHBEARER, SCRAM-SHA-256, SCRAM-SHA-512. + sasl_plain_username (str): username for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_plain_password (str): password for sasl PLAIN and SCRAM authentication. + Required if sasl_mechanism is PLAIN or one of the SCRAM mechanisms. + sasl_kerberos_service_name (str): Service name to include in GSSAPI + sasl mechanism handshake. Default: 'kafka' + sasl_kerberos_domain_name (str): kerberos domain name to use in GSSAPI + sasl mechanism handshake. Default: one of bootstrap servers + sasl_oauth_token_provider (AbstractTokenProvider): OAuthBearer token provider + instance. (See kafka.oauth.abstract). Default: None + + Note: + Configuration parameters are described in more detail at + https://kafka.apache.org/0100/configuration.html#producerconfigs + """ + DEFAULT_CONFIG = { + 'bootstrap_servers': 'localhost', + 'client_id': None, + 'key_serializer': None, + 'value_serializer': None, + 'acks': 1, + 'bootstrap_topics_filter': set(), + 'compression_type': None, + 'retries': 0, + 'batch_size': 16384, + 'linger_ms': 0, + 'partitioner': DefaultPartitioner(), + 'buffer_memory': 33554432, + 'connections_max_idle_ms': 9 * 60 * 1000, + 'max_block_ms': 60000, + 'max_request_size': 1048576, + 'metadata_max_age_ms': 300000, + 'retry_backoff_ms': 100, + 'request_timeout_ms': 30000, + 'receive_buffer_bytes': None, + 'send_buffer_bytes': None, + 'socket_options': [(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)], + 'sock_chunk_bytes': 4096, # undocumented experimental option + 'sock_chunk_buffer_count': 1000, # undocumented experimental option + 'reconnect_backoff_ms': 50, + 'reconnect_backoff_max_ms': 1000, + 'max_in_flight_requests_per_connection': 5, + 'security_protocol': 'PLAINTEXT', + 'ssl_context': None, + 'ssl_check_hostname': True, + 'ssl_cafile': None, + 'ssl_certfile': None, + 'ssl_keyfile': None, + 'ssl_crlfile': None, + 'ssl_password': None, + 'ssl_ciphers': None, + 'api_version': None, + 'api_version_auto_timeout_ms': 2000, + 'metric_reporters': [], + 'metrics_num_samples': 2, + 'metrics_sample_window_ms': 30000, + 'selector': selectors.DefaultSelector, + 'sasl_mechanism': None, + 'sasl_plain_username': None, + 'sasl_plain_password': None, + 'sasl_kerberos_service_name': 'kafka', + 'sasl_kerberos_domain_name': None, + 'sasl_oauth_token_provider': None + } + + _COMPRESSORS = { + 'gzip': (has_gzip, LegacyRecordBatchBuilder.CODEC_GZIP), + 'snappy': (has_snappy, LegacyRecordBatchBuilder.CODEC_SNAPPY), + 'lz4': (has_lz4, LegacyRecordBatchBuilder.CODEC_LZ4), + 'zstd': (has_zstd, DefaultRecordBatchBuilder.CODEC_ZSTD), + None: (lambda: True, LegacyRecordBatchBuilder.CODEC_NONE), + } + + def __init__(self, **configs): + log.debug("Starting the Kafka producer") # trace + self.config = copy.copy(self.DEFAULT_CONFIG) + for key in self.config: + if key in configs: + self.config[key] = configs.pop(key) + + # Only check for extra config keys in top-level class + assert not configs, 'Unrecognized configs: %s' % (configs,) + + if self.config['client_id'] is None: + self.config['client_id'] = 'kafka-python-producer-%s' % \ + (PRODUCER_CLIENT_ID_SEQUENCE.increment(),) + + if self.config['acks'] == 'all': + self.config['acks'] = -1 + + # api_version was previously a str. accept old format for now + if isinstance(self.config['api_version'], str): + deprecated = self.config['api_version'] + if deprecated == 'auto': + self.config['api_version'] = None + else: + self.config['api_version'] = tuple(map(int, deprecated.split('.'))) + log.warning('use api_version=%s [tuple] -- "%s" as str is deprecated', + str(self.config['api_version']), deprecated) + + # Configure metrics + metrics_tags = {'client-id': self.config['client_id']} + metric_config = MetricConfig(samples=self.config['metrics_num_samples'], + time_window_ms=self.config['metrics_sample_window_ms'], + tags=metrics_tags) + reporters = [reporter() for reporter in self.config['metric_reporters']] + self._metrics = Metrics(metric_config, reporters) + + client = KafkaClient(metrics=self._metrics, metric_group_prefix='producer', + wakeup_timeout_ms=self.config['max_block_ms'], + **self.config) + + # Get auto-discovered version from client if necessary + if self.config['api_version'] is None: + self.config['api_version'] = client.config['api_version'] + + if self.config['compression_type'] == 'lz4': + assert self.config['api_version'] >= (0, 8, 2), 'LZ4 Requires >= Kafka 0.8.2 Brokers' + + if self.config['compression_type'] == 'zstd': + assert self.config['api_version'] >= (2, 1, 0), 'Zstd Requires >= Kafka 2.1.0 Brokers' + + # Check compression_type for library support + ct = self.config['compression_type'] + if ct not in self._COMPRESSORS: + raise ValueError("Not supported codec: {}".format(ct)) + else: + checker, compression_attrs = self._COMPRESSORS[ct] + assert checker(), "Libraries for {} compression codec not found".format(ct) + self.config['compression_attrs'] = compression_attrs + + message_version = self._max_usable_produce_magic() + self._accumulator = RecordAccumulator(message_version=message_version, metrics=self._metrics, **self.config) + self._metadata = client.cluster + guarantee_message_order = bool(self.config['max_in_flight_requests_per_connection'] == 1) + self._sender = Sender(client, self._metadata, + self._accumulator, self._metrics, + guarantee_message_order=guarantee_message_order, + **self.config) + self._sender.daemon = True + self._sender.start() + self._closed = False + + self._cleanup = self._cleanup_factory() + atexit.register(self._cleanup) + log.debug("Kafka producer started") + + def bootstrap_connected(self): + """Return True if the bootstrap is connected.""" + return self._sender.bootstrap_connected() + + def _cleanup_factory(self): + """Build a cleanup clojure that doesn't increase our ref count""" + _self = weakref.proxy(self) + def wrapper(): + try: + _self.close(timeout=0) + except (ReferenceError, AttributeError): + pass + return wrapper + + def _unregister_cleanup(self): + if getattr(self, '_cleanup', None): + if hasattr(atexit, 'unregister'): + atexit.unregister(self._cleanup) # pylint: disable=no-member + + # py2 requires removing from private attribute... + else: + + # ValueError on list.remove() if the exithandler no longer exists + # but that is fine here + try: + atexit._exithandlers.remove( # pylint: disable=no-member + (self._cleanup, (), {})) + except ValueError: + pass + self._cleanup = None + + def __del__(self): + # Disable logger during destruction to avoid touching dangling references + class NullLogger(object): + def __getattr__(self, name): + return lambda *args: None + + global log + log = NullLogger() + + self.close() + + def close(self, timeout=None): + """Close this producer. + + Arguments: + timeout (float, optional): timeout in seconds to wait for completion. + """ + + # drop our atexit handler now to avoid leaks + self._unregister_cleanup() + + if not hasattr(self, '_closed') or self._closed: + log.info('Kafka producer closed') + return + if timeout is None: + # threading.TIMEOUT_MAX is available in Python3.3+ + timeout = getattr(threading, 'TIMEOUT_MAX', float('inf')) + if getattr(threading, 'TIMEOUT_MAX', False): + assert 0 <= timeout <= getattr(threading, 'TIMEOUT_MAX') + else: + assert timeout >= 0 + + log.info("Closing the Kafka producer with %s secs timeout.", timeout) + invoked_from_callback = bool(threading.current_thread() is self._sender) + if timeout > 0: + if invoked_from_callback: + log.warning("Overriding close timeout %s secs to 0 in order to" + " prevent useless blocking due to self-join. This" + " means you have incorrectly invoked close with a" + " non-zero timeout from the producer call-back.", + timeout) + else: + # Try to close gracefully. + if self._sender is not None: + self._sender.initiate_close() + self._sender.join(timeout) + + if self._sender is not None and self._sender.is_alive(): + log.info("Proceeding to force close the producer since pending" + " requests could not be completed within timeout %s.", + timeout) + self._sender.force_close() + + self._metrics.close() + try: + self.config['key_serializer'].close() + except AttributeError: + pass + try: + self.config['value_serializer'].close() + except AttributeError: + pass + self._closed = True + log.debug("The Kafka producer has closed.") + + def partitions_for(self, topic): + """Returns set of all known partitions for the topic.""" + max_wait = self.config['max_block_ms'] / 1000.0 + return self._wait_on_metadata(topic, max_wait) + + def _max_usable_produce_magic(self): + if self.config['api_version'] >= (0, 11): + return 2 + elif self.config['api_version'] >= (0, 10): + return 1 + else: + return 0 + + def _estimate_size_in_bytes(self, key, value, headers=[]): + magic = self._max_usable_produce_magic() + if magic == 2: + return DefaultRecordBatchBuilder.estimate_size_in_bytes( + key, value, headers) + else: + return LegacyRecordBatchBuilder.estimate_size_in_bytes( + magic, self.config['compression_type'], key, value) + + def send(self, topic, value=None, key=None, headers=None, partition=None, timestamp_ms=None): + """Publish a message to a topic. + + Arguments: + topic (str): topic where the message will be published + value (optional): message value. Must be type bytes, or be + serializable to bytes via configured value_serializer. If value + is None, key is required and message acts as a 'delete'. + See kafka compaction documentation for more details: + https://kafka.apache.org/documentation.html#compaction + (compaction requires kafka >= 0.8.1) + partition (int, optional): optionally specify a partition. If not + set, the partition will be selected using the configured + 'partitioner'. + key (optional): a key to associate with the message. Can be used to + determine which partition to send the message to. If partition + is None (and producer's partitioner config is left as default), + then messages with the same key will be delivered to the same + partition (but if key is None, partition is chosen randomly). + Must be type bytes, or be serializable to bytes via configured + key_serializer. + headers (optional): a list of header key value pairs. List items + are tuples of str key and bytes value. + timestamp_ms (int, optional): epoch milliseconds (from Jan 1 1970 UTC) + to use as the message timestamp. Defaults to current time. + + Returns: + FutureRecordMetadata: resolves to RecordMetadata + + Raises: + KafkaTimeoutError: if unable to fetch topic metadata, or unable + to obtain memory buffer prior to configured max_block_ms + """ + assert value is not None or self.config['api_version'] >= (0, 8, 1), ( + 'Null messages require kafka >= 0.8.1') + assert not (value is None and key is None), 'Need at least one: key or value' + key_bytes = value_bytes = None + try: + self._wait_on_metadata(topic, self.config['max_block_ms'] / 1000.0) + + key_bytes = self._serialize( + self.config['key_serializer'], + topic, key) + value_bytes = self._serialize( + self.config['value_serializer'], + topic, value) + assert type(key_bytes) in (bytes, bytearray, memoryview, type(None)) + assert type(value_bytes) in (bytes, bytearray, memoryview, type(None)) + + partition = self._partition(topic, partition, key, value, + key_bytes, value_bytes) + + if headers is None: + headers = [] + assert type(headers) == list + assert all(type(item) == tuple and len(item) == 2 and type(item[0]) == str and type(item[1]) == bytes for item in headers) + + message_size = self._estimate_size_in_bytes(key_bytes, value_bytes, headers) + self._ensure_valid_record_size(message_size) + + tp = TopicPartition(topic, partition) + log.debug("Sending (key=%r value=%r headers=%r) to %s", key, value, headers, tp) + result = self._accumulator.append(tp, timestamp_ms, + key_bytes, value_bytes, headers, + self.config['max_block_ms'], + estimated_size=message_size) + future, batch_is_full, new_batch_created = result + if batch_is_full or new_batch_created: + log.debug("Waking up the sender since %s is either full or" + " getting a new batch", tp) + self._sender.wakeup() + + return future + # handling exceptions and record the errors; + # for API exceptions return them in the future, + # for other exceptions raise directly + except Errors.BrokerResponseError as e: + log.debug("Exception occurred during message send: %s", e) + return FutureRecordMetadata( + FutureProduceResult(TopicPartition(topic, partition)), + -1, None, None, + len(key_bytes) if key_bytes is not None else -1, + len(value_bytes) if value_bytes is not None else -1, + sum(len(h_key.encode("utf-8")) + len(h_value) for h_key, h_value in headers) if headers else -1, + ).failure(e) + + def flush(self, timeout=None): + """ + Invoking this method makes all buffered records immediately available + to send (even if linger_ms is greater than 0) and blocks on the + completion of the requests associated with these records. The + post-condition of :meth:`~kafka.KafkaProducer.flush` is that any + previously sent record will have completed + (e.g. Future.is_done() == True). A request is considered completed when + either it is successfully acknowledged according to the 'acks' + configuration for the producer, or it results in an error. + + Other threads can continue sending messages while one thread is blocked + waiting for a flush call to complete; however, no guarantee is made + about the completion of messages sent after the flush call begins. + + Arguments: + timeout (float, optional): timeout in seconds to wait for completion. + + Raises: + KafkaTimeoutError: failure to flush buffered records within the + provided timeout + """ + log.debug("Flushing accumulated records in producer.") # trace + self._accumulator.begin_flush() + self._sender.wakeup() + self._accumulator.await_flush_completion(timeout=timeout) + + def _ensure_valid_record_size(self, size): + """Validate that the record size isn't too large.""" + if size > self.config['max_request_size']: + raise Errors.MessageSizeTooLargeError( + "The message is %d bytes when serialized which is larger than" + " the maximum request size you have configured with the" + " max_request_size configuration" % (size,)) + if size > self.config['buffer_memory']: + raise Errors.MessageSizeTooLargeError( + "The message is %d bytes when serialized which is larger than" + " the total memory buffer you have configured with the" + " buffer_memory configuration." % (size,)) + + def _wait_on_metadata(self, topic, max_wait): + """ + Wait for cluster metadata including partitions for the given topic to + be available. + + Arguments: + topic (str): topic we want metadata for + max_wait (float): maximum time in secs for waiting on the metadata + + Returns: + set: partition ids for the topic + + Raises: + KafkaTimeoutError: if partitions for topic were not obtained before + specified max_wait timeout + """ + # add topic to metadata topic list if it is not there already. + self._sender.add_topic(topic) + begin = time.time() + elapsed = 0.0 + metadata_event = None + while True: + partitions = self._metadata.partitions_for_topic(topic) + if partitions is not None: + return partitions + + if not metadata_event: + metadata_event = threading.Event() + + log.debug("Requesting metadata update for topic %s", topic) + + metadata_event.clear() + future = self._metadata.request_update() + future.add_both(lambda e, *args: e.set(), metadata_event) + self._sender.wakeup() + metadata_event.wait(max_wait - elapsed) + elapsed = time.time() - begin + if not metadata_event.is_set(): + raise Errors.KafkaTimeoutError( + "Failed to update metadata after %.1f secs." % (max_wait,)) + elif topic in self._metadata.unauthorized_topics: + raise Errors.TopicAuthorizationFailedError(topic) + else: + log.debug("_wait_on_metadata woke after %s secs.", elapsed) + + def _serialize(self, f, topic, data): + if not f: + return data + if isinstance(f, Serializer): + return f.serialize(topic, data) + return f(data) + + def _partition(self, topic, partition, key, value, + serialized_key, serialized_value): + if partition is not None: + assert partition >= 0 + assert partition in self._metadata.partitions_for_topic(topic), 'Unrecognized partition' + return partition + + all_partitions = sorted(self._metadata.partitions_for_topic(topic)) + available = list(self._metadata.available_partitions_for_topic(topic)) + return self.config['partitioner'](serialized_key, + all_partitions, + available) + + def metrics(self, raw=False): + """Get metrics on producer performance. + + This is ported from the Java Producer, for details see: + https://kafka.apache.org/documentation/#producer_monitoring + + Warning: + This is an unstable interface. It may change in future + releases without warning. + """ + if raw: + return self._metrics.metrics.copy() + + metrics = {} + for k, v in six.iteritems(self._metrics.metrics.copy()): + if k.group not in metrics: + metrics[k.group] = {} + if k.name not in metrics[k.group]: + metrics[k.group][k.name] = {} + metrics[k.group][k.name] = v.value() + return metrics diff --git a/testbed/dpkp__kafka-python/kafka/producer/record_accumulator.py b/testbed/dpkp__kafka-python/kafka/producer/record_accumulator.py new file mode 100644 index 0000000000000000000000000000000000000000..a2aa0e8ec1dce1ef372846426db8e16044e422b6 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/producer/record_accumulator.py @@ -0,0 +1,590 @@ +from __future__ import absolute_import + +import collections +import copy +import logging +import threading +import time + +import kafka.errors as Errors +from kafka.producer.buffer import SimpleBufferPool +from kafka.producer.future import FutureRecordMetadata, FutureProduceResult +from kafka.record.memory_records import MemoryRecordsBuilder +from kafka.structs import TopicPartition + + +log = logging.getLogger(__name__) + + +class AtomicInteger(object): + def __init__(self, val=0): + self._lock = threading.Lock() + self._val = val + + def increment(self): + with self._lock: + self._val += 1 + return self._val + + def decrement(self): + with self._lock: + self._val -= 1 + return self._val + + def get(self): + return self._val + + +class ProducerBatch(object): + def __init__(self, tp, records, buffer): + self.max_record_size = 0 + now = time.time() + self.created = now + self.drained = None + self.attempts = 0 + self.last_attempt = now + self.last_append = now + self.records = records + self.topic_partition = tp + self.produce_future = FutureProduceResult(tp) + self._retry = False + self._buffer = buffer # We only save it, we don't write to it + + @property + def record_count(self): + return self.records.next_offset() + + def try_append(self, timestamp_ms, key, value, headers): + metadata = self.records.append(timestamp_ms, key, value, headers) + if metadata is None: + return None + + self.max_record_size = max(self.max_record_size, metadata.size) + self.last_append = time.time() + future = FutureRecordMetadata(self.produce_future, metadata.offset, + metadata.timestamp, metadata.crc, + len(key) if key is not None else -1, + len(value) if value is not None else -1, + sum(len(h_key.encode("utf-8")) + len(h_val) for h_key, h_val in headers) if headers else -1) + return future + + def done(self, base_offset=None, timestamp_ms=None, exception=None, log_start_offset=None, global_error=None): + level = logging.DEBUG if exception is None else logging.WARNING + log.log(level, "Produced messages to topic-partition %s with base offset" + " %s log start offset %s and error %s.", self.topic_partition, base_offset, + log_start_offset, global_error) # trace + if self.produce_future.is_done: + log.warning('Batch is already closed -- ignoring batch.done()') + return + elif exception is None: + self.produce_future.success((base_offset, timestamp_ms, log_start_offset)) + else: + self.produce_future.failure(exception) + + def maybe_expire(self, request_timeout_ms, retry_backoff_ms, linger_ms, is_full): + """Expire batches if metadata is not available + + A batch whose metadata is not available should be expired if one + of the following is true: + + * the batch is not in retry AND request timeout has elapsed after + it is ready (full or linger.ms has reached). + + * the batch is in retry AND request timeout has elapsed after the + backoff period ended. + """ + now = time.time() + since_append = now - self.last_append + since_ready = now - (self.created + linger_ms / 1000.0) + since_backoff = now - (self.last_attempt + retry_backoff_ms / 1000.0) + timeout = request_timeout_ms / 1000.0 + + error = None + if not self.in_retry() and is_full and timeout < since_append: + error = "%d seconds have passed since last append" % (since_append,) + elif not self.in_retry() and timeout < since_ready: + error = "%d seconds have passed since batch creation plus linger time" % (since_ready,) + elif self.in_retry() and timeout < since_backoff: + error = "%d seconds have passed since last attempt plus backoff time" % (since_backoff,) + + if error: + self.records.close() + self.done(-1, None, Errors.KafkaTimeoutError( + "Batch for %s containing %s record(s) expired: %s" % ( + self.topic_partition, self.records.next_offset(), error))) + return True + return False + + def in_retry(self): + return self._retry + + def set_retry(self): + self._retry = True + + def buffer(self): + return self._buffer + + def __str__(self): + return 'ProducerBatch(topic_partition=%s, record_count=%d)' % ( + self.topic_partition, self.records.next_offset()) + + +class RecordAccumulator(object): + """ + This class maintains a dequeue per TopicPartition that accumulates messages + into MessageSets to be sent to the server. + + The accumulator attempts to bound memory use, and append calls will block + when that memory is exhausted. + + Keyword Arguments: + batch_size (int): Requests sent to brokers will contain multiple + batches, one for each partition with data available to be sent. + A small batch size will make batching less common and may reduce + throughput (a batch size of zero will disable batching entirely). + Default: 16384 + buffer_memory (int): The total bytes of memory the producer should use + to buffer records waiting to be sent to the server. If records are + sent faster than they can be delivered to the server the producer + will block up to max_block_ms, raising an exception on timeout. + In the current implementation, this setting is an approximation. + Default: 33554432 (32MB) + compression_attrs (int): The compression type for all data generated by + the producer. Valid values are gzip(1), snappy(2), lz4(3), or + none(0). + Compression is of full batches of data, so the efficacy of batching + will also impact the compression ratio (more batching means better + compression). Default: None. + linger_ms (int): An artificial delay time to add before declaring a + messageset (that isn't full) ready for sending. This allows + time for more records to arrive. Setting a non-zero linger_ms + will trade off some latency for potentially better throughput + due to more batching (and hence fewer, larger requests). + Default: 0 + retry_backoff_ms (int): An artificial delay time to retry the + produce request upon receiving an error. This avoids exhausting + all retries in a short period of time. Default: 100 + """ + DEFAULT_CONFIG = { + 'buffer_memory': 33554432, + 'batch_size': 16384, + 'compression_attrs': 0, + 'linger_ms': 0, + 'retry_backoff_ms': 100, + 'message_version': 0, + 'metrics': None, + 'metric_group_prefix': 'producer-metrics', + } + + def __init__(self, **configs): + self.config = copy.copy(self.DEFAULT_CONFIG) + for key in self.config: + if key in configs: + self.config[key] = configs.pop(key) + + self._closed = False + self._flushes_in_progress = AtomicInteger() + self._appends_in_progress = AtomicInteger() + self._batches = collections.defaultdict(collections.deque) # TopicPartition: [ProducerBatch] + self._tp_locks = {None: threading.Lock()} # TopicPartition: Lock, plus a lock to add entries + self._free = SimpleBufferPool(self.config['buffer_memory'], + self.config['batch_size'], + metrics=self.config['metrics'], + metric_group_prefix=self.config['metric_group_prefix']) + self._incomplete = IncompleteProducerBatches() + # The following variables should only be accessed by the sender thread, + # so we don't need to protect them w/ locking. + self.muted = set() + self._drain_index = 0 + + def append(self, tp, timestamp_ms, key, value, headers, max_time_to_block_ms, + estimated_size=0): + """Add a record to the accumulator, return the append result. + + The append result will contain the future metadata, and flag for + whether the appended batch is full or a new batch is created + + Arguments: + tp (TopicPartition): The topic/partition to which this record is + being sent + timestamp_ms (int): The timestamp of the record (epoch ms) + key (bytes): The key for the record + value (bytes): The value for the record + headers (List[Tuple[str, bytes]]): The header fields for the record + max_time_to_block_ms (int): The maximum time in milliseconds to + block for buffer memory to be available + + Returns: + tuple: (future, batch_is_full, new_batch_created) + """ + assert isinstance(tp, TopicPartition), 'not TopicPartition' + assert not self._closed, 'RecordAccumulator is closed' + # We keep track of the number of appending thread to make sure we do + # not miss batches in abortIncompleteBatches(). + self._appends_in_progress.increment() + try: + if tp not in self._tp_locks: + with self._tp_locks[None]: + if tp not in self._tp_locks: + self._tp_locks[tp] = threading.Lock() + + with self._tp_locks[tp]: + # check if we have an in-progress batch + dq = self._batches[tp] + if dq: + last = dq[-1] + future = last.try_append(timestamp_ms, key, value, headers) + if future is not None: + batch_is_full = len(dq) > 1 or last.records.is_full() + return future, batch_is_full, False + + size = max(self.config['batch_size'], estimated_size) + log.debug("Allocating a new %d byte message buffer for %s", size, tp) # trace + buf = self._free.allocate(size, max_time_to_block_ms) + with self._tp_locks[tp]: + # Need to check if producer is closed again after grabbing the + # dequeue lock. + assert not self._closed, 'RecordAccumulator is closed' + + if dq: + last = dq[-1] + future = last.try_append(timestamp_ms, key, value, headers) + if future is not None: + # Somebody else found us a batch, return the one we + # waited for! Hopefully this doesn't happen often... + self._free.deallocate(buf) + batch_is_full = len(dq) > 1 or last.records.is_full() + return future, batch_is_full, False + + records = MemoryRecordsBuilder( + self.config['message_version'], + self.config['compression_attrs'], + self.config['batch_size'] + ) + + batch = ProducerBatch(tp, records, buf) + future = batch.try_append(timestamp_ms, key, value, headers) + if not future: + raise Exception() + + dq.append(batch) + self._incomplete.add(batch) + batch_is_full = len(dq) > 1 or batch.records.is_full() + return future, batch_is_full, True + finally: + self._appends_in_progress.decrement() + + def abort_expired_batches(self, request_timeout_ms, cluster): + """Abort the batches that have been sitting in RecordAccumulator for + more than the configured request_timeout due to metadata being + unavailable. + + Arguments: + request_timeout_ms (int): milliseconds to timeout + cluster (ClusterMetadata): current metadata for kafka cluster + + Returns: + list of ProducerBatch that were expired + """ + expired_batches = [] + to_remove = [] + count = 0 + for tp in list(self._batches.keys()): + assert tp in self._tp_locks, 'TopicPartition not in locks dict' + + # We only check if the batch should be expired if the partition + # does not have a batch in flight. This is to avoid the later + # batches get expired when an earlier batch is still in progress. + # This protection only takes effect when user sets + # max.in.flight.request.per.connection=1. Otherwise the expiration + # order is not guranteed. + if tp in self.muted: + continue + + with self._tp_locks[tp]: + # iterate over the batches and expire them if they have stayed + # in accumulator for more than request_timeout_ms + dq = self._batches[tp] + for batch in dq: + is_full = bool(bool(batch != dq[-1]) or batch.records.is_full()) + # check if the batch is expired + if batch.maybe_expire(request_timeout_ms, + self.config['retry_backoff_ms'], + self.config['linger_ms'], + is_full): + expired_batches.append(batch) + to_remove.append(batch) + count += 1 + self.deallocate(batch) + else: + # Stop at the first batch that has not expired. + break + + # Python does not allow us to mutate the dq during iteration + # Assuming expired batches are infrequent, this is better than + # creating a new copy of the deque for iteration on every loop + if to_remove: + for batch in to_remove: + dq.remove(batch) + to_remove = [] + + if expired_batches: + log.warning("Expired %d batches in accumulator", count) # trace + + return expired_batches + + def reenqueue(self, batch): + """Re-enqueue the given record batch in the accumulator to retry.""" + now = time.time() + batch.attempts += 1 + batch.last_attempt = now + batch.last_append = now + batch.set_retry() + assert batch.topic_partition in self._tp_locks, 'TopicPartition not in locks dict' + assert batch.topic_partition in self._batches, 'TopicPartition not in batches' + dq = self._batches[batch.topic_partition] + with self._tp_locks[batch.topic_partition]: + dq.appendleft(batch) + + def ready(self, cluster): + """ + Get a list of nodes whose partitions are ready to be sent, and the + earliest time at which any non-sendable partition will be ready; + Also return the flag for whether there are any unknown leaders for the + accumulated partition batches. + + A destination node is ready to send if: + + * There is at least one partition that is not backing off its send + * and those partitions are not muted (to prevent reordering if + max_in_flight_requests_per_connection is set to 1) + * and any of the following are true: + + * The record set is full + * The record set has sat in the accumulator for at least linger_ms + milliseconds + * The accumulator is out of memory and threads are blocking waiting + for data (in this case all partitions are immediately considered + ready). + * The accumulator has been closed + + Arguments: + cluster (ClusterMetadata): + + Returns: + tuple: + ready_nodes (set): node_ids that have ready batches + next_ready_check (float): secs until next ready after backoff + unknown_leaders_exist (bool): True if metadata refresh needed + """ + ready_nodes = set() + next_ready_check = 9999999.99 + unknown_leaders_exist = False + now = time.time() + + exhausted = bool(self._free.queued() > 0) + # several threads are accessing self._batches -- to simplify + # concurrent access, we iterate over a snapshot of partitions + # and lock each partition separately as needed + partitions = list(self._batches.keys()) + for tp in partitions: + leader = cluster.leader_for_partition(tp) + if leader is None or leader == -1: + unknown_leaders_exist = True + continue + elif leader in ready_nodes: + continue + elif tp in self.muted: + continue + + with self._tp_locks[tp]: + dq = self._batches[tp] + if not dq: + continue + batch = dq[0] + retry_backoff = self.config['retry_backoff_ms'] / 1000.0 + linger = self.config['linger_ms'] / 1000.0 + backing_off = bool(batch.attempts > 0 and + batch.last_attempt + retry_backoff > now) + waited_time = now - batch.last_attempt + time_to_wait = retry_backoff if backing_off else linger + time_left = max(time_to_wait - waited_time, 0) + full = bool(len(dq) > 1 or batch.records.is_full()) + expired = bool(waited_time >= time_to_wait) + + sendable = (full or expired or exhausted or self._closed or + self._flush_in_progress()) + + if sendable and not backing_off: + ready_nodes.add(leader) + else: + # Note that this results in a conservative estimate since + # an un-sendable partition may have a leader that will + # later be found to have sendable data. However, this is + # good enough since we'll just wake up and then sleep again + # for the remaining time. + next_ready_check = min(time_left, next_ready_check) + + return ready_nodes, next_ready_check, unknown_leaders_exist + + def has_unsent(self): + """Return whether there is any unsent record in the accumulator.""" + for tp in list(self._batches.keys()): + with self._tp_locks[tp]: + dq = self._batches[tp] + if len(dq): + return True + return False + + def drain(self, cluster, nodes, max_size): + """ + Drain all the data for the given nodes and collate them into a list of + batches that will fit within the specified size on a per-node basis. + This method attempts to avoid choosing the same topic-node repeatedly. + + Arguments: + cluster (ClusterMetadata): The current cluster metadata + nodes (list): list of node_ids to drain + max_size (int): maximum number of bytes to drain + + Returns: + dict: {node_id: list of ProducerBatch} with total size less than the + requested max_size. + """ + if not nodes: + return {} + + now = time.time() + batches = {} + for node_id in nodes: + size = 0 + partitions = list(cluster.partitions_for_broker(node_id)) + ready = [] + # to make starvation less likely this loop doesn't start at 0 + self._drain_index %= len(partitions) + start = self._drain_index + while True: + tp = partitions[self._drain_index] + if tp in self._batches and tp not in self.muted: + with self._tp_locks[tp]: + dq = self._batches[tp] + if dq: + first = dq[0] + backoff = ( + bool(first.attempts > 0) and + bool(first.last_attempt + + self.config['retry_backoff_ms'] / 1000.0 + > now) + ) + # Only drain the batch if it is not during backoff + if not backoff: + if (size + first.records.size_in_bytes() > max_size + and len(ready) > 0): + # there is a rare case that a single batch + # size is larger than the request size due + # to compression; in this case we will + # still eventually send this batch in a + # single request + break + else: + batch = dq.popleft() + batch.records.close() + size += batch.records.size_in_bytes() + ready.append(batch) + batch.drained = now + + self._drain_index += 1 + self._drain_index %= len(partitions) + if start == self._drain_index: + break + + batches[node_id] = ready + return batches + + def deallocate(self, batch): + """Deallocate the record batch.""" + self._incomplete.remove(batch) + self._free.deallocate(batch.buffer()) + + def _flush_in_progress(self): + """Are there any threads currently waiting on a flush?""" + return self._flushes_in_progress.get() > 0 + + def begin_flush(self): + """ + Initiate the flushing of data from the accumulator...this makes all + requests immediately ready + """ + self._flushes_in_progress.increment() + + def await_flush_completion(self, timeout=None): + """ + Mark all partitions as ready to send and block until the send is complete + """ + try: + for batch in self._incomplete.all(): + log.debug('Waiting on produce to %s', + batch.produce_future.topic_partition) + if not batch.produce_future.wait(timeout=timeout): + raise Errors.KafkaTimeoutError('Timeout waiting for future') + if not batch.produce_future.is_done: + raise Errors.UnknownError('Future not done') + + if batch.produce_future.failed(): + log.warning(batch.produce_future.exception) + finally: + self._flushes_in_progress.decrement() + + def abort_incomplete_batches(self): + """ + This function is only called when sender is closed forcefully. It will fail all the + incomplete batches and return. + """ + # We need to keep aborting the incomplete batch until no thread is trying to append to + # 1. Avoid losing batches. + # 2. Free up memory in case appending threads are blocked on buffer full. + # This is a tight loop but should be able to get through very quickly. + while True: + self._abort_batches() + if not self._appends_in_progress.get(): + break + # After this point, no thread will append any messages because they will see the close + # flag set. We need to do the last abort after no thread was appending in case the there was a new + # batch appended by the last appending thread. + self._abort_batches() + self._batches.clear() + + def _abort_batches(self): + """Go through incomplete batches and abort them.""" + error = Errors.IllegalStateError("Producer is closed forcefully.") + for batch in self._incomplete.all(): + tp = batch.topic_partition + # Close the batch before aborting + with self._tp_locks[tp]: + batch.records.close() + batch.done(exception=error) + self.deallocate(batch) + + def close(self): + """Close this accumulator and force all the record buffers to be drained.""" + self._closed = True + + +class IncompleteProducerBatches(object): + """A threadsafe helper class to hold ProducerBatches that haven't been ack'd yet""" + + def __init__(self): + self._incomplete = set() + self._lock = threading.Lock() + + def add(self, batch): + with self._lock: + return self._incomplete.add(batch) + + def remove(self, batch): + with self._lock: + return self._incomplete.remove(batch) + + def all(self): + with self._lock: + return list(self._incomplete) diff --git a/testbed/dpkp__kafka-python/kafka/producer/sender.py b/testbed/dpkp__kafka-python/kafka/producer/sender.py new file mode 100644 index 0000000000000000000000000000000000000000..35688d3f1cf43b00122e0da7d2215391cb9f28d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/producer/sender.py @@ -0,0 +1,517 @@ +from __future__ import absolute_import, division + +import collections +import copy +import logging +import threading +import time + +from kafka.vendor import six + +from kafka import errors as Errors +from kafka.metrics.measurable import AnonMeasurable +from kafka.metrics.stats import Avg, Max, Rate +from kafka.protocol.produce import ProduceRequest +from kafka.structs import TopicPartition +from kafka.version import __version__ + +log = logging.getLogger(__name__) + + +class Sender(threading.Thread): + """ + The background thread that handles the sending of produce requests to the + Kafka cluster. This thread makes metadata requests to renew its view of the + cluster and then sends produce requests to the appropriate nodes. + """ + DEFAULT_CONFIG = { + 'max_request_size': 1048576, + 'acks': 1, + 'retries': 0, + 'request_timeout_ms': 30000, + 'guarantee_message_order': False, + 'client_id': 'kafka-python-' + __version__, + 'api_version': (0, 8, 0), + } + + def __init__(self, client, metadata, accumulator, metrics, **configs): + super(Sender, self).__init__() + self.config = copy.copy(self.DEFAULT_CONFIG) + for key in self.config: + if key in configs: + self.config[key] = configs.pop(key) + + self.name = self.config['client_id'] + '-network-thread' + self._client = client + self._accumulator = accumulator + self._metadata = client.cluster + self._running = True + self._force_close = False + self._topics_to_add = set() + self._sensors = SenderMetrics(metrics, self._client, self._metadata) + + def run(self): + """The main run loop for the sender thread.""" + log.debug("Starting Kafka producer I/O thread.") + + # main loop, runs until close is called + while self._running: + try: + self.run_once() + except Exception: + log.exception("Uncaught error in kafka producer I/O thread") + + log.debug("Beginning shutdown of Kafka producer I/O thread, sending" + " remaining records.") + + # okay we stopped accepting requests but there may still be + # requests in the accumulator or waiting for acknowledgment, + # wait until these are completed. + while (not self._force_close + and (self._accumulator.has_unsent() + or self._client.in_flight_request_count() > 0)): + try: + self.run_once() + except Exception: + log.exception("Uncaught error in kafka producer I/O thread") + + if self._force_close: + # We need to fail all the incomplete batches and wake up the + # threads waiting on the futures. + self._accumulator.abort_incomplete_batches() + + try: + self._client.close() + except Exception: + log.exception("Failed to close network client") + + log.debug("Shutdown of Kafka producer I/O thread has completed.") + + def run_once(self): + """Run a single iteration of sending.""" + while self._topics_to_add: + self._client.add_topic(self._topics_to_add.pop()) + + # get the list of partitions with data ready to send + result = self._accumulator.ready(self._metadata) + ready_nodes, next_ready_check_delay, unknown_leaders_exist = result + + # if there are any partitions whose leaders are not known yet, force + # metadata update + if unknown_leaders_exist: + log.debug('Unknown leaders exist, requesting metadata update') + self._metadata.request_update() + + # remove any nodes we aren't ready to send to + not_ready_timeout = float('inf') + for node in list(ready_nodes): + if not self._client.is_ready(node): + log.debug('Node %s not ready; delaying produce of accumulated batch', node) + self._client.maybe_connect(node, wakeup=False) + ready_nodes.remove(node) + not_ready_timeout = min(not_ready_timeout, + self._client.connection_delay(node)) + + # create produce requests + batches_by_node = self._accumulator.drain( + self._metadata, ready_nodes, self.config['max_request_size']) + + if self.config['guarantee_message_order']: + # Mute all the partitions drained + for batch_list in six.itervalues(batches_by_node): + for batch in batch_list: + self._accumulator.muted.add(batch.topic_partition) + + expired_batches = self._accumulator.abort_expired_batches( + self.config['request_timeout_ms'], self._metadata) + for expired_batch in expired_batches: + self._sensors.record_errors(expired_batch.topic_partition.topic, expired_batch.record_count) + + self._sensors.update_produce_request_metrics(batches_by_node) + requests = self._create_produce_requests(batches_by_node) + # If we have any nodes that are ready to send + have sendable data, + # poll with 0 timeout so this can immediately loop and try sending more + # data. Otherwise, the timeout is determined by nodes that have + # partitions with data that isn't yet sendable (e.g. lingering, backing + # off). Note that this specifically does not include nodes with + # sendable data that aren't ready to send since they would cause busy + # looping. + poll_timeout_ms = min(next_ready_check_delay * 1000, not_ready_timeout) + if ready_nodes: + log.debug("Nodes with data ready to send: %s", ready_nodes) # trace + log.debug("Created %d produce requests: %s", len(requests), requests) # trace + poll_timeout_ms = 0 + + for node_id, request in six.iteritems(requests): + batches = batches_by_node[node_id] + log.debug('Sending Produce Request: %r', request) + (self._client.send(node_id, request, wakeup=False) + .add_callback( + self._handle_produce_response, node_id, time.time(), batches) + .add_errback( + self._failed_produce, batches, node_id)) + + # if some partitions are already ready to be sent, the select time + # would be 0; otherwise if some partition already has some data + # accumulated but not ready yet, the select time will be the time + # difference between now and its linger expiry time; otherwise the + # select time will be the time difference between now and the + # metadata expiry time + self._client.poll(timeout_ms=poll_timeout_ms) + + def initiate_close(self): + """Start closing the sender (won't complete until all data is sent).""" + self._running = False + self._accumulator.close() + self.wakeup() + + def force_close(self): + """Closes the sender without sending out any pending messages.""" + self._force_close = True + self.initiate_close() + + def add_topic(self, topic): + # This is generally called from a separate thread + # so this needs to be a thread-safe operation + # we assume that checking set membership across threads + # is ok where self._client._topics should never + # remove topics for a producer instance, only add them. + if topic not in self._client._topics: + self._topics_to_add.add(topic) + self.wakeup() + + def _failed_produce(self, batches, node_id, error): + log.debug("Error sending produce request to node %d: %s", node_id, error) # trace + for batch in batches: + self._complete_batch(batch, error, -1, None) + + def _handle_produce_response(self, node_id, send_time, batches, response): + """Handle a produce response.""" + # if we have a response, parse it + log.debug('Parsing produce response: %r', response) + if response: + batches_by_partition = dict([(batch.topic_partition, batch) + for batch in batches]) + + for topic, partitions in response.topics: + for partition_info in partitions: + global_error = None + log_start_offset = None + if response.API_VERSION < 2: + partition, error_code, offset = partition_info + ts = None + elif 2 <= response.API_VERSION <= 4: + partition, error_code, offset, ts = partition_info + elif 5 <= response.API_VERSION <= 7: + partition, error_code, offset, ts, log_start_offset = partition_info + else: + # the ignored parameter is record_error of type list[(batch_index: int, error_message: str)] + partition, error_code, offset, ts, log_start_offset, _, global_error = partition_info + tp = TopicPartition(topic, partition) + error = Errors.for_code(error_code) + batch = batches_by_partition[tp] + self._complete_batch(batch, error, offset, ts, log_start_offset, global_error) + + if response.API_VERSION > 0: + self._sensors.record_throttle_time(response.throttle_time_ms, node=node_id) + + else: + # this is the acks = 0 case, just complete all requests + for batch in batches: + self._complete_batch(batch, None, -1, None) + + def _complete_batch(self, batch, error, base_offset, timestamp_ms=None, log_start_offset=None, global_error=None): + """Complete or retry the given batch of records. + + Arguments: + batch (RecordBatch): The record batch + error (Exception): The error (or None if none) + base_offset (int): The base offset assigned to the records if successful + timestamp_ms (int, optional): The timestamp returned by the broker for this batch + log_start_offset (int): The start offset of the log at the time this produce response was created + global_error (str): The summarising error message + """ + # Standardize no-error to None + if error is Errors.NoError: + error = None + + if error is not None and self._can_retry(batch, error): + # retry + log.warning("Got error produce response on topic-partition %s," + " retrying (%d attempts left). Error: %s", + batch.topic_partition, + self.config['retries'] - batch.attempts - 1, + global_error or error) + self._accumulator.reenqueue(batch) + self._sensors.record_retries(batch.topic_partition.topic, batch.record_count) + else: + if error is Errors.TopicAuthorizationFailedError: + error = error(batch.topic_partition.topic) + + # tell the user the result of their request + batch.done(base_offset, timestamp_ms, error, log_start_offset, global_error) + self._accumulator.deallocate(batch) + if error is not None: + self._sensors.record_errors(batch.topic_partition.topic, batch.record_count) + + if getattr(error, 'invalid_metadata', False): + self._metadata.request_update() + + # Unmute the completed partition. + if self.config['guarantee_message_order']: + self._accumulator.muted.remove(batch.topic_partition) + + def _can_retry(self, batch, error): + """ + We can retry a send if the error is transient and the number of + attempts taken is fewer than the maximum allowed + """ + return (batch.attempts < self.config['retries'] + and getattr(error, 'retriable', False)) + + def _create_produce_requests(self, collated): + """ + Transfer the record batches into a list of produce requests on a + per-node basis. + + Arguments: + collated: {node_id: [RecordBatch]} + + Returns: + dict: {node_id: ProduceRequest} (version depends on api_version) + """ + requests = {} + for node_id, batches in six.iteritems(collated): + requests[node_id] = self._produce_request( + node_id, self.config['acks'], + self.config['request_timeout_ms'], batches) + return requests + + def _produce_request(self, node_id, acks, timeout, batches): + """Create a produce request from the given record batches. + + Returns: + ProduceRequest (version depends on api_version) + """ + produce_records_by_partition = collections.defaultdict(dict) + for batch in batches: + topic = batch.topic_partition.topic + partition = batch.topic_partition.partition + + buf = batch.records.buffer() + produce_records_by_partition[topic][partition] = buf + + kwargs = {} + if self.config['api_version'] >= (2, 1): + version = 7 + elif self.config['api_version'] >= (2, 0): + version = 6 + elif self.config['api_version'] >= (1, 1): + version = 5 + elif self.config['api_version'] >= (1, 0): + version = 4 + elif self.config['api_version'] >= (0, 11): + version = 3 + kwargs = dict(transactional_id=None) + elif self.config['api_version'] >= (0, 10): + version = 2 + elif self.config['api_version'] == (0, 9): + version = 1 + else: + version = 0 + return ProduceRequest[version]( + required_acks=acks, + timeout=timeout, + topics=[(topic, list(partition_info.items())) + for topic, partition_info + in six.iteritems(produce_records_by_partition)], + **kwargs + ) + + def wakeup(self): + """Wake up the selector associated with this send thread.""" + self._client.wakeup() + + def bootstrap_connected(self): + return self._client.bootstrap_connected() + + +class SenderMetrics(object): + + def __init__(self, metrics, client, metadata): + self.metrics = metrics + self._client = client + self._metadata = metadata + + sensor_name = 'batch-size' + self.batch_size_sensor = self.metrics.sensor(sensor_name) + self.add_metric('batch-size-avg', Avg(), + sensor_name=sensor_name, + description='The average number of bytes sent per partition per-request.') + self.add_metric('batch-size-max', Max(), + sensor_name=sensor_name, + description='The max number of bytes sent per partition per-request.') + + sensor_name = 'compression-rate' + self.compression_rate_sensor = self.metrics.sensor(sensor_name) + self.add_metric('compression-rate-avg', Avg(), + sensor_name=sensor_name, + description='The average compression rate of record batches.') + + sensor_name = 'queue-time' + self.queue_time_sensor = self.metrics.sensor(sensor_name) + self.add_metric('record-queue-time-avg', Avg(), + sensor_name=sensor_name, + description='The average time in ms record batches spent in the record accumulator.') + self.add_metric('record-queue-time-max', Max(), + sensor_name=sensor_name, + description='The maximum time in ms record batches spent in the record accumulator.') + + sensor_name = 'produce-throttle-time' + self.produce_throttle_time_sensor = self.metrics.sensor(sensor_name) + self.add_metric('produce-throttle-time-avg', Avg(), + sensor_name=sensor_name, + description='The average throttle time in ms') + self.add_metric('produce-throttle-time-max', Max(), + sensor_name=sensor_name, + description='The maximum throttle time in ms') + + sensor_name = 'records-per-request' + self.records_per_request_sensor = self.metrics.sensor(sensor_name) + self.add_metric('record-send-rate', Rate(), + sensor_name=sensor_name, + description='The average number of records sent per second.') + self.add_metric('records-per-request-avg', Avg(), + sensor_name=sensor_name, + description='The average number of records per request.') + + sensor_name = 'bytes' + self.byte_rate_sensor = self.metrics.sensor(sensor_name) + self.add_metric('byte-rate', Rate(), + sensor_name=sensor_name, + description='The average number of bytes sent per second.') + + sensor_name = 'record-retries' + self.retry_sensor = self.metrics.sensor(sensor_name) + self.add_metric('record-retry-rate', Rate(), + sensor_name=sensor_name, + description='The average per-second number of retried record sends') + + sensor_name = 'errors' + self.error_sensor = self.metrics.sensor(sensor_name) + self.add_metric('record-error-rate', Rate(), + sensor_name=sensor_name, + description='The average per-second number of record sends that resulted in errors') + + sensor_name = 'record-size-max' + self.max_record_size_sensor = self.metrics.sensor(sensor_name) + self.add_metric('record-size-max', Max(), + sensor_name=sensor_name, + description='The maximum record size across all batches') + self.add_metric('record-size-avg', Avg(), + sensor_name=sensor_name, + description='The average maximum record size per batch') + + self.add_metric('requests-in-flight', + AnonMeasurable(lambda *_: self._client.in_flight_request_count()), + description='The current number of in-flight requests awaiting a response.') + + self.add_metric('metadata-age', + AnonMeasurable(lambda _, now: (now - self._metadata._last_successful_refresh_ms) / 1000), + description='The age in seconds of the current producer metadata being used.') + + def add_metric(self, metric_name, measurable, group_name='producer-metrics', + description=None, tags=None, + sensor_name=None): + m = self.metrics + metric = m.metric_name(metric_name, group_name, description, tags) + if sensor_name: + sensor = m.sensor(sensor_name) + sensor.add(metric, measurable) + else: + m.add_metric(metric, measurable) + + def maybe_register_topic_metrics(self, topic): + + def sensor_name(name): + return 'topic.{0}.{1}'.format(topic, name) + + # if one sensor of the metrics has been registered for the topic, + # then all other sensors should have been registered; and vice versa + if not self.metrics.get_sensor(sensor_name('records-per-batch')): + + self.add_metric('record-send-rate', Rate(), + sensor_name=sensor_name('records-per-batch'), + group_name='producer-topic-metrics.' + topic, + description= 'Records sent per second for topic ' + topic) + + self.add_metric('byte-rate', Rate(), + sensor_name=sensor_name('bytes'), + group_name='producer-topic-metrics.' + topic, + description='Bytes per second for topic ' + topic) + + self.add_metric('compression-rate', Avg(), + sensor_name=sensor_name('compression-rate'), + group_name='producer-topic-metrics.' + topic, + description='Average Compression ratio for topic ' + topic) + + self.add_metric('record-retry-rate', Rate(), + sensor_name=sensor_name('record-retries'), + group_name='producer-topic-metrics.' + topic, + description='Record retries per second for topic ' + topic) + + self.add_metric('record-error-rate', Rate(), + sensor_name=sensor_name('record-errors'), + group_name='producer-topic-metrics.' + topic, + description='Record errors per second for topic ' + topic) + + def update_produce_request_metrics(self, batches_map): + for node_batch in batches_map.values(): + records = 0 + total_bytes = 0 + for batch in node_batch: + # register all per-topic metrics at once + topic = batch.topic_partition.topic + self.maybe_register_topic_metrics(topic) + + # per-topic record send rate + topic_records_count = self.metrics.get_sensor( + 'topic.' + topic + '.records-per-batch') + topic_records_count.record(batch.record_count) + + # per-topic bytes send rate + topic_byte_rate = self.metrics.get_sensor( + 'topic.' + topic + '.bytes') + topic_byte_rate.record(batch.records.size_in_bytes()) + + # per-topic compression rate + topic_compression_rate = self.metrics.get_sensor( + 'topic.' + topic + '.compression-rate') + topic_compression_rate.record(batch.records.compression_rate()) + + # global metrics + self.batch_size_sensor.record(batch.records.size_in_bytes()) + if batch.drained: + self.queue_time_sensor.record(batch.drained - batch.created) + self.compression_rate_sensor.record(batch.records.compression_rate()) + self.max_record_size_sensor.record(batch.max_record_size) + records += batch.record_count + total_bytes += batch.records.size_in_bytes() + + self.records_per_request_sensor.record(records) + self.byte_rate_sensor.record(total_bytes) + + def record_retries(self, topic, count): + self.retry_sensor.record(count) + sensor = self.metrics.get_sensor('topic.' + topic + '.record-retries') + if sensor: + sensor.record(count) + + def record_errors(self, topic, count): + self.error_sensor.record(count) + sensor = self.metrics.get_sensor('topic.' + topic + '.record-errors') + if sensor: + sensor.record(count) + + def record_throttle_time(self, throttle_time_ms, node=None): + self.produce_throttle_time_sensor.record(throttle_time_ms) diff --git a/testbed/dpkp__kafka-python/kafka/protocol/__init__.py b/testbed/dpkp__kafka-python/kafka/protocol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e739b5cb107bdb33e13c346d8f945333872eb48a --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/__init__.py @@ -0,0 +1,47 @@ +from __future__ import absolute_import + + +API_KEYS = { + 0: 'Produce', + 1: 'Fetch', + 2: 'ListOffsets', + 3: 'Metadata', + 4: 'LeaderAndIsr', + 5: 'StopReplica', + 6: 'UpdateMetadata', + 7: 'ControlledShutdown', + 8: 'OffsetCommit', + 9: 'OffsetFetch', + 10: 'FindCoordinator', + 11: 'JoinGroup', + 12: 'Heartbeat', + 13: 'LeaveGroup', + 14: 'SyncGroup', + 15: 'DescribeGroups', + 16: 'ListGroups', + 17: 'SaslHandshake', + 18: 'ApiVersions', + 19: 'CreateTopics', + 20: 'DeleteTopics', + 21: 'DeleteRecords', + 22: 'InitProducerId', + 23: 'OffsetForLeaderEpoch', + 24: 'AddPartitionsToTxn', + 25: 'AddOffsetsToTxn', + 26: 'EndTxn', + 27: 'WriteTxnMarkers', + 28: 'TxnOffsetCommit', + 29: 'DescribeAcls', + 30: 'CreateAcls', + 31: 'DeleteAcls', + 32: 'DescribeConfigs', + 33: 'AlterConfigs', + 36: 'SaslAuthenticate', + 37: 'CreatePartitions', + 38: 'CreateDelegationToken', + 39: 'RenewDelegationToken', + 40: 'ExpireDelegationToken', + 41: 'DescribeDelegationToken', + 42: 'DeleteGroups', + 48: 'DescribeClientQuotas', +} diff --git a/testbed/dpkp__kafka-python/kafka/protocol/abstract.py b/testbed/dpkp__kafka-python/kafka/protocol/abstract.py new file mode 100644 index 0000000000000000000000000000000000000000..2de65c4bb2ea4c7c46182889bc6128ea83f54365 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/abstract.py @@ -0,0 +1,19 @@ +from __future__ import absolute_import + +import abc + + +class AbstractType(object): + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod + def encode(cls, value): # pylint: disable=no-self-argument + pass + + @abc.abstractmethod + def decode(cls, data): # pylint: disable=no-self-argument + pass + + @classmethod + def repr(cls, value): + return repr(value) diff --git a/testbed/dpkp__kafka-python/kafka/protocol/admin.py b/testbed/dpkp__kafka-python/kafka/protocol/admin.py new file mode 100644 index 0000000000000000000000000000000000000000..63a3327a6ad9b21fe25f6d91a06969d0683e0206 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/admin.py @@ -0,0 +1,965 @@ +from __future__ import absolute_import + +from kafka.protocol.api import Request, Response +from kafka.protocol.types import Array, Boolean, Bytes, Int8, Int16, Int32, Int64, Schema, String, Float64 + + +class ApiVersionResponse_v0(Response): + API_KEY = 18 + API_VERSION = 0 + SCHEMA = Schema( + ('error_code', Int16), + ('api_versions', Array( + ('api_key', Int16), + ('min_version', Int16), + ('max_version', Int16))) + ) + + +class ApiVersionResponse_v1(Response): + API_KEY = 18 + API_VERSION = 1 + SCHEMA = Schema( + ('error_code', Int16), + ('api_versions', Array( + ('api_key', Int16), + ('min_version', Int16), + ('max_version', Int16))), + ('throttle_time_ms', Int32) + ) + + +class ApiVersionResponse_v2(Response): + API_KEY = 18 + API_VERSION = 2 + SCHEMA = ApiVersionResponse_v1.SCHEMA + + +class ApiVersionRequest_v0(Request): + API_KEY = 18 + API_VERSION = 0 + RESPONSE_TYPE = ApiVersionResponse_v0 + SCHEMA = Schema() + + +class ApiVersionRequest_v1(Request): + API_KEY = 18 + API_VERSION = 1 + RESPONSE_TYPE = ApiVersionResponse_v1 + SCHEMA = ApiVersionRequest_v0.SCHEMA + + +class ApiVersionRequest_v2(Request): + API_KEY = 18 + API_VERSION = 2 + RESPONSE_TYPE = ApiVersionResponse_v1 + SCHEMA = ApiVersionRequest_v0.SCHEMA + + +ApiVersionRequest = [ + ApiVersionRequest_v0, ApiVersionRequest_v1, ApiVersionRequest_v2, +] +ApiVersionResponse = [ + ApiVersionResponse_v0, ApiVersionResponse_v1, ApiVersionResponse_v2, +] + + +class CreateTopicsResponse_v0(Response): + API_KEY = 19 + API_VERSION = 0 + SCHEMA = Schema( + ('topic_errors', Array( + ('topic', String('utf-8')), + ('error_code', Int16))) + ) + + +class CreateTopicsResponse_v1(Response): + API_KEY = 19 + API_VERSION = 1 + SCHEMA = Schema( + ('topic_errors', Array( + ('topic', String('utf-8')), + ('error_code', Int16), + ('error_message', String('utf-8')))) + ) + + +class CreateTopicsResponse_v2(Response): + API_KEY = 19 + API_VERSION = 2 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topic_errors', Array( + ('topic', String('utf-8')), + ('error_code', Int16), + ('error_message', String('utf-8')))) + ) + +class CreateTopicsResponse_v3(Response): + API_KEY = 19 + API_VERSION = 3 + SCHEMA = CreateTopicsResponse_v2.SCHEMA + + +class CreateTopicsRequest_v0(Request): + API_KEY = 19 + API_VERSION = 0 + RESPONSE_TYPE = CreateTopicsResponse_v0 + SCHEMA = Schema( + ('create_topic_requests', Array( + ('topic', String('utf-8')), + ('num_partitions', Int32), + ('replication_factor', Int16), + ('replica_assignment', Array( + ('partition_id', Int32), + ('replicas', Array(Int32)))), + ('configs', Array( + ('config_key', String('utf-8')), + ('config_value', String('utf-8')))))), + ('timeout', Int32) + ) + + +class CreateTopicsRequest_v1(Request): + API_KEY = 19 + API_VERSION = 1 + RESPONSE_TYPE = CreateTopicsResponse_v1 + SCHEMA = Schema( + ('create_topic_requests', Array( + ('topic', String('utf-8')), + ('num_partitions', Int32), + ('replication_factor', Int16), + ('replica_assignment', Array( + ('partition_id', Int32), + ('replicas', Array(Int32)))), + ('configs', Array( + ('config_key', String('utf-8')), + ('config_value', String('utf-8')))))), + ('timeout', Int32), + ('validate_only', Boolean) + ) + + +class CreateTopicsRequest_v2(Request): + API_KEY = 19 + API_VERSION = 2 + RESPONSE_TYPE = CreateTopicsResponse_v2 + SCHEMA = CreateTopicsRequest_v1.SCHEMA + + +class CreateTopicsRequest_v3(Request): + API_KEY = 19 + API_VERSION = 3 + RESPONSE_TYPE = CreateTopicsResponse_v3 + SCHEMA = CreateTopicsRequest_v1.SCHEMA + + +CreateTopicsRequest = [ + CreateTopicsRequest_v0, CreateTopicsRequest_v1, + CreateTopicsRequest_v2, CreateTopicsRequest_v3, +] +CreateTopicsResponse = [ + CreateTopicsResponse_v0, CreateTopicsResponse_v1, + CreateTopicsResponse_v2, CreateTopicsResponse_v3, +] + + +class DeleteTopicsResponse_v0(Response): + API_KEY = 20 + API_VERSION = 0 + SCHEMA = Schema( + ('topic_error_codes', Array( + ('topic', String('utf-8')), + ('error_code', Int16))) + ) + + +class DeleteTopicsResponse_v1(Response): + API_KEY = 20 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topic_error_codes', Array( + ('topic', String('utf-8')), + ('error_code', Int16))) + ) + + +class DeleteTopicsResponse_v2(Response): + API_KEY = 20 + API_VERSION = 2 + SCHEMA = DeleteTopicsResponse_v1.SCHEMA + + +class DeleteTopicsResponse_v3(Response): + API_KEY = 20 + API_VERSION = 3 + SCHEMA = DeleteTopicsResponse_v1.SCHEMA + + +class DeleteTopicsRequest_v0(Request): + API_KEY = 20 + API_VERSION = 0 + RESPONSE_TYPE = DeleteTopicsResponse_v0 + SCHEMA = Schema( + ('topics', Array(String('utf-8'))), + ('timeout', Int32) + ) + + +class DeleteTopicsRequest_v1(Request): + API_KEY = 20 + API_VERSION = 1 + RESPONSE_TYPE = DeleteTopicsResponse_v1 + SCHEMA = DeleteTopicsRequest_v0.SCHEMA + + +class DeleteTopicsRequest_v2(Request): + API_KEY = 20 + API_VERSION = 2 + RESPONSE_TYPE = DeleteTopicsResponse_v2 + SCHEMA = DeleteTopicsRequest_v0.SCHEMA + + +class DeleteTopicsRequest_v3(Request): + API_KEY = 20 + API_VERSION = 3 + RESPONSE_TYPE = DeleteTopicsResponse_v3 + SCHEMA = DeleteTopicsRequest_v0.SCHEMA + + +DeleteTopicsRequest = [ + DeleteTopicsRequest_v0, DeleteTopicsRequest_v1, + DeleteTopicsRequest_v2, DeleteTopicsRequest_v3, +] +DeleteTopicsResponse = [ + DeleteTopicsResponse_v0, DeleteTopicsResponse_v1, + DeleteTopicsResponse_v2, DeleteTopicsResponse_v3, +] + + +class ListGroupsResponse_v0(Response): + API_KEY = 16 + API_VERSION = 0 + SCHEMA = Schema( + ('error_code', Int16), + ('groups', Array( + ('group', String('utf-8')), + ('protocol_type', String('utf-8')))) + ) + + +class ListGroupsResponse_v1(Response): + API_KEY = 16 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('error_code', Int16), + ('groups', Array( + ('group', String('utf-8')), + ('protocol_type', String('utf-8')))) + ) + +class ListGroupsResponse_v2(Response): + API_KEY = 16 + API_VERSION = 2 + SCHEMA = ListGroupsResponse_v1.SCHEMA + + +class ListGroupsRequest_v0(Request): + API_KEY = 16 + API_VERSION = 0 + RESPONSE_TYPE = ListGroupsResponse_v0 + SCHEMA = Schema() + + +class ListGroupsRequest_v1(Request): + API_KEY = 16 + API_VERSION = 1 + RESPONSE_TYPE = ListGroupsResponse_v1 + SCHEMA = ListGroupsRequest_v0.SCHEMA + +class ListGroupsRequest_v2(Request): + API_KEY = 16 + API_VERSION = 1 + RESPONSE_TYPE = ListGroupsResponse_v2 + SCHEMA = ListGroupsRequest_v0.SCHEMA + + +ListGroupsRequest = [ + ListGroupsRequest_v0, ListGroupsRequest_v1, + ListGroupsRequest_v2, +] +ListGroupsResponse = [ + ListGroupsResponse_v0, ListGroupsResponse_v1, + ListGroupsResponse_v2, +] + + +class DescribeGroupsResponse_v0(Response): + API_KEY = 15 + API_VERSION = 0 + SCHEMA = Schema( + ('groups', Array( + ('error_code', Int16), + ('group', String('utf-8')), + ('state', String('utf-8')), + ('protocol_type', String('utf-8')), + ('protocol', String('utf-8')), + ('members', Array( + ('member_id', String('utf-8')), + ('client_id', String('utf-8')), + ('client_host', String('utf-8')), + ('member_metadata', Bytes), + ('member_assignment', Bytes))))) + ) + + +class DescribeGroupsResponse_v1(Response): + API_KEY = 15 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('groups', Array( + ('error_code', Int16), + ('group', String('utf-8')), + ('state', String('utf-8')), + ('protocol_type', String('utf-8')), + ('protocol', String('utf-8')), + ('members', Array( + ('member_id', String('utf-8')), + ('client_id', String('utf-8')), + ('client_host', String('utf-8')), + ('member_metadata', Bytes), + ('member_assignment', Bytes))))) + ) + + +class DescribeGroupsResponse_v2(Response): + API_KEY = 15 + API_VERSION = 2 + SCHEMA = DescribeGroupsResponse_v1.SCHEMA + + +class DescribeGroupsResponse_v3(Response): + API_KEY = 15 + API_VERSION = 3 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('groups', Array( + ('error_code', Int16), + ('group', String('utf-8')), + ('state', String('utf-8')), + ('protocol_type', String('utf-8')), + ('protocol', String('utf-8')), + ('members', Array( + ('member_id', String('utf-8')), + ('client_id', String('utf-8')), + ('client_host', String('utf-8')), + ('member_metadata', Bytes), + ('member_assignment', Bytes)))), + ('authorized_operations', Int32)) + ) + + +class DescribeGroupsRequest_v0(Request): + API_KEY = 15 + API_VERSION = 0 + RESPONSE_TYPE = DescribeGroupsResponse_v0 + SCHEMA = Schema( + ('groups', Array(String('utf-8'))) + ) + + +class DescribeGroupsRequest_v1(Request): + API_KEY = 15 + API_VERSION = 1 + RESPONSE_TYPE = DescribeGroupsResponse_v1 + SCHEMA = DescribeGroupsRequest_v0.SCHEMA + + +class DescribeGroupsRequest_v2(Request): + API_KEY = 15 + API_VERSION = 2 + RESPONSE_TYPE = DescribeGroupsResponse_v2 + SCHEMA = DescribeGroupsRequest_v0.SCHEMA + + +class DescribeGroupsRequest_v3(Request): + API_KEY = 15 + API_VERSION = 3 + RESPONSE_TYPE = DescribeGroupsResponse_v2 + SCHEMA = Schema( + ('groups', Array(String('utf-8'))), + ('include_authorized_operations', Boolean) + ) + + +DescribeGroupsRequest = [ + DescribeGroupsRequest_v0, DescribeGroupsRequest_v1, + DescribeGroupsRequest_v2, DescribeGroupsRequest_v3, +] +DescribeGroupsResponse = [ + DescribeGroupsResponse_v0, DescribeGroupsResponse_v1, + DescribeGroupsResponse_v2, DescribeGroupsResponse_v3, +] + + +class SaslHandShakeResponse_v0(Response): + API_KEY = 17 + API_VERSION = 0 + SCHEMA = Schema( + ('error_code', Int16), + ('enabled_mechanisms', Array(String('utf-8'))) + ) + + +class SaslHandShakeResponse_v1(Response): + API_KEY = 17 + API_VERSION = 1 + SCHEMA = SaslHandShakeResponse_v0.SCHEMA + + +class SaslHandShakeRequest_v0(Request): + API_KEY = 17 + API_VERSION = 0 + RESPONSE_TYPE = SaslHandShakeResponse_v0 + SCHEMA = Schema( + ('mechanism', String('utf-8')) + ) + + +class SaslHandShakeRequest_v1(Request): + API_KEY = 17 + API_VERSION = 1 + RESPONSE_TYPE = SaslHandShakeResponse_v1 + SCHEMA = SaslHandShakeRequest_v0.SCHEMA + + +SaslHandShakeRequest = [SaslHandShakeRequest_v0, SaslHandShakeRequest_v1] +SaslHandShakeResponse = [SaslHandShakeResponse_v0, SaslHandShakeResponse_v1] + + +class DescribeAclsResponse_v0(Response): + API_KEY = 29 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resources', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('acls', Array( + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))))) + ) + + +class DescribeAclsResponse_v1(Response): + API_KEY = 29 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resources', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('resource_pattern_type', Int8), + ('acls', Array( + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))))) + ) + + +class DescribeAclsResponse_v2(Response): + API_KEY = 29 + API_VERSION = 2 + SCHEMA = DescribeAclsResponse_v1.SCHEMA + + +class DescribeAclsRequest_v0(Request): + API_KEY = 29 + API_VERSION = 0 + RESPONSE_TYPE = DescribeAclsResponse_v0 + SCHEMA = Schema( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8) + ) + + +class DescribeAclsRequest_v1(Request): + API_KEY = 29 + API_VERSION = 1 + RESPONSE_TYPE = DescribeAclsResponse_v1 + SCHEMA = Schema( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('resource_pattern_type_filter', Int8), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8) + ) + + +class DescribeAclsRequest_v2(Request): + """ + Enable flexible version + """ + API_KEY = 29 + API_VERSION = 2 + RESPONSE_TYPE = DescribeAclsResponse_v2 + SCHEMA = DescribeAclsRequest_v1.SCHEMA + + +DescribeAclsRequest = [DescribeAclsRequest_v0, DescribeAclsRequest_v1] +DescribeAclsResponse = [DescribeAclsResponse_v0, DescribeAclsResponse_v1] + +class CreateAclsResponse_v0(Response): + API_KEY = 30 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('creation_responses', Array( + ('error_code', Int16), + ('error_message', String('utf-8')))) + ) + +class CreateAclsResponse_v1(Response): + API_KEY = 30 + API_VERSION = 1 + SCHEMA = CreateAclsResponse_v0.SCHEMA + +class CreateAclsRequest_v0(Request): + API_KEY = 30 + API_VERSION = 0 + RESPONSE_TYPE = CreateAclsResponse_v0 + SCHEMA = Schema( + ('creations', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))) + ) + +class CreateAclsRequest_v1(Request): + API_KEY = 30 + API_VERSION = 1 + RESPONSE_TYPE = CreateAclsResponse_v1 + SCHEMA = Schema( + ('creations', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('resource_pattern_type', Int8), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))) + ) + +CreateAclsRequest = [CreateAclsRequest_v0, CreateAclsRequest_v1] +CreateAclsResponse = [CreateAclsResponse_v0, CreateAclsResponse_v1] + +class DeleteAclsResponse_v0(Response): + API_KEY = 31 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('filter_responses', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('matching_acls', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))))) + ) + +class DeleteAclsResponse_v1(Response): + API_KEY = 31 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('filter_responses', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('matching_acls', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('resource_pattern_type', Int8), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))))) + ) + +class DeleteAclsRequest_v0(Request): + API_KEY = 31 + API_VERSION = 0 + RESPONSE_TYPE = DeleteAclsResponse_v0 + SCHEMA = Schema( + ('filters', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))) + ) + +class DeleteAclsRequest_v1(Request): + API_KEY = 31 + API_VERSION = 1 + RESPONSE_TYPE = DeleteAclsResponse_v1 + SCHEMA = Schema( + ('filters', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('resource_pattern_type_filter', Int8), + ('principal', String('utf-8')), + ('host', String('utf-8')), + ('operation', Int8), + ('permission_type', Int8))) + ) + +DeleteAclsRequest = [DeleteAclsRequest_v0, DeleteAclsRequest_v1] +DeleteAclsResponse = [DeleteAclsResponse_v0, DeleteAclsResponse_v1] + +class AlterConfigsResponse_v0(Response): + API_KEY = 33 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('resources', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resource_type', Int8), + ('resource_name', String('utf-8')))) + ) + + +class AlterConfigsResponse_v1(Response): + API_KEY = 33 + API_VERSION = 1 + SCHEMA = AlterConfigsResponse_v0.SCHEMA + + +class AlterConfigsRequest_v0(Request): + API_KEY = 33 + API_VERSION = 0 + RESPONSE_TYPE = AlterConfigsResponse_v0 + SCHEMA = Schema( + ('resources', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('config_entries', Array( + ('config_name', String('utf-8')), + ('config_value', String('utf-8')))))), + ('validate_only', Boolean) + ) + +class AlterConfigsRequest_v1(Request): + API_KEY = 33 + API_VERSION = 1 + RESPONSE_TYPE = AlterConfigsResponse_v1 + SCHEMA = AlterConfigsRequest_v0.SCHEMA + +AlterConfigsRequest = [AlterConfigsRequest_v0, AlterConfigsRequest_v1] +AlterConfigsResponse = [AlterConfigsResponse_v0, AlterConfigsRequest_v1] + + +class DescribeConfigsResponse_v0(Response): + API_KEY = 32 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('resources', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('config_entries', Array( + ('config_names', String('utf-8')), + ('config_value', String('utf-8')), + ('read_only', Boolean), + ('is_default', Boolean), + ('is_sensitive', Boolean))))) + ) + +class DescribeConfigsResponse_v1(Response): + API_KEY = 32 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('resources', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('config_entries', Array( + ('config_names', String('utf-8')), + ('config_value', String('utf-8')), + ('read_only', Boolean), + ('is_default', Boolean), + ('is_sensitive', Boolean), + ('config_synonyms', Array( + ('config_name', String('utf-8')), + ('config_value', String('utf-8')), + ('config_source', Int8))))))) + ) + +class DescribeConfigsResponse_v2(Response): + API_KEY = 32 + API_VERSION = 2 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('resources', Array( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('config_entries', Array( + ('config_names', String('utf-8')), + ('config_value', String('utf-8')), + ('read_only', Boolean), + ('config_source', Int8), + ('is_sensitive', Boolean), + ('config_synonyms', Array( + ('config_name', String('utf-8')), + ('config_value', String('utf-8')), + ('config_source', Int8))))))) + ) + +class DescribeConfigsRequest_v0(Request): + API_KEY = 32 + API_VERSION = 0 + RESPONSE_TYPE = DescribeConfigsResponse_v0 + SCHEMA = Schema( + ('resources', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('config_names', Array(String('utf-8'))))) + ) + +class DescribeConfigsRequest_v1(Request): + API_KEY = 32 + API_VERSION = 1 + RESPONSE_TYPE = DescribeConfigsResponse_v1 + SCHEMA = Schema( + ('resources', Array( + ('resource_type', Int8), + ('resource_name', String('utf-8')), + ('config_names', Array(String('utf-8'))))), + ('include_synonyms', Boolean) + ) + + +class DescribeConfigsRequest_v2(Request): + API_KEY = 32 + API_VERSION = 2 + RESPONSE_TYPE = DescribeConfigsResponse_v2 + SCHEMA = DescribeConfigsRequest_v1.SCHEMA + + +DescribeConfigsRequest = [ + DescribeConfigsRequest_v0, DescribeConfigsRequest_v1, + DescribeConfigsRequest_v2, +] +DescribeConfigsResponse = [ + DescribeConfigsResponse_v0, DescribeConfigsResponse_v1, + DescribeConfigsResponse_v2, +] + + +class SaslAuthenticateResponse_v0(Response): + API_KEY = 36 + API_VERSION = 0 + SCHEMA = Schema( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('sasl_auth_bytes', Bytes) + ) + + +class SaslAuthenticateResponse_v1(Response): + API_KEY = 36 + API_VERSION = 1 + SCHEMA = Schema( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('sasl_auth_bytes', Bytes), + ('session_lifetime_ms', Int64) + ) + + +class SaslAuthenticateRequest_v0(Request): + API_KEY = 36 + API_VERSION = 0 + RESPONSE_TYPE = SaslAuthenticateResponse_v0 + SCHEMA = Schema( + ('sasl_auth_bytes', Bytes) + ) + + +class SaslAuthenticateRequest_v1(Request): + API_KEY = 36 + API_VERSION = 1 + RESPONSE_TYPE = SaslAuthenticateResponse_v1 + SCHEMA = SaslAuthenticateRequest_v0.SCHEMA + + +SaslAuthenticateRequest = [ + SaslAuthenticateRequest_v0, SaslAuthenticateRequest_v1, +] +SaslAuthenticateResponse = [ + SaslAuthenticateResponse_v0, SaslAuthenticateResponse_v1, +] + + +class CreatePartitionsResponse_v0(Response): + API_KEY = 37 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topic_errors', Array( + ('topic', String('utf-8')), + ('error_code', Int16), + ('error_message', String('utf-8')))) + ) + + +class CreatePartitionsResponse_v1(Response): + API_KEY = 37 + API_VERSION = 1 + SCHEMA = CreatePartitionsResponse_v0.SCHEMA + + +class CreatePartitionsRequest_v0(Request): + API_KEY = 37 + API_VERSION = 0 + RESPONSE_TYPE = CreatePartitionsResponse_v0 + SCHEMA = Schema( + ('topic_partitions', Array( + ('topic', String('utf-8')), + ('new_partitions', Schema( + ('count', Int32), + ('assignment', Array(Array(Int32))))))), + ('timeout', Int32), + ('validate_only', Boolean) + ) + + +class CreatePartitionsRequest_v1(Request): + API_KEY = 37 + API_VERSION = 1 + SCHEMA = CreatePartitionsRequest_v0.SCHEMA + RESPONSE_TYPE = CreatePartitionsResponse_v1 + + +CreatePartitionsRequest = [ + CreatePartitionsRequest_v0, CreatePartitionsRequest_v1, +] +CreatePartitionsResponse = [ + CreatePartitionsResponse_v0, CreatePartitionsResponse_v1, +] + + +class DeleteGroupsResponse_v0(Response): + API_KEY = 42 + API_VERSION = 0 + SCHEMA = Schema( + ("throttle_time_ms", Int32), + ("results", Array( + ("group_id", String("utf-8")), + ("error_code", Int16))) + ) + + +class DeleteGroupsResponse_v1(Response): + API_KEY = 42 + API_VERSION = 1 + SCHEMA = DeleteGroupsResponse_v0.SCHEMA + + +class DeleteGroupsRequest_v0(Request): + API_KEY = 42 + API_VERSION = 0 + RESPONSE_TYPE = DeleteGroupsResponse_v0 + SCHEMA = Schema( + ("groups_names", Array(String("utf-8"))) + ) + + +class DeleteGroupsRequest_v1(Request): + API_KEY = 42 + API_VERSION = 1 + RESPONSE_TYPE = DeleteGroupsResponse_v1 + SCHEMA = DeleteGroupsRequest_v0.SCHEMA + + +DeleteGroupsRequest = [ + DeleteGroupsRequest_v0, DeleteGroupsRequest_v1 +] + +DeleteGroupsResponse = [ + DeleteGroupsResponse_v0, DeleteGroupsResponse_v1 +] + + +class DescribeClientQuotasResponse_v0(Request): + API_KEY = 48 + API_VERSION = 0 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('error_code', Int16), + ('error_message', String('utf-8')), + ('entries', Array( + ('entity', Array( + ('entity_type', String('utf-8')), + ('entity_name', String('utf-8')))), + ('values', Array( + ('name', String('utf-8')), + ('value', Float64))))), + ) + + +class DescribeClientQuotasRequest_v0(Request): + API_KEY = 48 + API_VERSION = 0 + RESPONSE_TYPE = DescribeClientQuotasResponse_v0 + SCHEMA = Schema( + ('components', Array( + ('entity_type', String('utf-8')), + ('match_type', Int8), + ('match', String('utf-8')), + )), + ('strict', Boolean) + ) + + +DescribeClientQuotasRequest = [ + DescribeClientQuotasRequest_v0, +] + +DescribeClientQuotasResponse = [ + DescribeClientQuotasResponse_v0, +] diff --git a/testbed/dpkp__kafka-python/kafka/protocol/api.py b/testbed/dpkp__kafka-python/kafka/protocol/api.py new file mode 100644 index 0000000000000000000000000000000000000000..64276fc1750140cc41bebc725532dce1b9a126ee --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/api.py @@ -0,0 +1,97 @@ +from __future__ import absolute_import + +import abc + +from kafka.protocol.struct import Struct +from kafka.protocol.types import Int16, Int32, String, Schema, Array + + +class RequestHeader(Struct): + SCHEMA = Schema( + ('api_key', Int16), + ('api_version', Int16), + ('correlation_id', Int32), + ('client_id', String('utf-8')) + ) + + def __init__(self, request, correlation_id=0, client_id='kafka-python'): + super(RequestHeader, self).__init__( + request.API_KEY, request.API_VERSION, correlation_id, client_id + ) + + +class Request(Struct): + __metaclass__ = abc.ABCMeta + + @abc.abstractproperty + def API_KEY(self): + """Integer identifier for api request""" + pass + + @abc.abstractproperty + def API_VERSION(self): + """Integer of api request version""" + pass + + @abc.abstractproperty + def SCHEMA(self): + """An instance of Schema() representing the request structure""" + pass + + @abc.abstractproperty + def RESPONSE_TYPE(self): + """The Response class associated with the api request""" + pass + + def expect_response(self): + """Override this method if an api request does not always generate a response""" + return True + + def to_object(self): + return _to_object(self.SCHEMA, self) + + +class Response(Struct): + __metaclass__ = abc.ABCMeta + + @abc.abstractproperty + def API_KEY(self): + """Integer identifier for api request/response""" + pass + + @abc.abstractproperty + def API_VERSION(self): + """Integer of api request/response version""" + pass + + @abc.abstractproperty + def SCHEMA(self): + """An instance of Schema() representing the response structure""" + pass + + def to_object(self): + return _to_object(self.SCHEMA, self) + + +def _to_object(schema, data): + obj = {} + for idx, (name, _type) in enumerate(zip(schema.names, schema.fields)): + if isinstance(data, Struct): + val = data.get_item(name) + else: + val = data[idx] + + if isinstance(_type, Schema): + obj[name] = _to_object(_type, val) + elif isinstance(_type, Array): + if isinstance(_type.array_of, (Array, Schema)): + obj[name] = [ + _to_object(_type.array_of, x) + for x in val + ] + else: + obj[name] = val + else: + obj[name] = val + + return obj diff --git a/testbed/dpkp__kafka-python/kafka/protocol/commit.py b/testbed/dpkp__kafka-python/kafka/protocol/commit.py new file mode 100644 index 0000000000000000000000000000000000000000..31fc23707d17cfaeff72b39ade170565fd3f3c33 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/commit.py @@ -0,0 +1,255 @@ +from __future__ import absolute_import + +from kafka.protocol.api import Request, Response +from kafka.protocol.types import Array, Int8, Int16, Int32, Int64, Schema, String + + +class OffsetCommitResponse_v0(Response): + API_KEY = 8 + API_VERSION = 0 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16))))) + ) + + +class OffsetCommitResponse_v1(Response): + API_KEY = 8 + API_VERSION = 1 + SCHEMA = OffsetCommitResponse_v0.SCHEMA + + +class OffsetCommitResponse_v2(Response): + API_KEY = 8 + API_VERSION = 2 + SCHEMA = OffsetCommitResponse_v1.SCHEMA + + +class OffsetCommitResponse_v3(Response): + API_KEY = 8 + API_VERSION = 3 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16))))) + ) + + +class OffsetCommitRequest_v0(Request): + API_KEY = 8 + API_VERSION = 0 # Zookeeper-backed storage + RESPONSE_TYPE = OffsetCommitResponse_v0 + SCHEMA = Schema( + ('consumer_group', String('utf-8')), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('metadata', String('utf-8')))))) + ) + + +class OffsetCommitRequest_v1(Request): + API_KEY = 8 + API_VERSION = 1 # Kafka-backed storage + RESPONSE_TYPE = OffsetCommitResponse_v1 + SCHEMA = Schema( + ('consumer_group', String('utf-8')), + ('consumer_group_generation_id', Int32), + ('consumer_id', String('utf-8')), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('timestamp', Int64), + ('metadata', String('utf-8')))))) + ) + + +class OffsetCommitRequest_v2(Request): + API_KEY = 8 + API_VERSION = 2 # added retention_time, dropped timestamp + RESPONSE_TYPE = OffsetCommitResponse_v2 + SCHEMA = Schema( + ('consumer_group', String('utf-8')), + ('consumer_group_generation_id', Int32), + ('consumer_id', String('utf-8')), + ('retention_time', Int64), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('metadata', String('utf-8')))))) + ) + DEFAULT_GENERATION_ID = -1 + DEFAULT_RETENTION_TIME = -1 + + +class OffsetCommitRequest_v3(Request): + API_KEY = 8 + API_VERSION = 3 + RESPONSE_TYPE = OffsetCommitResponse_v3 + SCHEMA = OffsetCommitRequest_v2.SCHEMA + + +OffsetCommitRequest = [ + OffsetCommitRequest_v0, OffsetCommitRequest_v1, + OffsetCommitRequest_v2, OffsetCommitRequest_v3 +] +OffsetCommitResponse = [ + OffsetCommitResponse_v0, OffsetCommitResponse_v1, + OffsetCommitResponse_v2, OffsetCommitResponse_v3 +] + + +class OffsetFetchResponse_v0(Response): + API_KEY = 9 + API_VERSION = 0 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('metadata', String('utf-8')), + ('error_code', Int16))))) + ) + + +class OffsetFetchResponse_v1(Response): + API_KEY = 9 + API_VERSION = 1 + SCHEMA = OffsetFetchResponse_v0.SCHEMA + + +class OffsetFetchResponse_v2(Response): + # Added in KIP-88 + API_KEY = 9 + API_VERSION = 2 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('metadata', String('utf-8')), + ('error_code', Int16))))), + ('error_code', Int16) + ) + + +class OffsetFetchResponse_v3(Response): + API_KEY = 9 + API_VERSION = 3 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('metadata', String('utf-8')), + ('error_code', Int16))))), + ('error_code', Int16) + ) + + +class OffsetFetchRequest_v0(Request): + API_KEY = 9 + API_VERSION = 0 # zookeeper-backed storage + RESPONSE_TYPE = OffsetFetchResponse_v0 + SCHEMA = Schema( + ('consumer_group', String('utf-8')), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array(Int32)))) + ) + + +class OffsetFetchRequest_v1(Request): + API_KEY = 9 + API_VERSION = 1 # kafka-backed storage + RESPONSE_TYPE = OffsetFetchResponse_v1 + SCHEMA = OffsetFetchRequest_v0.SCHEMA + + +class OffsetFetchRequest_v2(Request): + # KIP-88: Allows passing null topics to return offsets for all partitions + # that the consumer group has a stored offset for, even if no consumer in + # the group is currently consuming that partition. + API_KEY = 9 + API_VERSION = 2 + RESPONSE_TYPE = OffsetFetchResponse_v2 + SCHEMA = OffsetFetchRequest_v1.SCHEMA + + +class OffsetFetchRequest_v3(Request): + API_KEY = 9 + API_VERSION = 3 + RESPONSE_TYPE = OffsetFetchResponse_v3 + SCHEMA = OffsetFetchRequest_v2.SCHEMA + + +OffsetFetchRequest = [ + OffsetFetchRequest_v0, OffsetFetchRequest_v1, + OffsetFetchRequest_v2, OffsetFetchRequest_v3, +] +OffsetFetchResponse = [ + OffsetFetchResponse_v0, OffsetFetchResponse_v1, + OffsetFetchResponse_v2, OffsetFetchResponse_v3, +] + + +class GroupCoordinatorResponse_v0(Response): + API_KEY = 10 + API_VERSION = 0 + SCHEMA = Schema( + ('error_code', Int16), + ('coordinator_id', Int32), + ('host', String('utf-8')), + ('port', Int32) + ) + + +class GroupCoordinatorResponse_v1(Response): + API_KEY = 10 + API_VERSION = 1 + SCHEMA = Schema( + ('error_code', Int16), + ('error_message', String('utf-8')), + ('coordinator_id', Int32), + ('host', String('utf-8')), + ('port', Int32) + ) + + +class GroupCoordinatorRequest_v0(Request): + API_KEY = 10 + API_VERSION = 0 + RESPONSE_TYPE = GroupCoordinatorResponse_v0 + SCHEMA = Schema( + ('consumer_group', String('utf-8')) + ) + + +class GroupCoordinatorRequest_v1(Request): + API_KEY = 10 + API_VERSION = 1 + RESPONSE_TYPE = GroupCoordinatorResponse_v1 + SCHEMA = Schema( + ('coordinator_key', String('utf-8')), + ('coordinator_type', Int8) + ) + + +GroupCoordinatorRequest = [GroupCoordinatorRequest_v0, GroupCoordinatorRequest_v1] +GroupCoordinatorResponse = [GroupCoordinatorResponse_v0, GroupCoordinatorResponse_v1] diff --git a/testbed/dpkp__kafka-python/kafka/protocol/fetch.py b/testbed/dpkp__kafka-python/kafka/protocol/fetch.py new file mode 100644 index 0000000000000000000000000000000000000000..f367848ce49dc611b124b3f29a33141f22cfa1ca --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/fetch.py @@ -0,0 +1,386 @@ +from __future__ import absolute_import + +from kafka.protocol.api import Request, Response +from kafka.protocol.types import Array, Int8, Int16, Int32, Int64, Schema, String, Bytes + + +class FetchResponse_v0(Response): + API_KEY = 1 + API_VERSION = 0 + SCHEMA = Schema( + ('topics', Array( + ('topics', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('highwater_offset', Int64), + ('message_set', Bytes))))) + ) + + +class FetchResponse_v1(Response): + API_KEY = 1 + API_VERSION = 1 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topics', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('highwater_offset', Int64), + ('message_set', Bytes))))) + ) + + +class FetchResponse_v2(Response): + API_KEY = 1 + API_VERSION = 2 + SCHEMA = FetchResponse_v1.SCHEMA # message format changed internally + + +class FetchResponse_v3(Response): + API_KEY = 1 + API_VERSION = 3 + SCHEMA = FetchResponse_v2.SCHEMA + + +class FetchResponse_v4(Response): + API_KEY = 1 + API_VERSION = 4 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topics', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('highwater_offset', Int64), + ('last_stable_offset', Int64), + ('aborted_transactions', Array( + ('producer_id', Int64), + ('first_offset', Int64))), + ('message_set', Bytes))))) + ) + + +class FetchResponse_v5(Response): + API_KEY = 1 + API_VERSION = 5 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topics', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('highwater_offset', Int64), + ('last_stable_offset', Int64), + ('log_start_offset', Int64), + ('aborted_transactions', Array( + ('producer_id', Int64), + ('first_offset', Int64))), + ('message_set', Bytes))))) + ) + + +class FetchResponse_v6(Response): + """ + Same as FetchResponse_v5. The version number is bumped up to indicate that the client supports KafkaStorageException. + The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 5 + """ + API_KEY = 1 + API_VERSION = 6 + SCHEMA = FetchResponse_v5.SCHEMA + + +class FetchResponse_v7(Response): + """ + Add error_code and session_id to response + """ + API_KEY = 1 + API_VERSION = 7 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('error_code', Int16), + ('session_id', Int32), + ('topics', Array( + ('topics', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('highwater_offset', Int64), + ('last_stable_offset', Int64), + ('log_start_offset', Int64), + ('aborted_transactions', Array( + ('producer_id', Int64), + ('first_offset', Int64))), + ('message_set', Bytes))))) + ) + + +class FetchResponse_v8(Response): + API_KEY = 1 + API_VERSION = 8 + SCHEMA = FetchResponse_v7.SCHEMA + + +class FetchResponse_v9(Response): + API_KEY = 1 + API_VERSION = 9 + SCHEMA = FetchResponse_v7.SCHEMA + + +class FetchResponse_v10(Response): + API_KEY = 1 + API_VERSION = 10 + SCHEMA = FetchResponse_v7.SCHEMA + + +class FetchResponse_v11(Response): + API_KEY = 1 + API_VERSION = 11 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('error_code', Int16), + ('session_id', Int32), + ('topics', Array( + ('topics', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('highwater_offset', Int64), + ('last_stable_offset', Int64), + ('log_start_offset', Int64), + ('aborted_transactions', Array( + ('producer_id', Int64), + ('first_offset', Int64))), + ('preferred_read_replica', Int32), + ('message_set', Bytes))))) + ) + + +class FetchRequest_v0(Request): + API_KEY = 1 + API_VERSION = 0 + RESPONSE_TYPE = FetchResponse_v0 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('max_bytes', Int32))))) + ) + + +class FetchRequest_v1(Request): + API_KEY = 1 + API_VERSION = 1 + RESPONSE_TYPE = FetchResponse_v1 + SCHEMA = FetchRequest_v0.SCHEMA + + +class FetchRequest_v2(Request): + API_KEY = 1 + API_VERSION = 2 + RESPONSE_TYPE = FetchResponse_v2 + SCHEMA = FetchRequest_v1.SCHEMA + + +class FetchRequest_v3(Request): + API_KEY = 1 + API_VERSION = 3 + RESPONSE_TYPE = FetchResponse_v3 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('max_bytes', Int32), # This new field is only difference from FR_v2 + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('max_bytes', Int32))))) + ) + + +class FetchRequest_v4(Request): + # Adds isolation_level field + API_KEY = 1 + API_VERSION = 4 + RESPONSE_TYPE = FetchResponse_v4 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('max_bytes', Int32), + ('isolation_level', Int8), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('offset', Int64), + ('max_bytes', Int32))))) + ) + + +class FetchRequest_v5(Request): + # This may only be used in broker-broker api calls + API_KEY = 1 + API_VERSION = 5 + RESPONSE_TYPE = FetchResponse_v5 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('max_bytes', Int32), + ('isolation_level', Int8), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('fetch_offset', Int64), + ('log_start_offset', Int64), + ('max_bytes', Int32))))) + ) + + +class FetchRequest_v6(Request): + """ + The body of FETCH_REQUEST_V6 is the same as FETCH_REQUEST_V5. + The version number is bumped up to indicate that the client supports KafkaStorageException. + The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 5 + """ + API_KEY = 1 + API_VERSION = 6 + RESPONSE_TYPE = FetchResponse_v6 + SCHEMA = FetchRequest_v5.SCHEMA + + +class FetchRequest_v7(Request): + """ + Add incremental fetch requests + """ + API_KEY = 1 + API_VERSION = 7 + RESPONSE_TYPE = FetchResponse_v7 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('max_bytes', Int32), + ('isolation_level', Int8), + ('session_id', Int32), + ('session_epoch', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('fetch_offset', Int64), + ('log_start_offset', Int64), + ('max_bytes', Int32))))), + ('forgotten_topics_data', Array( + ('topic', String), + ('partitions', Array(Int32)) + )), + ) + + +class FetchRequest_v8(Request): + """ + bump used to indicate that on quota violation brokers send out responses before throttling. + """ + API_KEY = 1 + API_VERSION = 8 + RESPONSE_TYPE = FetchResponse_v8 + SCHEMA = FetchRequest_v7.SCHEMA + + +class FetchRequest_v9(Request): + """ + adds the current leader epoch (see KIP-320) + """ + API_KEY = 1 + API_VERSION = 9 + RESPONSE_TYPE = FetchResponse_v9 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('max_bytes', Int32), + ('isolation_level', Int8), + ('session_id', Int32), + ('session_epoch', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('current_leader_epoch', Int32), + ('fetch_offset', Int64), + ('log_start_offset', Int64), + ('max_bytes', Int32))))), + ('forgotten_topics_data', Array( + ('topic', String), + ('partitions', Array(Int32)), + )), + ) + + +class FetchRequest_v10(Request): + """ + bumped up to indicate ZStandard capability. (see KIP-110) + """ + API_KEY = 1 + API_VERSION = 10 + RESPONSE_TYPE = FetchResponse_v10 + SCHEMA = FetchRequest_v9.SCHEMA + + +class FetchRequest_v11(Request): + """ + added rack ID to support read from followers (KIP-392) + """ + API_KEY = 1 + API_VERSION = 11 + RESPONSE_TYPE = FetchResponse_v11 + SCHEMA = Schema( + ('replica_id', Int32), + ('max_wait_time', Int32), + ('min_bytes', Int32), + ('max_bytes', Int32), + ('isolation_level', Int8), + ('session_id', Int32), + ('session_epoch', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('current_leader_epoch', Int32), + ('fetch_offset', Int64), + ('log_start_offset', Int64), + ('max_bytes', Int32))))), + ('forgotten_topics_data', Array( + ('topic', String), + ('partitions', Array(Int32)) + )), + ('rack_id', String('utf-8')), + ) + + +FetchRequest = [ + FetchRequest_v0, FetchRequest_v1, FetchRequest_v2, + FetchRequest_v3, FetchRequest_v4, FetchRequest_v5, + FetchRequest_v6, FetchRequest_v7, FetchRequest_v8, + FetchRequest_v9, FetchRequest_v10, FetchRequest_v11, +] +FetchResponse = [ + FetchResponse_v0, FetchResponse_v1, FetchResponse_v2, + FetchResponse_v3, FetchResponse_v4, FetchResponse_v5, + FetchResponse_v6, FetchResponse_v7, FetchResponse_v8, + FetchResponse_v9, FetchResponse_v10, FetchResponse_v11, +] diff --git a/testbed/dpkp__kafka-python/kafka/protocol/frame.py b/testbed/dpkp__kafka-python/kafka/protocol/frame.py new file mode 100644 index 0000000000000000000000000000000000000000..7b4a32bcf5ef997d413eee0f2e1695aecf39da47 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/frame.py @@ -0,0 +1,30 @@ +class KafkaBytes(bytearray): + def __init__(self, size): + super(KafkaBytes, self).__init__(size) + self._idx = 0 + + def read(self, nbytes=None): + if nbytes is None: + nbytes = len(self) - self._idx + start = self._idx + self._idx += nbytes + if self._idx > len(self): + self._idx = len(self) + return bytes(self[start:self._idx]) + + def write(self, data): + start = self._idx + self._idx += len(data) + self[start:self._idx] = data + + def seek(self, idx): + self._idx = idx + + def tell(self): + return self._idx + + def __str__(self): + return 'KafkaBytes(%d)' % len(self) + + def __repr__(self): + return str(self) diff --git a/testbed/dpkp__kafka-python/kafka/protocol/message.py b/testbed/dpkp__kafka-python/kafka/protocol/message.py new file mode 100644 index 0000000000000000000000000000000000000000..4c5c031b83e614148ebe1f3afc236107c5f1564e --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/message.py @@ -0,0 +1,216 @@ +from __future__ import absolute_import + +import io +import time + +from kafka.codec import (has_gzip, has_snappy, has_lz4, has_zstd, + gzip_decode, snappy_decode, zstd_decode, + lz4_decode, lz4_decode_old_kafka) +from kafka.protocol.frame import KafkaBytes +from kafka.protocol.struct import Struct +from kafka.protocol.types import ( + Int8, Int32, Int64, Bytes, Schema, AbstractType +) +from kafka.util import crc32, WeakMethod + + +class Message(Struct): + SCHEMAS = [ + Schema( + ('crc', Int32), + ('magic', Int8), + ('attributes', Int8), + ('key', Bytes), + ('value', Bytes)), + Schema( + ('crc', Int32), + ('magic', Int8), + ('attributes', Int8), + ('timestamp', Int64), + ('key', Bytes), + ('value', Bytes)), + ] + SCHEMA = SCHEMAS[1] + CODEC_MASK = 0x07 + CODEC_GZIP = 0x01 + CODEC_SNAPPY = 0x02 + CODEC_LZ4 = 0x03 + CODEC_ZSTD = 0x04 + TIMESTAMP_TYPE_MASK = 0x08 + HEADER_SIZE = 22 # crc(4), magic(1), attributes(1), timestamp(8), key+value size(4*2) + + def __init__(self, value, key=None, magic=0, attributes=0, crc=0, + timestamp=None): + assert value is None or isinstance(value, bytes), 'value must be bytes' + assert key is None or isinstance(key, bytes), 'key must be bytes' + assert magic > 0 or timestamp is None, 'timestamp not supported in v0' + + # Default timestamp to now for v1 messages + if magic > 0 and timestamp is None: + timestamp = int(time.time() * 1000) + self.timestamp = timestamp + self.crc = crc + self._validated_crc = None + self.magic = magic + self.attributes = attributes + self.key = key + self.value = value + self.encode = WeakMethod(self._encode_self) + + @property + def timestamp_type(self): + """0 for CreateTime; 1 for LogAppendTime; None if unsupported. + + Value is determined by broker; produced messages should always set to 0 + Requires Kafka >= 0.10 / message version >= 1 + """ + if self.magic == 0: + return None + elif self.attributes & self.TIMESTAMP_TYPE_MASK: + return 1 + else: + return 0 + + def _encode_self(self, recalc_crc=True): + version = self.magic + if version == 1: + fields = (self.crc, self.magic, self.attributes, self.timestamp, self.key, self.value) + elif version == 0: + fields = (self.crc, self.magic, self.attributes, self.key, self.value) + else: + raise ValueError('Unrecognized message version: %s' % (version,)) + message = Message.SCHEMAS[version].encode(fields) + if not recalc_crc: + return message + self.crc = crc32(message[4:]) + crc_field = self.SCHEMAS[version].fields[0] + return crc_field.encode(self.crc) + message[4:] + + @classmethod + def decode(cls, data): + _validated_crc = None + if isinstance(data, bytes): + _validated_crc = crc32(data[4:]) + data = io.BytesIO(data) + # Partial decode required to determine message version + base_fields = cls.SCHEMAS[0].fields[0:3] + crc, magic, attributes = [field.decode(data) for field in base_fields] + remaining = cls.SCHEMAS[magic].fields[3:] + fields = [field.decode(data) for field in remaining] + if magic == 1: + timestamp = fields[0] + else: + timestamp = None + msg = cls(fields[-1], key=fields[-2], + magic=magic, attributes=attributes, crc=crc, + timestamp=timestamp) + msg._validated_crc = _validated_crc + return msg + + def validate_crc(self): + if self._validated_crc is None: + raw_msg = self._encode_self(recalc_crc=False) + self._validated_crc = crc32(raw_msg[4:]) + if self.crc == self._validated_crc: + return True + return False + + def is_compressed(self): + return self.attributes & self.CODEC_MASK != 0 + + def decompress(self): + codec = self.attributes & self.CODEC_MASK + assert codec in (self.CODEC_GZIP, self.CODEC_SNAPPY, self.CODEC_LZ4, self.CODEC_ZSTD) + if codec == self.CODEC_GZIP: + assert has_gzip(), 'Gzip decompression unsupported' + raw_bytes = gzip_decode(self.value) + elif codec == self.CODEC_SNAPPY: + assert has_snappy(), 'Snappy decompression unsupported' + raw_bytes = snappy_decode(self.value) + elif codec == self.CODEC_LZ4: + assert has_lz4(), 'LZ4 decompression unsupported' + if self.magic == 0: + raw_bytes = lz4_decode_old_kafka(self.value) + else: + raw_bytes = lz4_decode(self.value) + elif codec == self.CODEC_ZSTD: + assert has_zstd(), "ZSTD decompression unsupported" + raw_bytes = zstd_decode(self.value) + else: + raise Exception('This should be impossible') + + return MessageSet.decode(raw_bytes, bytes_to_read=len(raw_bytes)) + + def __hash__(self): + return hash(self._encode_self(recalc_crc=False)) + + +class PartialMessage(bytes): + def __repr__(self): + return 'PartialMessage(%s)' % (self,) + + +class MessageSet(AbstractType): + ITEM = Schema( + ('offset', Int64), + ('message', Bytes) + ) + HEADER_SIZE = 12 # offset + message_size + + @classmethod + def encode(cls, items, prepend_size=True): + # RecordAccumulator encodes messagesets internally + if isinstance(items, (io.BytesIO, KafkaBytes)): + size = Int32.decode(items) + if prepend_size: + # rewind and return all the bytes + items.seek(items.tell() - 4) + size += 4 + return items.read(size) + + encoded_values = [] + for (offset, message) in items: + encoded_values.append(Int64.encode(offset)) + encoded_values.append(Bytes.encode(message)) + encoded = b''.join(encoded_values) + if prepend_size: + return Bytes.encode(encoded) + else: + return encoded + + @classmethod + def decode(cls, data, bytes_to_read=None): + """Compressed messages should pass in bytes_to_read (via message size) + otherwise, we decode from data as Int32 + """ + if isinstance(data, bytes): + data = io.BytesIO(data) + if bytes_to_read is None: + bytes_to_read = Int32.decode(data) + + # if FetchRequest max_bytes is smaller than the available message set + # the server returns partial data for the final message + # So create an internal buffer to avoid over-reading + raw = io.BytesIO(data.read(bytes_to_read)) + + items = [] + while bytes_to_read: + try: + offset = Int64.decode(raw) + msg_bytes = Bytes.decode(raw) + bytes_to_read -= 8 + 4 + len(msg_bytes) + items.append((offset, len(msg_bytes), Message.decode(msg_bytes))) + except ValueError: + # PartialMessage to signal that max_bytes may be too small + items.append((None, None, PartialMessage())) + break + return items + + @classmethod + def repr(cls, messages): + if isinstance(messages, (KafkaBytes, io.BytesIO)): + offset = messages.tell() + decoded = cls.decode(messages) + messages.seek(offset) + messages = decoded + return str([cls.ITEM.repr(m) for m in messages]) diff --git a/testbed/dpkp__kafka-python/kafka/protocol/metadata.py b/testbed/dpkp__kafka-python/kafka/protocol/metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..414e5b84a1fea782cadda12a652d674fa2d4f746 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/metadata.py @@ -0,0 +1,200 @@ +from __future__ import absolute_import + +from kafka.protocol.api import Request, Response +from kafka.protocol.types import Array, Boolean, Int16, Int32, Schema, String + + +class MetadataResponse_v0(Response): + API_KEY = 3 + API_VERSION = 0 + SCHEMA = Schema( + ('brokers', Array( + ('node_id', Int32), + ('host', String('utf-8')), + ('port', Int32))), + ('topics', Array( + ('error_code', Int16), + ('topic', String('utf-8')), + ('partitions', Array( + ('error_code', Int16), + ('partition', Int32), + ('leader', Int32), + ('replicas', Array(Int32)), + ('isr', Array(Int32)))))) + ) + + +class MetadataResponse_v1(Response): + API_KEY = 3 + API_VERSION = 1 + SCHEMA = Schema( + ('brokers', Array( + ('node_id', Int32), + ('host', String('utf-8')), + ('port', Int32), + ('rack', String('utf-8')))), + ('controller_id', Int32), + ('topics', Array( + ('error_code', Int16), + ('topic', String('utf-8')), + ('is_internal', Boolean), + ('partitions', Array( + ('error_code', Int16), + ('partition', Int32), + ('leader', Int32), + ('replicas', Array(Int32)), + ('isr', Array(Int32)))))) + ) + + +class MetadataResponse_v2(Response): + API_KEY = 3 + API_VERSION = 2 + SCHEMA = Schema( + ('brokers', Array( + ('node_id', Int32), + ('host', String('utf-8')), + ('port', Int32), + ('rack', String('utf-8')))), + ('cluster_id', String('utf-8')), # <-- Added cluster_id field in v2 + ('controller_id', Int32), + ('topics', Array( + ('error_code', Int16), + ('topic', String('utf-8')), + ('is_internal', Boolean), + ('partitions', Array( + ('error_code', Int16), + ('partition', Int32), + ('leader', Int32), + ('replicas', Array(Int32)), + ('isr', Array(Int32)))))) + ) + + +class MetadataResponse_v3(Response): + API_KEY = 3 + API_VERSION = 3 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('brokers', Array( + ('node_id', Int32), + ('host', String('utf-8')), + ('port', Int32), + ('rack', String('utf-8')))), + ('cluster_id', String('utf-8')), + ('controller_id', Int32), + ('topics', Array( + ('error_code', Int16), + ('topic', String('utf-8')), + ('is_internal', Boolean), + ('partitions', Array( + ('error_code', Int16), + ('partition', Int32), + ('leader', Int32), + ('replicas', Array(Int32)), + ('isr', Array(Int32)))))) + ) + + +class MetadataResponse_v4(Response): + API_KEY = 3 + API_VERSION = 4 + SCHEMA = MetadataResponse_v3.SCHEMA + + +class MetadataResponse_v5(Response): + API_KEY = 3 + API_VERSION = 5 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('brokers', Array( + ('node_id', Int32), + ('host', String('utf-8')), + ('port', Int32), + ('rack', String('utf-8')))), + ('cluster_id', String('utf-8')), + ('controller_id', Int32), + ('topics', Array( + ('error_code', Int16), + ('topic', String('utf-8')), + ('is_internal', Boolean), + ('partitions', Array( + ('error_code', Int16), + ('partition', Int32), + ('leader', Int32), + ('replicas', Array(Int32)), + ('isr', Array(Int32)), + ('offline_replicas', Array(Int32)))))) + ) + + +class MetadataRequest_v0(Request): + API_KEY = 3 + API_VERSION = 0 + RESPONSE_TYPE = MetadataResponse_v0 + SCHEMA = Schema( + ('topics', Array(String('utf-8'))) + ) + ALL_TOPICS = None # Empty Array (len 0) for topics returns all topics + + +class MetadataRequest_v1(Request): + API_KEY = 3 + API_VERSION = 1 + RESPONSE_TYPE = MetadataResponse_v1 + SCHEMA = MetadataRequest_v0.SCHEMA + ALL_TOPICS = -1 # Null Array (len -1) for topics returns all topics + NO_TOPICS = None # Empty array (len 0) for topics returns no topics + + +class MetadataRequest_v2(Request): + API_KEY = 3 + API_VERSION = 2 + RESPONSE_TYPE = MetadataResponse_v2 + SCHEMA = MetadataRequest_v1.SCHEMA + ALL_TOPICS = -1 # Null Array (len -1) for topics returns all topics + NO_TOPICS = None # Empty array (len 0) for topics returns no topics + + +class MetadataRequest_v3(Request): + API_KEY = 3 + API_VERSION = 3 + RESPONSE_TYPE = MetadataResponse_v3 + SCHEMA = MetadataRequest_v1.SCHEMA + ALL_TOPICS = -1 # Null Array (len -1) for topics returns all topics + NO_TOPICS = None # Empty array (len 0) for topics returns no topics + + +class MetadataRequest_v4(Request): + API_KEY = 3 + API_VERSION = 4 + RESPONSE_TYPE = MetadataResponse_v4 + SCHEMA = Schema( + ('topics', Array(String('utf-8'))), + ('allow_auto_topic_creation', Boolean) + ) + ALL_TOPICS = -1 # Null Array (len -1) for topics returns all topics + NO_TOPICS = None # Empty array (len 0) for topics returns no topics + + +class MetadataRequest_v5(Request): + """ + The v5 metadata request is the same as v4. + An additional field for offline_replicas has been added to the v5 metadata response + """ + API_KEY = 3 + API_VERSION = 5 + RESPONSE_TYPE = MetadataResponse_v5 + SCHEMA = MetadataRequest_v4.SCHEMA + ALL_TOPICS = -1 # Null Array (len -1) for topics returns all topics + NO_TOPICS = None # Empty array (len 0) for topics returns no topics + + +MetadataRequest = [ + MetadataRequest_v0, MetadataRequest_v1, MetadataRequest_v2, + MetadataRequest_v3, MetadataRequest_v4, MetadataRequest_v5 +] +MetadataResponse = [ + MetadataResponse_v0, MetadataResponse_v1, MetadataResponse_v2, + MetadataResponse_v3, MetadataResponse_v4, MetadataResponse_v5 +] diff --git a/testbed/dpkp__kafka-python/kafka/protocol/offset.py b/testbed/dpkp__kafka-python/kafka/protocol/offset.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed382b0da6dfcd1d849daced3fdf73100dfb187 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/offset.py @@ -0,0 +1,194 @@ +from __future__ import absolute_import + +from kafka.protocol.api import Request, Response +from kafka.protocol.types import Array, Int8, Int16, Int32, Int64, Schema, String + +UNKNOWN_OFFSET = -1 + + +class OffsetResetStrategy(object): + LATEST = -1 + EARLIEST = -2 + NONE = 0 + + +class OffsetResponse_v0(Response): + API_KEY = 2 + API_VERSION = 0 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('offsets', Array(Int64)))))) + ) + +class OffsetResponse_v1(Response): + API_KEY = 2 + API_VERSION = 1 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('timestamp', Int64), + ('offset', Int64))))) + ) + + +class OffsetResponse_v2(Response): + API_KEY = 2 + API_VERSION = 2 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('timestamp', Int64), + ('offset', Int64))))) + ) + + +class OffsetResponse_v3(Response): + """ + on quota violation, brokers send out responses before throttling + """ + API_KEY = 2 + API_VERSION = 3 + SCHEMA = OffsetResponse_v2.SCHEMA + + +class OffsetResponse_v4(Response): + """ + Add leader_epoch to response + """ + API_KEY = 2 + API_VERSION = 4 + SCHEMA = Schema( + ('throttle_time_ms', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('timestamp', Int64), + ('offset', Int64), + ('leader_epoch', Int32))))) + ) + + +class OffsetResponse_v5(Response): + """ + adds a new error code, OFFSET_NOT_AVAILABLE + """ + API_KEY = 2 + API_VERSION = 5 + SCHEMA = OffsetResponse_v4.SCHEMA + + +class OffsetRequest_v0(Request): + API_KEY = 2 + API_VERSION = 0 + RESPONSE_TYPE = OffsetResponse_v0 + SCHEMA = Schema( + ('replica_id', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('timestamp', Int64), + ('max_offsets', Int32))))) + ) + DEFAULTS = { + 'replica_id': -1 + } + +class OffsetRequest_v1(Request): + API_KEY = 2 + API_VERSION = 1 + RESPONSE_TYPE = OffsetResponse_v1 + SCHEMA = Schema( + ('replica_id', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('timestamp', Int64))))) + ) + DEFAULTS = { + 'replica_id': -1 + } + + +class OffsetRequest_v2(Request): + API_KEY = 2 + API_VERSION = 2 + RESPONSE_TYPE = OffsetResponse_v2 + SCHEMA = Schema( + ('replica_id', Int32), + ('isolation_level', Int8), # <- added isolation_level + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('timestamp', Int64))))) + ) + DEFAULTS = { + 'replica_id': -1 + } + + +class OffsetRequest_v3(Request): + API_KEY = 2 + API_VERSION = 3 + RESPONSE_TYPE = OffsetResponse_v3 + SCHEMA = OffsetRequest_v2.SCHEMA + DEFAULTS = { + 'replica_id': -1 + } + + +class OffsetRequest_v4(Request): + """ + Add current_leader_epoch to request + """ + API_KEY = 2 + API_VERSION = 4 + RESPONSE_TYPE = OffsetResponse_v4 + SCHEMA = Schema( + ('replica_id', Int32), + ('isolation_level', Int8), # <- added isolation_level + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('current_leader_epoch', Int64), + ('timestamp', Int64))))) + ) + DEFAULTS = { + 'replica_id': -1 + } + + +class OffsetRequest_v5(Request): + API_KEY = 2 + API_VERSION = 5 + RESPONSE_TYPE = OffsetResponse_v5 + SCHEMA = OffsetRequest_v4.SCHEMA + DEFAULTS = { + 'replica_id': -1 + } + + +OffsetRequest = [ + OffsetRequest_v0, OffsetRequest_v1, OffsetRequest_v2, + OffsetRequest_v3, OffsetRequest_v4, OffsetRequest_v5, +] +OffsetResponse = [ + OffsetResponse_v0, OffsetResponse_v1, OffsetResponse_v2, + OffsetResponse_v3, OffsetResponse_v4, OffsetResponse_v5, +] diff --git a/testbed/dpkp__kafka-python/kafka/protocol/parser.py b/testbed/dpkp__kafka-python/kafka/protocol/parser.py new file mode 100644 index 0000000000000000000000000000000000000000..cfee0466de2d0bdfacf700ea528fef854a8b0013 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/parser.py @@ -0,0 +1,183 @@ +from __future__ import absolute_import + +import collections +import logging + +import kafka.errors as Errors +from kafka.protocol.api import RequestHeader +from kafka.protocol.commit import GroupCoordinatorResponse +from kafka.protocol.frame import KafkaBytes +from kafka.protocol.types import Int32 +from kafka.version import __version__ + +log = logging.getLogger(__name__) + + +class KafkaProtocol(object): + """Manage the kafka network protocol + + Use an instance of KafkaProtocol to manage bytes send/recv'd + from a network socket to a broker. + + Arguments: + client_id (str): identifier string to be included in each request + api_version (tuple): Optional tuple to specify api_version to use. + Currently only used to check for 0.8.2 protocol quirks, but + may be used for more in the future. + """ + def __init__(self, client_id=None, api_version=None): + if client_id is None: + client_id = self._gen_client_id() + self._client_id = client_id + self._api_version = api_version + self._correlation_id = 0 + self._header = KafkaBytes(4) + self._rbuffer = None + self._receiving = False + self.in_flight_requests = collections.deque() + self.bytes_to_send = [] + + def _next_correlation_id(self): + self._correlation_id = (self._correlation_id + 1) % 2**31 + return self._correlation_id + + def _gen_client_id(self): + return 'kafka-python' + __version__ + + def send_request(self, request, correlation_id=None): + """Encode and queue a kafka api request for sending. + + Arguments: + request (object): An un-encoded kafka request. + correlation_id (int, optional): Optionally specify an ID to + correlate requests with responses. If not provided, an ID will + be generated automatically. + + Returns: + correlation_id + """ + log.debug('Sending request %s', request) + if correlation_id is None: + correlation_id = self._next_correlation_id() + header = RequestHeader(request, + correlation_id=correlation_id, + client_id=self._client_id) + message = b''.join([header.encode(), request.encode()]) + size = Int32.encode(len(message)) + data = size + message + self.bytes_to_send.append(data) + if request.expect_response(): + ifr = (correlation_id, request) + self.in_flight_requests.append(ifr) + return correlation_id + + def send_bytes(self): + """Retrieve all pending bytes to send on the network""" + data = b''.join(self.bytes_to_send) + self.bytes_to_send = [] + return data + + def receive_bytes(self, data): + """Process bytes received from the network. + + Arguments: + data (bytes): any length bytes received from a network connection + to a kafka broker. + + Returns: + responses (list of (correlation_id, response)): any/all completed + responses, decoded from bytes to python objects. + + Raises: + KafkaProtocolError: if the bytes received could not be decoded. + CorrelationIdError: if the response does not match the request + correlation id. + """ + i = 0 + n = len(data) + responses = [] + while i < n: + + # Not receiving is the state of reading the payload header + if not self._receiving: + bytes_to_read = min(4 - self._header.tell(), n - i) + self._header.write(data[i:i+bytes_to_read]) + i += bytes_to_read + + if self._header.tell() == 4: + self._header.seek(0) + nbytes = Int32.decode(self._header) + # reset buffer and switch state to receiving payload bytes + self._rbuffer = KafkaBytes(nbytes) + self._receiving = True + elif self._header.tell() > 4: + raise Errors.KafkaError('this should not happen - are you threading?') + + if self._receiving: + total_bytes = len(self._rbuffer) + staged_bytes = self._rbuffer.tell() + bytes_to_read = min(total_bytes - staged_bytes, n - i) + self._rbuffer.write(data[i:i+bytes_to_read]) + i += bytes_to_read + + staged_bytes = self._rbuffer.tell() + if staged_bytes > total_bytes: + raise Errors.KafkaError('Receive buffer has more bytes than expected?') + + if staged_bytes != total_bytes: + break + + self._receiving = False + self._rbuffer.seek(0) + resp = self._process_response(self._rbuffer) + responses.append(resp) + self._reset_buffer() + return responses + + def _process_response(self, read_buffer): + recv_correlation_id = Int32.decode(read_buffer) + log.debug('Received correlation id: %d', recv_correlation_id) + + if not self.in_flight_requests: + raise Errors.CorrelationIdError( + 'No in-flight-request found for server response' + ' with correlation ID %d' + % (recv_correlation_id,)) + + (correlation_id, request) = self.in_flight_requests.popleft() + + # 0.8.2 quirk + if (recv_correlation_id == 0 and + correlation_id != 0 and + request.RESPONSE_TYPE is GroupCoordinatorResponse[0] and + (self._api_version == (0, 8, 2) or self._api_version is None)): + log.warning('Kafka 0.8.2 quirk -- GroupCoordinatorResponse' + ' Correlation ID does not match request. This' + ' should go away once at least one topic has been' + ' initialized on the broker.') + + elif correlation_id != recv_correlation_id: + # return or raise? + raise Errors.CorrelationIdError( + 'Correlation IDs do not match: sent %d, recv %d' + % (correlation_id, recv_correlation_id)) + + # decode response + log.debug('Processing response %s', request.RESPONSE_TYPE.__name__) + try: + response = request.RESPONSE_TYPE.decode(read_buffer) + except ValueError: + read_buffer.seek(0) + buf = read_buffer.read() + log.error('Response %d [ResponseType: %s Request: %s]:' + ' Unable to decode %d-byte buffer: %r', + correlation_id, request.RESPONSE_TYPE, + request, len(buf), buf) + raise Errors.KafkaProtocolError('Unable to decode response') + + return (correlation_id, response) + + def _reset_buffer(self): + self._receiving = False + self._header.seek(0) + self._rbuffer = None diff --git a/testbed/dpkp__kafka-python/kafka/protocol/pickle.py b/testbed/dpkp__kafka-python/kafka/protocol/pickle.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e5fa74ff3c1633bb05094a853b6f69609af2bc --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/pickle.py @@ -0,0 +1,35 @@ +from __future__ import absolute_import + +try: + import copyreg # pylint: disable=import-error +except ImportError: + import copy_reg as copyreg # pylint: disable=import-error + +import types + + +def _pickle_method(method): + try: + func_name = method.__func__.__name__ + obj = method.__self__ + cls = method.__self__.__class__ + except AttributeError: + func_name = method.im_func.__name__ + obj = method.im_self + cls = method.im_class + + return _unpickle_method, (func_name, obj, cls) + + +def _unpickle_method(func_name, obj, cls): + for cls in cls.mro(): + try: + func = cls.__dict__[func_name] + except KeyError: + pass + else: + break + return func.__get__(obj, cls) + +# https://bytes.com/topic/python/answers/552476-why-cant-you-pickle-instancemethods +copyreg.pickle(types.MethodType, _pickle_method, _unpickle_method) diff --git a/testbed/dpkp__kafka-python/kafka/protocol/produce.py b/testbed/dpkp__kafka-python/kafka/protocol/produce.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3f6bf5560e7fd89294cac37b3f12059ce235c9 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/produce.py @@ -0,0 +1,232 @@ +from __future__ import absolute_import + +from kafka.protocol.api import Request, Response +from kafka.protocol.types import Int16, Int32, Int64, String, Array, Schema, Bytes + + +class ProduceResponse_v0(Response): + API_KEY = 0 + API_VERSION = 0 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('offset', Int64))))) + ) + + +class ProduceResponse_v1(Response): + API_KEY = 0 + API_VERSION = 1 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('offset', Int64))))), + ('throttle_time_ms', Int32) + ) + + +class ProduceResponse_v2(Response): + API_KEY = 0 + API_VERSION = 2 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('offset', Int64), + ('timestamp', Int64))))), + ('throttle_time_ms', Int32) + ) + + +class ProduceResponse_v3(Response): + API_KEY = 0 + API_VERSION = 3 + SCHEMA = ProduceResponse_v2.SCHEMA + + +class ProduceResponse_v4(Response): + """ + The version number is bumped up to indicate that the client supports KafkaStorageException. + The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 3 + """ + API_KEY = 0 + API_VERSION = 4 + SCHEMA = ProduceResponse_v3.SCHEMA + + +class ProduceResponse_v5(Response): + API_KEY = 0 + API_VERSION = 5 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('offset', Int64), + ('timestamp', Int64), + ('log_start_offset', Int64))))), + ('throttle_time_ms', Int32) + ) + + +class ProduceResponse_v6(Response): + """ + The version number is bumped to indicate that on quota violation brokers send out responses before throttling. + """ + API_KEY = 0 + API_VERSION = 6 + SCHEMA = ProduceResponse_v5.SCHEMA + + +class ProduceResponse_v7(Response): + """ + V7 bumped up to indicate ZStandard capability. (see KIP-110) + """ + API_KEY = 0 + API_VERSION = 7 + SCHEMA = ProduceResponse_v6.SCHEMA + + +class ProduceResponse_v8(Response): + """ + V8 bumped up to add two new fields record_errors offset list and error_message + (See KIP-467) + """ + API_KEY = 0 + API_VERSION = 8 + SCHEMA = Schema( + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('error_code', Int16), + ('offset', Int64), + ('timestamp', Int64), + ('log_start_offset', Int64)), + ('record_errors', (Array( + ('batch_index', Int32), + ('batch_index_error_message', String('utf-8')) + ))), + ('error_message', String('utf-8')) + ))), + ('throttle_time_ms', Int32) + ) + + +class ProduceRequest(Request): + API_KEY = 0 + + def expect_response(self): + if self.required_acks == 0: # pylint: disable=no-member + return False + return True + + +class ProduceRequest_v0(ProduceRequest): + API_VERSION = 0 + RESPONSE_TYPE = ProduceResponse_v0 + SCHEMA = Schema( + ('required_acks', Int16), + ('timeout', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('messages', Bytes))))) + ) + + +class ProduceRequest_v1(ProduceRequest): + API_VERSION = 1 + RESPONSE_TYPE = ProduceResponse_v1 + SCHEMA = ProduceRequest_v0.SCHEMA + + +class ProduceRequest_v2(ProduceRequest): + API_VERSION = 2 + RESPONSE_TYPE = ProduceResponse_v2 + SCHEMA = ProduceRequest_v1.SCHEMA + + +class ProduceRequest_v3(ProduceRequest): + API_VERSION = 3 + RESPONSE_TYPE = ProduceResponse_v3 + SCHEMA = Schema( + ('transactional_id', String('utf-8')), + ('required_acks', Int16), + ('timeout', Int32), + ('topics', Array( + ('topic', String('utf-8')), + ('partitions', Array( + ('partition', Int32), + ('messages', Bytes))))) + ) + + +class ProduceRequest_v4(ProduceRequest): + """ + The version number is bumped up to indicate that the client supports KafkaStorageException. + The KafkaStorageException will be translated to NotLeaderForPartitionException in the response if version <= 3 + """ + API_VERSION = 4 + RESPONSE_TYPE = ProduceResponse_v4 + SCHEMA = ProduceRequest_v3.SCHEMA + + +class ProduceRequest_v5(ProduceRequest): + """ + Same as v4. The version number is bumped since the v5 response includes an additional + partition level field: the log_start_offset. + """ + API_VERSION = 5 + RESPONSE_TYPE = ProduceResponse_v5 + SCHEMA = ProduceRequest_v4.SCHEMA + + +class ProduceRequest_v6(ProduceRequest): + """ + The version number is bumped to indicate that on quota violation brokers send out responses before throttling. + """ + API_VERSION = 6 + RESPONSE_TYPE = ProduceResponse_v6 + SCHEMA = ProduceRequest_v5.SCHEMA + + +class ProduceRequest_v7(ProduceRequest): + """ + V7 bumped up to indicate ZStandard capability. (see KIP-110) + """ + API_VERSION = 7 + RESPONSE_TYPE = ProduceResponse_v7 + SCHEMA = ProduceRequest_v6.SCHEMA + + +class ProduceRequest_v8(ProduceRequest): + """ + V8 bumped up to add two new fields record_errors offset list and error_message to PartitionResponse + (See KIP-467) + """ + API_VERSION = 8 + RESPONSE_TYPE = ProduceResponse_v8 + SCHEMA = ProduceRequest_v7.SCHEMA + + +ProduceRequest = [ + ProduceRequest_v0, ProduceRequest_v1, ProduceRequest_v2, + ProduceRequest_v3, ProduceRequest_v4, ProduceRequest_v5, + ProduceRequest_v6, ProduceRequest_v7, ProduceRequest_v8, +] +ProduceResponse = [ + ProduceResponse_v0, ProduceResponse_v1, ProduceResponse_v2, + ProduceResponse_v3, ProduceResponse_v4, ProduceResponse_v5, + ProduceResponse_v6, ProduceResponse_v7, ProduceResponse_v8, +] diff --git a/testbed/dpkp__kafka-python/kafka/protocol/struct.py b/testbed/dpkp__kafka-python/kafka/protocol/struct.py new file mode 100644 index 0000000000000000000000000000000000000000..e9da6e6c1c8aa7505e2dccb0473335da2979bab2 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/struct.py @@ -0,0 +1,72 @@ +from __future__ import absolute_import + +from io import BytesIO + +from kafka.protocol.abstract import AbstractType +from kafka.protocol.types import Schema + +from kafka.util import WeakMethod + + +class Struct(AbstractType): + SCHEMA = Schema() + + def __init__(self, *args, **kwargs): + if len(args) == len(self.SCHEMA.fields): + for i, name in enumerate(self.SCHEMA.names): + self.__dict__[name] = args[i] + elif len(args) > 0: + raise ValueError('Args must be empty or mirror schema') + else: + for name in self.SCHEMA.names: + self.__dict__[name] = kwargs.pop(name, None) + if kwargs: + raise ValueError('Keyword(s) not in schema %s: %s' + % (list(self.SCHEMA.names), + ', '.join(kwargs.keys()))) + + # overloading encode() to support both class and instance + # Without WeakMethod() this creates circular ref, which + # causes instances to "leak" to garbage + self.encode = WeakMethod(self._encode_self) + + + @classmethod + def encode(cls, item): # pylint: disable=E0202 + bits = [] + for i, field in enumerate(cls.SCHEMA.fields): + bits.append(field.encode(item[i])) + return b''.join(bits) + + def _encode_self(self): + return self.SCHEMA.encode( + [self.__dict__[name] for name in self.SCHEMA.names] + ) + + @classmethod + def decode(cls, data): + if isinstance(data, bytes): + data = BytesIO(data) + return cls(*[field.decode(data) for field in cls.SCHEMA.fields]) + + def get_item(self, name): + if name not in self.SCHEMA.names: + raise KeyError("%s is not in the schema" % name) + return self.__dict__[name] + + def __repr__(self): + key_vals = [] + for name, field in zip(self.SCHEMA.names, self.SCHEMA.fields): + key_vals.append('%s=%s' % (name, field.repr(self.__dict__[name]))) + return self.__class__.__name__ + '(' + ', '.join(key_vals) + ')' + + def __hash__(self): + return hash(self.encode()) + + def __eq__(self, other): + if self.SCHEMA != other.SCHEMA: + return False + for attr in self.SCHEMA.names: + if self.__dict__[attr] != other.__dict__[attr]: + return False + return True diff --git a/testbed/dpkp__kafka-python/kafka/protocol/types.py b/testbed/dpkp__kafka-python/kafka/protocol/types.py new file mode 100644 index 0000000000000000000000000000000000000000..2fde24fcc4deae1a25fb627ad65b945afb827c92 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/protocol/types.py @@ -0,0 +1,212 @@ +from __future__ import absolute_import + +import struct +from struct import error + +from kafka.protocol.abstract import AbstractType + + +def _pack(f, value): + try: + return f(value) + except error as e: + raise ValueError("Error encountered when attempting to convert value: " + "{!r} to struct format: '{}', hit error: {}" + .format(value, f, e)) + + +def _unpack(f, data): + try: + (value,) = f(data) + return value + except error as e: + raise ValueError("Error encountered when attempting to convert value: " + "{!r} to struct format: '{}', hit error: {}" + .format(data, f, e)) + + +class Int8(AbstractType): + _pack = struct.Struct('>b').pack + _unpack = struct.Struct('>b').unpack + + @classmethod + def encode(cls, value): + return _pack(cls._pack, value) + + @classmethod + def decode(cls, data): + return _unpack(cls._unpack, data.read(1)) + + +class Int16(AbstractType): + _pack = struct.Struct('>h').pack + _unpack = struct.Struct('>h').unpack + + @classmethod + def encode(cls, value): + return _pack(cls._pack, value) + + @classmethod + def decode(cls, data): + return _unpack(cls._unpack, data.read(2)) + + +class Int32(AbstractType): + _pack = struct.Struct('>i').pack + _unpack = struct.Struct('>i').unpack + + @classmethod + def encode(cls, value): + return _pack(cls._pack, value) + + @classmethod + def decode(cls, data): + return _unpack(cls._unpack, data.read(4)) + + +class Int64(AbstractType): + _pack = struct.Struct('>q').pack + _unpack = struct.Struct('>q').unpack + + @classmethod + def encode(cls, value): + return _pack(cls._pack, value) + + @classmethod + def decode(cls, data): + return _unpack(cls._unpack, data.read(8)) + + +class Float64(AbstractType): + _pack = struct.Struct('>d').pack + _unpack = struct.Struct('>d').unpack + + @classmethod + def encode(cls, value): + return _pack(cls._pack, value) + + @classmethod + def decode(cls, data): + return _unpack(cls._unpack, data.read(8)) + + +class String(AbstractType): + def __init__(self, encoding='utf-8'): + self.encoding = encoding + + def encode(self, value): + if value is None: + return Int16.encode(-1) + value = str(value).encode(self.encoding) + return Int16.encode(len(value)) + value + + def decode(self, data): + length = Int16.decode(data) + if length < 0: + return None + value = data.read(length) + if len(value) != length: + raise ValueError('Buffer underrun decoding string') + return value.decode(self.encoding) + + +class Bytes(AbstractType): + @classmethod + def encode(cls, value): + if value is None: + return Int32.encode(-1) + else: + return Int32.encode(len(value)) + value + + @classmethod + def decode(cls, data): + length = Int32.decode(data) + if length < 0: + return None + value = data.read(length) + if len(value) != length: + raise ValueError('Buffer underrun decoding Bytes') + return value + + @classmethod + def repr(cls, value): + return repr(value[:100] + b'...' if value is not None and len(value) > 100 else value) + + +class Boolean(AbstractType): + _pack = struct.Struct('>?').pack + _unpack = struct.Struct('>?').unpack + + @classmethod + def encode(cls, value): + return _pack(cls._pack, value) + + @classmethod + def decode(cls, data): + return _unpack(cls._unpack, data.read(1)) + + +class Schema(AbstractType): + def __init__(self, *fields): + if fields: + self.names, self.fields = zip(*fields) + else: + self.names, self.fields = (), () + + def encode(self, item): + if len(item) != len(self.fields): + raise ValueError('Item field count does not match Schema') + return b''.join([ + field.encode(item[i]) + for i, field in enumerate(self.fields) + ]) + + def decode(self, data): + return tuple([field.decode(data) for field in self.fields]) + + def __len__(self): + return len(self.fields) + + def repr(self, value): + key_vals = [] + try: + for i in range(len(self)): + try: + field_val = getattr(value, self.names[i]) + except AttributeError: + field_val = value[i] + key_vals.append('%s=%s' % (self.names[i], self.fields[i].repr(field_val))) + return '(' + ', '.join(key_vals) + ')' + except Exception: + return repr(value) + + +class Array(AbstractType): + def __init__(self, *array_of): + if len(array_of) > 1: + self.array_of = Schema(*array_of) + elif len(array_of) == 1 and (isinstance(array_of[0], AbstractType) or + issubclass(array_of[0], AbstractType)): + self.array_of = array_of[0] + else: + raise ValueError('Array instantiated with no array_of type') + + def encode(self, items): + if items is None: + return Int32.encode(-1) + encoded_items = [self.array_of.encode(item) for item in items] + return b''.join( + [Int32.encode(len(encoded_items))] + + encoded_items + ) + + def decode(self, data): + length = Int32.decode(data) + if length == -1: + return None + return [self.array_of.decode(data) for _ in range(length)] + + def repr(self, list_of_items): + if list_of_items is None: + return 'NULL' + return '[' + ', '.join([self.array_of.repr(item) for item in list_of_items]) + ']' diff --git a/testbed/dpkp__kafka-python/kafka/record/README b/testbed/dpkp__kafka-python/kafka/record/README new file mode 100644 index 0000000000000000000000000000000000000000..e4454554ca93faef6859310da0a3df7ef2c29819 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/README @@ -0,0 +1,8 @@ +Module structured mostly based on +kafka/clients/src/main/java/org/apache/kafka/common/record/ module of Java +Client. + +See abc.py for abstract declarations. `ABCRecords` is used as a facade to hide +version differences. `ABCRecordBatch` subclasses will implement actual parsers +for different versions (v0/v1 as LegacyBatch and v2 as DefaultBatch. Names +taken from Java). diff --git a/testbed/dpkp__kafka-python/kafka/record/__init__.py b/testbed/dpkp__kafka-python/kafka/record/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..93936df48e0f6d7fc0ef06a650db91b57cc0cf80 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/__init__.py @@ -0,0 +1,3 @@ +from kafka.record.memory_records import MemoryRecords, MemoryRecordsBuilder + +__all__ = ["MemoryRecords", "MemoryRecordsBuilder"] diff --git a/testbed/dpkp__kafka-python/kafka/record/_crc32c.py b/testbed/dpkp__kafka-python/kafka/record/_crc32c.py new file mode 100644 index 0000000000000000000000000000000000000000..ecff48f5e81ffee51d602dd058cb44434b70d699 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/_crc32c.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python +# +# Taken from https://cloud.google.com/appengine/docs/standard/python/refdocs/\ +# modules/google/appengine/api/files/crc32c?hl=ru +# +# Copyright 2007 Google Inc. +# +# 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. +# +"""Implementation of CRC-32C checksumming as in rfc3720 section B.4. +See https://en.wikipedia.org/wiki/Cyclic_redundancy_check for details on CRC-32C +This code is a manual python translation of c code generated by +pycrc 0.7.1 (https://pycrc.org/). Command line used: +'./pycrc.py --model=crc-32c --generate c --algorithm=table-driven' +""" + +import array + +CRC_TABLE = ( + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, + 0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb, + 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, + 0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b, + 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, + 0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b, + 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, + 0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5, + 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, + 0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a, + 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, + 0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48, + 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, + 0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198, + 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, + 0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8, + 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, + 0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789, + 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, + 0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9, + 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, + 0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829, + 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, + 0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043, + 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, + 0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc, + 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, + 0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652, + 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, + 0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982, + 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, + 0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2, + 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, + 0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f, + 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, + 0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f, + 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, + 0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f, + 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, + 0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321, + 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, + 0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e, + 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, +) + +CRC_INIT = 0 +_MASK = 0xFFFFFFFF + + +def crc_update(crc, data): + """Update CRC-32C checksum with data. + Args: + crc: 32-bit checksum to update as long. + data: byte array, string or iterable over bytes. + Returns: + 32-bit updated CRC-32C as long. + """ + if type(data) != array.array or data.itemsize != 1: + buf = array.array("B", data) + else: + buf = data + crc = crc ^ _MASK + for b in buf: + table_index = (crc ^ b) & 0xff + crc = (CRC_TABLE[table_index] ^ (crc >> 8)) & _MASK + return crc ^ _MASK + + +def crc_finalize(crc): + """Finalize CRC-32C checksum. + This function should be called as last step of crc calculation. + Args: + crc: 32-bit checksum as long. + Returns: + finalized 32-bit checksum as long + """ + return crc & _MASK + + +def crc(data): + """Compute CRC-32C checksum of the data. + Args: + data: byte array, string or iterable over bytes. + Returns: + 32-bit CRC-32C checksum of data as long. + """ + return crc_finalize(crc_update(CRC_INIT, data)) + + +if __name__ == "__main__": + import sys + # TODO remove the pylint disable once pylint fixes + # https://github.com/PyCQA/pylint/issues/2571 + data = sys.stdin.read() # pylint: disable=assignment-from-no-return + print(hex(crc(data))) diff --git a/testbed/dpkp__kafka-python/kafka/record/abc.py b/testbed/dpkp__kafka-python/kafka/record/abc.py new file mode 100644 index 0000000000000000000000000000000000000000..d5c172aaa5d9339006deaa8bd9164accf0183c18 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/abc.py @@ -0,0 +1,124 @@ +from __future__ import absolute_import +import abc + + +class ABCRecord(object): + __metaclass__ = abc.ABCMeta + __slots__ = () + + @abc.abstractproperty + def offset(self): + """ Absolute offset of record + """ + + @abc.abstractproperty + def timestamp(self): + """ Epoch milliseconds + """ + + @abc.abstractproperty + def timestamp_type(self): + """ CREATE_TIME(0) or APPEND_TIME(1) + """ + + @abc.abstractproperty + def key(self): + """ Bytes key or None + """ + + @abc.abstractproperty + def value(self): + """ Bytes value or None + """ + + @abc.abstractproperty + def checksum(self): + """ Prior to v2 format CRC was contained in every message. This will + be the checksum for v0 and v1 and None for v2 and above. + """ + + @abc.abstractproperty + def headers(self): + """ If supported by version list of key-value tuples, or empty list if + not supported by format. + """ + + +class ABCRecordBatchBuilder(object): + __metaclass__ = abc.ABCMeta + __slots__ = () + + @abc.abstractmethod + def append(self, offset, timestamp, key, value, headers=None): + """ Writes record to internal buffer. + + Arguments: + offset (int): Relative offset of record, starting from 0 + timestamp (int or None): Timestamp in milliseconds since beginning + of the epoch (midnight Jan 1, 1970 (UTC)). If omitted, will be + set to current time. + key (bytes or None): Key of the record + value (bytes or None): Value of the record + headers (List[Tuple[str, bytes]]): Headers of the record. Header + keys can not be ``None``. + + Returns: + (bytes, int): Checksum of the written record (or None for v2 and + above) and size of the written record. + """ + + @abc.abstractmethod + def size_in_bytes(self, offset, timestamp, key, value, headers): + """ Return the expected size change on buffer (uncompressed) if we add + this message. This will account for varint size changes and give a + reliable size. + """ + + @abc.abstractmethod + def build(self): + """ Close for append, compress if needed, write size and header and + return a ready to send buffer object. + + Return: + bytearray: finished batch, ready to send. + """ + + +class ABCRecordBatch(object): + """ For v2 incapsulates a RecordBatch, for v0/v1 a single (maybe + compressed) message. + """ + __metaclass__ = abc.ABCMeta + __slots__ = () + + @abc.abstractmethod + def __iter__(self): + """ Return iterator over records (ABCRecord instances). Will decompress + if needed. + """ + + +class ABCRecords(object): + __metaclass__ = abc.ABCMeta + __slots__ = () + + @abc.abstractmethod + def __init__(self, buffer): + """ Initialize with bytes-like object conforming to the buffer + interface (ie. bytes, bytearray, memoryview etc.). + """ + + @abc.abstractmethod + def size_in_bytes(self): + """ Returns the size of inner buffer. + """ + + @abc.abstractmethod + def next_batch(self): + """ Return next batch of records (ABCRecordBatch instances). + """ + + @abc.abstractmethod + def has_next(self): + """ True if there are more batches to read, False otherwise. + """ diff --git a/testbed/dpkp__kafka-python/kafka/record/default_records.py b/testbed/dpkp__kafka-python/kafka/record/default_records.py new file mode 100644 index 0000000000000000000000000000000000000000..a098c42a912cad384e7600e37e200b96399962b9 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/default_records.py @@ -0,0 +1,630 @@ +# See: +# https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/\ +# apache/kafka/common/record/DefaultRecordBatch.java +# https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/\ +# apache/kafka/common/record/DefaultRecord.java + +# RecordBatch and Record implementation for magic 2 and above. +# The schema is given below: + +# RecordBatch => +# BaseOffset => Int64 +# Length => Int32 +# PartitionLeaderEpoch => Int32 +# Magic => Int8 +# CRC => Uint32 +# Attributes => Int16 +# LastOffsetDelta => Int32 // also serves as LastSequenceDelta +# FirstTimestamp => Int64 +# MaxTimestamp => Int64 +# ProducerId => Int64 +# ProducerEpoch => Int16 +# BaseSequence => Int32 +# Records => [Record] + +# Record => +# Length => Varint +# Attributes => Int8 +# TimestampDelta => Varlong +# OffsetDelta => Varint +# Key => Bytes +# Value => Bytes +# Headers => [HeaderKey HeaderValue] +# HeaderKey => String +# HeaderValue => Bytes + +# Note that when compression is enabled (see attributes below), the compressed +# record data is serialized directly following the count of the number of +# records. (ie Records => [Record], but without length bytes) + +# The CRC covers the data from the attributes to the end of the batch (i.e. all +# the bytes that follow the CRC). It is located after the magic byte, which +# means that clients must parse the magic byte before deciding how to interpret +# the bytes between the batch length and the magic byte. The partition leader +# epoch field is not included in the CRC computation to avoid the need to +# recompute the CRC when this field is assigned for every batch that is +# received by the broker. The CRC-32C (Castagnoli) polynomial is used for the +# computation. + +# The current RecordBatch attributes are given below: +# +# * Unused (6-15) +# * Control (5) +# * Transactional (4) +# * Timestamp Type (3) +# * Compression Type (0-2) + +import struct +import time +from kafka.record.abc import ABCRecord, ABCRecordBatch, ABCRecordBatchBuilder +from kafka.record.util import ( + decode_varint, encode_varint, calc_crc32c, size_of_varint +) +from kafka.errors import CorruptRecordException, UnsupportedCodecError +from kafka.codec import ( + gzip_encode, snappy_encode, lz4_encode, zstd_encode, + gzip_decode, snappy_decode, lz4_decode, zstd_decode +) +import kafka.codec as codecs + + +class DefaultRecordBase(object): + + __slots__ = () + + HEADER_STRUCT = struct.Struct( + ">q" # BaseOffset => Int64 + "i" # Length => Int32 + "i" # PartitionLeaderEpoch => Int32 + "b" # Magic => Int8 + "I" # CRC => Uint32 + "h" # Attributes => Int16 + "i" # LastOffsetDelta => Int32 // also serves as LastSequenceDelta + "q" # FirstTimestamp => Int64 + "q" # MaxTimestamp => Int64 + "q" # ProducerId => Int64 + "h" # ProducerEpoch => Int16 + "i" # BaseSequence => Int32 + "i" # Records count => Int32 + ) + # Byte offset in HEADER_STRUCT of attributes field. Used to calculate CRC + ATTRIBUTES_OFFSET = struct.calcsize(">qiibI") + CRC_OFFSET = struct.calcsize(">qiib") + AFTER_LEN_OFFSET = struct.calcsize(">qi") + + CODEC_MASK = 0x07 + CODEC_NONE = 0x00 + CODEC_GZIP = 0x01 + CODEC_SNAPPY = 0x02 + CODEC_LZ4 = 0x03 + CODEC_ZSTD = 0x04 + TIMESTAMP_TYPE_MASK = 0x08 + TRANSACTIONAL_MASK = 0x10 + CONTROL_MASK = 0x20 + + LOG_APPEND_TIME = 1 + CREATE_TIME = 0 + + def _assert_has_codec(self, compression_type): + if compression_type == self.CODEC_GZIP: + checker, name = codecs.has_gzip, "gzip" + elif compression_type == self.CODEC_SNAPPY: + checker, name = codecs.has_snappy, "snappy" + elif compression_type == self.CODEC_LZ4: + checker, name = codecs.has_lz4, "lz4" + elif compression_type == self.CODEC_ZSTD: + checker, name = codecs.has_zstd, "zstd" + if not checker(): + raise UnsupportedCodecError( + "Libraries for {} compression codec not found".format(name)) + + +class DefaultRecordBatch(DefaultRecordBase, ABCRecordBatch): + + __slots__ = ("_buffer", "_header_data", "_pos", "_num_records", + "_next_record_index", "_decompressed") + + def __init__(self, buffer): + self._buffer = bytearray(buffer) + self._header_data = self.HEADER_STRUCT.unpack_from(self._buffer) + self._pos = self.HEADER_STRUCT.size + self._num_records = self._header_data[12] + self._next_record_index = 0 + self._decompressed = False + + @property + def base_offset(self): + return self._header_data[0] + + @property + def magic(self): + return self._header_data[3] + + @property + def crc(self): + return self._header_data[4] + + @property + def attributes(self): + return self._header_data[5] + + @property + def last_offset_delta(self): + return self._header_data[6] + + @property + def compression_type(self): + return self.attributes & self.CODEC_MASK + + @property + def timestamp_type(self): + return int(bool(self.attributes & self.TIMESTAMP_TYPE_MASK)) + + @property + def is_transactional(self): + return bool(self.attributes & self.TRANSACTIONAL_MASK) + + @property + def is_control_batch(self): + return bool(self.attributes & self.CONTROL_MASK) + + @property + def first_timestamp(self): + return self._header_data[7] + + @property + def max_timestamp(self): + return self._header_data[8] + + def _maybe_uncompress(self): + if not self._decompressed: + compression_type = self.compression_type + if compression_type != self.CODEC_NONE: + self._assert_has_codec(compression_type) + data = memoryview(self._buffer)[self._pos:] + if compression_type == self.CODEC_GZIP: + uncompressed = gzip_decode(data) + if compression_type == self.CODEC_SNAPPY: + uncompressed = snappy_decode(data.tobytes()) + if compression_type == self.CODEC_LZ4: + uncompressed = lz4_decode(data.tobytes()) + if compression_type == self.CODEC_ZSTD: + uncompressed = zstd_decode(data.tobytes()) + self._buffer = bytearray(uncompressed) + self._pos = 0 + self._decompressed = True + + def _read_msg( + self, + decode_varint=decode_varint): + # Record => + # Length => Varint + # Attributes => Int8 + # TimestampDelta => Varlong + # OffsetDelta => Varint + # Key => Bytes + # Value => Bytes + # Headers => [HeaderKey HeaderValue] + # HeaderKey => String + # HeaderValue => Bytes + + buffer = self._buffer + pos = self._pos + length, pos = decode_varint(buffer, pos) + start_pos = pos + _, pos = decode_varint(buffer, pos) # attrs can be skipped for now + + ts_delta, pos = decode_varint(buffer, pos) + if self.timestamp_type == self.LOG_APPEND_TIME: + timestamp = self.max_timestamp + else: + timestamp = self.first_timestamp + ts_delta + + offset_delta, pos = decode_varint(buffer, pos) + offset = self.base_offset + offset_delta + + key_len, pos = decode_varint(buffer, pos) + if key_len >= 0: + key = bytes(buffer[pos: pos + key_len]) + pos += key_len + else: + key = None + + value_len, pos = decode_varint(buffer, pos) + if value_len >= 0: + value = bytes(buffer[pos: pos + value_len]) + pos += value_len + else: + value = None + + header_count, pos = decode_varint(buffer, pos) + if header_count < 0: + raise CorruptRecordException("Found invalid number of record " + "headers {}".format(header_count)) + headers = [] + while header_count: + # Header key is of type String, that can't be None + h_key_len, pos = decode_varint(buffer, pos) + if h_key_len < 0: + raise CorruptRecordException( + "Invalid negative header key size {}".format(h_key_len)) + h_key = buffer[pos: pos + h_key_len].decode("utf-8") + pos += h_key_len + + # Value is of type NULLABLE_BYTES, so it can be None + h_value_len, pos = decode_varint(buffer, pos) + if h_value_len >= 0: + h_value = bytes(buffer[pos: pos + h_value_len]) + pos += h_value_len + else: + h_value = None + + headers.append((h_key, h_value)) + header_count -= 1 + + # validate whether we have read all header bytes in the current record + if pos - start_pos != length: + raise CorruptRecordException( + "Invalid record size: expected to read {} bytes in record " + "payload, but instead read {}".format(length, pos - start_pos)) + self._pos = pos + + return DefaultRecord( + offset, timestamp, self.timestamp_type, key, value, headers) + + def __iter__(self): + self._maybe_uncompress() + return self + + def __next__(self): + if self._next_record_index >= self._num_records: + if self._pos != len(self._buffer): + raise CorruptRecordException( + "{} unconsumed bytes after all records consumed".format( + len(self._buffer) - self._pos)) + raise StopIteration + try: + msg = self._read_msg() + except (ValueError, IndexError) as err: + raise CorruptRecordException( + "Found invalid record structure: {!r}".format(err)) + else: + self._next_record_index += 1 + return msg + + next = __next__ + + def validate_crc(self): + assert self._decompressed is False, \ + "Validate should be called before iteration" + + crc = self.crc + data_view = memoryview(self._buffer)[self.ATTRIBUTES_OFFSET:] + verify_crc = calc_crc32c(data_view.tobytes()) + return crc == verify_crc + + +class DefaultRecord(ABCRecord): + + __slots__ = ("_offset", "_timestamp", "_timestamp_type", "_key", "_value", + "_headers") + + def __init__(self, offset, timestamp, timestamp_type, key, value, headers): + self._offset = offset + self._timestamp = timestamp + self._timestamp_type = timestamp_type + self._key = key + self._value = value + self._headers = headers + + @property + def offset(self): + return self._offset + + @property + def timestamp(self): + """ Epoch milliseconds + """ + return self._timestamp + + @property + def timestamp_type(self): + """ CREATE_TIME(0) or APPEND_TIME(1) + """ + return self._timestamp_type + + @property + def key(self): + """ Bytes key or None + """ + return self._key + + @property + def value(self): + """ Bytes value or None + """ + return self._value + + @property + def headers(self): + return self._headers + + @property + def checksum(self): + return None + + def __repr__(self): + return ( + "DefaultRecord(offset={!r}, timestamp={!r}, timestamp_type={!r}," + " key={!r}, value={!r}, headers={!r})".format( + self._offset, self._timestamp, self._timestamp_type, + self._key, self._value, self._headers) + ) + + +class DefaultRecordBatchBuilder(DefaultRecordBase, ABCRecordBatchBuilder): + + # excluding key, value and headers: + # 5 bytes length + 10 bytes timestamp + 5 bytes offset + 1 byte attributes + MAX_RECORD_OVERHEAD = 21 + + __slots__ = ("_magic", "_compression_type", "_batch_size", "_is_transactional", + "_producer_id", "_producer_epoch", "_base_sequence", + "_first_timestamp", "_max_timestamp", "_last_offset", "_num_records", + "_buffer") + + def __init__( + self, magic, compression_type, is_transactional, + producer_id, producer_epoch, base_sequence, batch_size): + assert magic >= 2 + self._magic = magic + self._compression_type = compression_type & self.CODEC_MASK + self._batch_size = batch_size + self._is_transactional = bool(is_transactional) + # KIP-98 fields for EOS + self._producer_id = producer_id + self._producer_epoch = producer_epoch + self._base_sequence = base_sequence + + self._first_timestamp = None + self._max_timestamp = None + self._last_offset = 0 + self._num_records = 0 + + self._buffer = bytearray(self.HEADER_STRUCT.size) + + def _get_attributes(self, include_compression_type=True): + attrs = 0 + if include_compression_type: + attrs |= self._compression_type + # Timestamp Type is set by Broker + if self._is_transactional: + attrs |= self.TRANSACTIONAL_MASK + # Control batches are only created by Broker + return attrs + + def append(self, offset, timestamp, key, value, headers, + # Cache for LOAD_FAST opcodes + encode_varint=encode_varint, size_of_varint=size_of_varint, + get_type=type, type_int=int, time_time=time.time, + byte_like=(bytes, bytearray, memoryview), + bytearray_type=bytearray, len_func=len, zero_len_varint=1 + ): + """ Write message to messageset buffer with MsgVersion 2 + """ + # Check types + if get_type(offset) != type_int: + raise TypeError(offset) + if timestamp is None: + timestamp = type_int(time_time() * 1000) + elif get_type(timestamp) != type_int: + raise TypeError(timestamp) + if not (key is None or get_type(key) in byte_like): + raise TypeError( + "Not supported type for key: {}".format(type(key))) + if not (value is None or get_type(value) in byte_like): + raise TypeError( + "Not supported type for value: {}".format(type(value))) + + # We will always add the first message, so those will be set + if self._first_timestamp is None: + self._first_timestamp = timestamp + self._max_timestamp = timestamp + timestamp_delta = 0 + first_message = 1 + else: + timestamp_delta = timestamp - self._first_timestamp + first_message = 0 + + # We can't write record right away to out buffer, we need to + # precompute the length as first value... + message_buffer = bytearray_type(b"\x00") # Attributes + write_byte = message_buffer.append + write = message_buffer.extend + + encode_varint(timestamp_delta, write_byte) + # Base offset is always 0 on Produce + encode_varint(offset, write_byte) + + if key is not None: + encode_varint(len_func(key), write_byte) + write(key) + else: + write_byte(zero_len_varint) + + if value is not None: + encode_varint(len_func(value), write_byte) + write(value) + else: + write_byte(zero_len_varint) + + encode_varint(len_func(headers), write_byte) + + for h_key, h_value in headers: + h_key = h_key.encode("utf-8") + encode_varint(len_func(h_key), write_byte) + write(h_key) + if h_value is not None: + encode_varint(len_func(h_value), write_byte) + write(h_value) + else: + write_byte(zero_len_varint) + + message_len = len_func(message_buffer) + main_buffer = self._buffer + + required_size = message_len + size_of_varint(message_len) + # Check if we can write this message + if (required_size + len_func(main_buffer) > self._batch_size and + not first_message): + return None + + # Those should be updated after the length check + if self._max_timestamp < timestamp: + self._max_timestamp = timestamp + self._num_records += 1 + self._last_offset = offset + + encode_varint(message_len, main_buffer.append) + main_buffer.extend(message_buffer) + + return DefaultRecordMetadata(offset, required_size, timestamp) + + def write_header(self, use_compression_type=True): + batch_len = len(self._buffer) + self.HEADER_STRUCT.pack_into( + self._buffer, 0, + 0, # BaseOffset, set by broker + batch_len - self.AFTER_LEN_OFFSET, # Size from here to end + 0, # PartitionLeaderEpoch, set by broker + self._magic, + 0, # CRC will be set below, as we need a filled buffer for it + self._get_attributes(use_compression_type), + self._last_offset, + self._first_timestamp, + self._max_timestamp, + self._producer_id, + self._producer_epoch, + self._base_sequence, + self._num_records + ) + crc = calc_crc32c(self._buffer[self.ATTRIBUTES_OFFSET:]) + struct.pack_into(">I", self._buffer, self.CRC_OFFSET, crc) + + def _maybe_compress(self): + if self._compression_type != self.CODEC_NONE: + self._assert_has_codec(self._compression_type) + header_size = self.HEADER_STRUCT.size + data = bytes(self._buffer[header_size:]) + if self._compression_type == self.CODEC_GZIP: + compressed = gzip_encode(data) + elif self._compression_type == self.CODEC_SNAPPY: + compressed = snappy_encode(data) + elif self._compression_type == self.CODEC_LZ4: + compressed = lz4_encode(data) + elif self._compression_type == self.CODEC_ZSTD: + compressed = zstd_encode(data) + compressed_size = len(compressed) + if len(data) <= compressed_size: + # We did not get any benefit from compression, lets send + # uncompressed + return False + else: + # Trim bytearray to the required size + needed_size = header_size + compressed_size + del self._buffer[needed_size:] + self._buffer[header_size:needed_size] = compressed + return True + return False + + def build(self): + send_compressed = self._maybe_compress() + self.write_header(send_compressed) + return self._buffer + + def size(self): + """ Return current size of data written to buffer + """ + return len(self._buffer) + + def size_in_bytes(self, offset, timestamp, key, value, headers): + if self._first_timestamp is not None: + timestamp_delta = timestamp - self._first_timestamp + else: + timestamp_delta = 0 + size_of_body = ( + 1 + # Attrs + size_of_varint(offset) + + size_of_varint(timestamp_delta) + + self.size_of(key, value, headers) + ) + return size_of_body + size_of_varint(size_of_body) + + @classmethod + def size_of(cls, key, value, headers): + size = 0 + # Key size + if key is None: + size += 1 + else: + key_len = len(key) + size += size_of_varint(key_len) + key_len + # Value size + if value is None: + size += 1 + else: + value_len = len(value) + size += size_of_varint(value_len) + value_len + # Header size + size += size_of_varint(len(headers)) + for h_key, h_value in headers: + h_key_len = len(h_key.encode("utf-8")) + size += size_of_varint(h_key_len) + h_key_len + + if h_value is None: + size += 1 + else: + h_value_len = len(h_value) + size += size_of_varint(h_value_len) + h_value_len + return size + + @classmethod + def estimate_size_in_bytes(cls, key, value, headers): + """ Get the upper bound estimate on the size of record + """ + return ( + cls.HEADER_STRUCT.size + cls.MAX_RECORD_OVERHEAD + + cls.size_of(key, value, headers) + ) + + +class DefaultRecordMetadata(object): + + __slots__ = ("_size", "_timestamp", "_offset") + + def __init__(self, offset, size, timestamp): + self._offset = offset + self._size = size + self._timestamp = timestamp + + @property + def offset(self): + return self._offset + + @property + def crc(self): + return None + + @property + def size(self): + return self._size + + @property + def timestamp(self): + return self._timestamp + + def __repr__(self): + return ( + "DefaultRecordMetadata(offset={!r}, size={!r}, timestamp={!r})" + .format(self._offset, self._size, self._timestamp) + ) diff --git a/testbed/dpkp__kafka-python/kafka/record/legacy_records.py b/testbed/dpkp__kafka-python/kafka/record/legacy_records.py new file mode 100644 index 0000000000000000000000000000000000000000..e2ee5490c38b98f8d818647b8a6d75cc93b0772d --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/legacy_records.py @@ -0,0 +1,548 @@ +# See: +# https://github.com/apache/kafka/blob/trunk/clients/src/main/java/org/\ +# apache/kafka/common/record/LegacyRecord.java + +# Builder and reader implementation for V0 and V1 record versions. As of Kafka +# 0.11.0.0 those were replaced with V2, thus the Legacy naming. + +# The schema is given below (see +# https://kafka.apache.org/protocol#protocol_message_sets for more details): + +# MessageSet => [Offset MessageSize Message] +# Offset => int64 +# MessageSize => int32 + +# v0 +# Message => Crc MagicByte Attributes Key Value +# Crc => int32 +# MagicByte => int8 +# Attributes => int8 +# Key => bytes +# Value => bytes + +# v1 (supported since 0.10.0) +# Message => Crc MagicByte Attributes Key Value +# Crc => int32 +# MagicByte => int8 +# Attributes => int8 +# Timestamp => int64 +# Key => bytes +# Value => bytes + +# The message attribute bits are given below: +# * Unused (4-7) +# * Timestamp Type (3) (added in V1) +# * Compression Type (0-2) + +# Note that when compression is enabled (see attributes above), the whole +# array of MessageSet's is compressed and places into a message as the `value`. +# Only the parent message is marked with `compression` bits in attributes. + +# The CRC covers the data from the Magic byte to the end of the message. + + +import struct +import time + +from kafka.record.abc import ABCRecord, ABCRecordBatch, ABCRecordBatchBuilder +from kafka.record.util import calc_crc32 + +from kafka.codec import ( + gzip_encode, snappy_encode, lz4_encode, lz4_encode_old_kafka, + gzip_decode, snappy_decode, lz4_decode, lz4_decode_old_kafka, +) +import kafka.codec as codecs +from kafka.errors import CorruptRecordException, UnsupportedCodecError + + +class LegacyRecordBase(object): + + __slots__ = () + + HEADER_STRUCT_V0 = struct.Struct( + ">q" # BaseOffset => Int64 + "i" # Length => Int32 + "I" # CRC => Int32 + "b" # Magic => Int8 + "b" # Attributes => Int8 + ) + HEADER_STRUCT_V1 = struct.Struct( + ">q" # BaseOffset => Int64 + "i" # Length => Int32 + "I" # CRC => Int32 + "b" # Magic => Int8 + "b" # Attributes => Int8 + "q" # timestamp => Int64 + ) + + LOG_OVERHEAD = CRC_OFFSET = struct.calcsize( + ">q" # Offset + "i" # Size + ) + MAGIC_OFFSET = LOG_OVERHEAD + struct.calcsize( + ">I" # CRC + ) + # Those are used for fast size calculations + RECORD_OVERHEAD_V0 = struct.calcsize( + ">I" # CRC + "b" # magic + "b" # attributes + "i" # Key length + "i" # Value length + ) + RECORD_OVERHEAD_V1 = struct.calcsize( + ">I" # CRC + "b" # magic + "b" # attributes + "q" # timestamp + "i" # Key length + "i" # Value length + ) + + KEY_OFFSET_V0 = HEADER_STRUCT_V0.size + KEY_OFFSET_V1 = HEADER_STRUCT_V1.size + KEY_LENGTH = VALUE_LENGTH = struct.calcsize(">i") # Bytes length is Int32 + + CODEC_MASK = 0x07 + CODEC_NONE = 0x00 + CODEC_GZIP = 0x01 + CODEC_SNAPPY = 0x02 + CODEC_LZ4 = 0x03 + TIMESTAMP_TYPE_MASK = 0x08 + + LOG_APPEND_TIME = 1 + CREATE_TIME = 0 + + NO_TIMESTAMP = -1 + + def _assert_has_codec(self, compression_type): + if compression_type == self.CODEC_GZIP: + checker, name = codecs.has_gzip, "gzip" + elif compression_type == self.CODEC_SNAPPY: + checker, name = codecs.has_snappy, "snappy" + elif compression_type == self.CODEC_LZ4: + checker, name = codecs.has_lz4, "lz4" + if not checker(): + raise UnsupportedCodecError( + "Libraries for {} compression codec not found".format(name)) + + +class LegacyRecordBatch(ABCRecordBatch, LegacyRecordBase): + + __slots__ = ("_buffer", "_magic", "_offset", "_crc", "_timestamp", + "_attributes", "_decompressed") + + def __init__(self, buffer, magic): + self._buffer = memoryview(buffer) + self._magic = magic + + offset, length, crc, magic_, attrs, timestamp = self._read_header(0) + assert length == len(buffer) - self.LOG_OVERHEAD + assert magic == magic_ + + self._offset = offset + self._crc = crc + self._timestamp = timestamp + self._attributes = attrs + self._decompressed = False + + @property + def timestamp_type(self): + """0 for CreateTime; 1 for LogAppendTime; None if unsupported. + + Value is determined by broker; produced messages should always set to 0 + Requires Kafka >= 0.10 / message version >= 1 + """ + if self._magic == 0: + return None + elif self._attributes & self.TIMESTAMP_TYPE_MASK: + return 1 + else: + return 0 + + @property + def compression_type(self): + return self._attributes & self.CODEC_MASK + + def validate_crc(self): + crc = calc_crc32(self._buffer[self.MAGIC_OFFSET:]) + return self._crc == crc + + def _decompress(self, key_offset): + # Copy of `_read_key_value`, but uses memoryview + pos = key_offset + key_size = struct.unpack_from(">i", self._buffer, pos)[0] + pos += self.KEY_LENGTH + if key_size != -1: + pos += key_size + value_size = struct.unpack_from(">i", self._buffer, pos)[0] + pos += self.VALUE_LENGTH + if value_size == -1: + raise CorruptRecordException("Value of compressed message is None") + else: + data = self._buffer[pos:pos + value_size] + + compression_type = self.compression_type + self._assert_has_codec(compression_type) + if compression_type == self.CODEC_GZIP: + uncompressed = gzip_decode(data) + elif compression_type == self.CODEC_SNAPPY: + uncompressed = snappy_decode(data.tobytes()) + elif compression_type == self.CODEC_LZ4: + if self._magic == 0: + uncompressed = lz4_decode_old_kafka(data.tobytes()) + else: + uncompressed = lz4_decode(data.tobytes()) + return uncompressed + + def _read_header(self, pos): + if self._magic == 0: + offset, length, crc, magic_read, attrs = \ + self.HEADER_STRUCT_V0.unpack_from(self._buffer, pos) + timestamp = None + else: + offset, length, crc, magic_read, attrs, timestamp = \ + self.HEADER_STRUCT_V1.unpack_from(self._buffer, pos) + return offset, length, crc, magic_read, attrs, timestamp + + def _read_all_headers(self): + pos = 0 + msgs = [] + buffer_len = len(self._buffer) + while pos < buffer_len: + header = self._read_header(pos) + msgs.append((header, pos)) + pos += self.LOG_OVERHEAD + header[1] # length + return msgs + + def _read_key_value(self, pos): + key_size = struct.unpack_from(">i", self._buffer, pos)[0] + pos += self.KEY_LENGTH + if key_size == -1: + key = None + else: + key = self._buffer[pos:pos + key_size].tobytes() + pos += key_size + + value_size = struct.unpack_from(">i", self._buffer, pos)[0] + pos += self.VALUE_LENGTH + if value_size == -1: + value = None + else: + value = self._buffer[pos:pos + value_size].tobytes() + return key, value + + def __iter__(self): + if self._magic == 1: + key_offset = self.KEY_OFFSET_V1 + else: + key_offset = self.KEY_OFFSET_V0 + timestamp_type = self.timestamp_type + + if self.compression_type: + # In case we will call iter again + if not self._decompressed: + self._buffer = memoryview(self._decompress(key_offset)) + self._decompressed = True + + # If relative offset is used, we need to decompress the entire + # message first to compute the absolute offset. + headers = self._read_all_headers() + if self._magic > 0: + msg_header, _ = headers[-1] + absolute_base_offset = self._offset - msg_header[0] + else: + absolute_base_offset = -1 + + for header, msg_pos in headers: + offset, _, crc, _, attrs, timestamp = header + # There should only ever be a single layer of compression + assert not attrs & self.CODEC_MASK, ( + 'MessageSet at offset %d appears double-compressed. This ' + 'should not happen -- check your producers!' % (offset,)) + + # When magic value is greater than 0, the timestamp + # of a compressed message depends on the + # typestamp type of the wrapper message: + if timestamp_type == self.LOG_APPEND_TIME: + timestamp = self._timestamp + + if absolute_base_offset >= 0: + offset += absolute_base_offset + + key, value = self._read_key_value(msg_pos + key_offset) + yield LegacyRecord( + offset, timestamp, timestamp_type, + key, value, crc) + else: + key, value = self._read_key_value(key_offset) + yield LegacyRecord( + self._offset, self._timestamp, timestamp_type, + key, value, self._crc) + + +class LegacyRecord(ABCRecord): + + __slots__ = ("_offset", "_timestamp", "_timestamp_type", "_key", "_value", + "_crc") + + def __init__(self, offset, timestamp, timestamp_type, key, value, crc): + self._offset = offset + self._timestamp = timestamp + self._timestamp_type = timestamp_type + self._key = key + self._value = value + self._crc = crc + + @property + def offset(self): + return self._offset + + @property + def timestamp(self): + """ Epoch milliseconds + """ + return self._timestamp + + @property + def timestamp_type(self): + """ CREATE_TIME(0) or APPEND_TIME(1) + """ + return self._timestamp_type + + @property + def key(self): + """ Bytes key or None + """ + return self._key + + @property + def value(self): + """ Bytes value or None + """ + return self._value + + @property + def headers(self): + return [] + + @property + def checksum(self): + return self._crc + + def __repr__(self): + return ( + "LegacyRecord(offset={!r}, timestamp={!r}, timestamp_type={!r}," + " key={!r}, value={!r}, crc={!r})".format( + self._offset, self._timestamp, self._timestamp_type, + self._key, self._value, self._crc) + ) + + +class LegacyRecordBatchBuilder(ABCRecordBatchBuilder, LegacyRecordBase): + + __slots__ = ("_magic", "_compression_type", "_batch_size", "_buffer") + + def __init__(self, magic, compression_type, batch_size): + self._magic = magic + self._compression_type = compression_type + self._batch_size = batch_size + self._buffer = bytearray() + + def append(self, offset, timestamp, key, value, headers=None): + """ Append message to batch. + """ + assert not headers, "Headers not supported in v0/v1" + # Check types + if type(offset) != int: + raise TypeError(offset) + if self._magic == 0: + timestamp = self.NO_TIMESTAMP + elif timestamp is None: + timestamp = int(time.time() * 1000) + elif type(timestamp) != int: + raise TypeError( + "`timestamp` should be int, but {} provided".format( + type(timestamp))) + if not (key is None or + isinstance(key, (bytes, bytearray, memoryview))): + raise TypeError( + "Not supported type for key: {}".format(type(key))) + if not (value is None or + isinstance(value, (bytes, bytearray, memoryview))): + raise TypeError( + "Not supported type for value: {}".format(type(value))) + + # Check if we have room for another message + pos = len(self._buffer) + size = self.size_in_bytes(offset, timestamp, key, value) + # We always allow at least one record to be appended + if offset != 0 and pos + size >= self._batch_size: + return None + + # Allocate proper buffer length + self._buffer.extend(bytearray(size)) + + # Encode message + crc = self._encode_msg(pos, offset, timestamp, key, value) + + return LegacyRecordMetadata(offset, crc, size, timestamp) + + def _encode_msg(self, start_pos, offset, timestamp, key, value, + attributes=0): + """ Encode msg data into the `msg_buffer`, which should be allocated + to at least the size of this message. + """ + magic = self._magic + buf = self._buffer + pos = start_pos + + # Write key and value + pos += self.KEY_OFFSET_V0 if magic == 0 else self.KEY_OFFSET_V1 + + if key is None: + struct.pack_into(">i", buf, pos, -1) + pos += self.KEY_LENGTH + else: + key_size = len(key) + struct.pack_into(">i", buf, pos, key_size) + pos += self.KEY_LENGTH + buf[pos: pos + key_size] = key + pos += key_size + + if value is None: + struct.pack_into(">i", buf, pos, -1) + pos += self.VALUE_LENGTH + else: + value_size = len(value) + struct.pack_into(">i", buf, pos, value_size) + pos += self.VALUE_LENGTH + buf[pos: pos + value_size] = value + pos += value_size + length = (pos - start_pos) - self.LOG_OVERHEAD + + # Write msg header. Note, that Crc will be updated later + if magic == 0: + self.HEADER_STRUCT_V0.pack_into( + buf, start_pos, + offset, length, 0, magic, attributes) + else: + self.HEADER_STRUCT_V1.pack_into( + buf, start_pos, + offset, length, 0, magic, attributes, timestamp) + + # Calculate CRC for msg + crc_data = memoryview(buf)[start_pos + self.MAGIC_OFFSET:] + crc = calc_crc32(crc_data) + struct.pack_into(">I", buf, start_pos + self.CRC_OFFSET, crc) + return crc + + def _maybe_compress(self): + if self._compression_type: + self._assert_has_codec(self._compression_type) + data = bytes(self._buffer) + if self._compression_type == self.CODEC_GZIP: + compressed = gzip_encode(data) + elif self._compression_type == self.CODEC_SNAPPY: + compressed = snappy_encode(data) + elif self._compression_type == self.CODEC_LZ4: + if self._magic == 0: + compressed = lz4_encode_old_kafka(data) + else: + compressed = lz4_encode(data) + size = self.size_in_bytes( + 0, timestamp=0, key=None, value=compressed) + # We will try to reuse the same buffer if we have enough space + if size > len(self._buffer): + self._buffer = bytearray(size) + else: + del self._buffer[size:] + self._encode_msg( + start_pos=0, + offset=0, timestamp=0, key=None, value=compressed, + attributes=self._compression_type) + return True + return False + + def build(self): + """Compress batch to be ready for send""" + self._maybe_compress() + return self._buffer + + def size(self): + """ Return current size of data written to buffer + """ + return len(self._buffer) + + # Size calculations. Just copied Java's implementation + + def size_in_bytes(self, offset, timestamp, key, value, headers=None): + """ Actual size of message to add + """ + assert not headers, "Headers not supported in v0/v1" + magic = self._magic + return self.LOG_OVERHEAD + self.record_size(magic, key, value) + + @classmethod + def record_size(cls, magic, key, value): + message_size = cls.record_overhead(magic) + if key is not None: + message_size += len(key) + if value is not None: + message_size += len(value) + return message_size + + @classmethod + def record_overhead(cls, magic): + assert magic in [0, 1], "Not supported magic" + if magic == 0: + return cls.RECORD_OVERHEAD_V0 + else: + return cls.RECORD_OVERHEAD_V1 + + @classmethod + def estimate_size_in_bytes(cls, magic, compression_type, key, value): + """ Upper bound estimate of record size. + """ + assert magic in [0, 1], "Not supported magic" + # In case of compression we may need another overhead for inner msg + if compression_type: + return ( + cls.LOG_OVERHEAD + cls.record_overhead(magic) + + cls.record_size(magic, key, value) + ) + return cls.LOG_OVERHEAD + cls.record_size(magic, key, value) + + +class LegacyRecordMetadata(object): + + __slots__ = ("_crc", "_size", "_timestamp", "_offset") + + def __init__(self, offset, crc, size, timestamp): + self._offset = offset + self._crc = crc + self._size = size + self._timestamp = timestamp + + @property + def offset(self): + return self._offset + + @property + def crc(self): + return self._crc + + @property + def size(self): + return self._size + + @property + def timestamp(self): + return self._timestamp + + def __repr__(self): + return ( + "LegacyRecordMetadata(offset={!r}, crc={!r}, size={!r}," + " timestamp={!r})".format( + self._offset, self._crc, self._size, self._timestamp) + ) diff --git a/testbed/dpkp__kafka-python/kafka/record/memory_records.py b/testbed/dpkp__kafka-python/kafka/record/memory_records.py new file mode 100644 index 0000000000000000000000000000000000000000..fc2ef2d6b95ed5cb8d629a621ee4cc825e861dcc --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/memory_records.py @@ -0,0 +1,187 @@ +# This class takes advantage of the fact that all formats v0, v1 and v2 of +# messages storage has the same byte offsets for Length and Magic fields. +# Lets look closely at what leading bytes all versions have: +# +# V0 and V1 (Offset is MessageSet part, other bytes are Message ones): +# Offset => Int64 +# BytesLength => Int32 +# CRC => Int32 +# Magic => Int8 +# ... +# +# V2: +# BaseOffset => Int64 +# Length => Int32 +# PartitionLeaderEpoch => Int32 +# Magic => Int8 +# ... +# +# So we can iterate over batches just by knowing offsets of Length. Magic is +# used to construct the correct class for Batch itself. +from __future__ import division + +import struct + +from kafka.errors import CorruptRecordException +from kafka.record.abc import ABCRecords +from kafka.record.legacy_records import LegacyRecordBatch, LegacyRecordBatchBuilder +from kafka.record.default_records import DefaultRecordBatch, DefaultRecordBatchBuilder + + +class MemoryRecords(ABCRecords): + + LENGTH_OFFSET = struct.calcsize(">q") + LOG_OVERHEAD = struct.calcsize(">qi") + MAGIC_OFFSET = struct.calcsize(">qii") + + # Minimum space requirements for Record V0 + MIN_SLICE = LOG_OVERHEAD + LegacyRecordBatch.RECORD_OVERHEAD_V0 + + __slots__ = ("_buffer", "_pos", "_next_slice", "_remaining_bytes") + + def __init__(self, bytes_data): + self._buffer = bytes_data + self._pos = 0 + # We keep one slice ahead so `has_next` will return very fast + self._next_slice = None + self._remaining_bytes = None + self._cache_next() + + def size_in_bytes(self): + return len(self._buffer) + + def valid_bytes(self): + # We need to read the whole buffer to get the valid_bytes. + # NOTE: in Fetcher we do the call after iteration, so should be fast + if self._remaining_bytes is None: + next_slice = self._next_slice + pos = self._pos + while self._remaining_bytes is None: + self._cache_next() + # Reset previous iterator position + self._next_slice = next_slice + self._pos = pos + return len(self._buffer) - self._remaining_bytes + + # NOTE: we cache offsets here as kwargs for a bit more speed, as cPython + # will use LOAD_FAST opcode in this case + def _cache_next(self, len_offset=LENGTH_OFFSET, log_overhead=LOG_OVERHEAD): + buffer = self._buffer + buffer_len = len(buffer) + pos = self._pos + remaining = buffer_len - pos + if remaining < log_overhead: + # Will be re-checked in Fetcher for remaining bytes. + self._remaining_bytes = remaining + self._next_slice = None + return + + length, = struct.unpack_from( + ">i", buffer, pos + len_offset) + + slice_end = pos + log_overhead + length + if slice_end > buffer_len: + # Will be re-checked in Fetcher for remaining bytes + self._remaining_bytes = remaining + self._next_slice = None + return + + self._next_slice = memoryview(buffer)[pos: slice_end] + self._pos = slice_end + + def has_next(self): + return self._next_slice is not None + + # NOTE: same cache for LOAD_FAST as above + def next_batch(self, _min_slice=MIN_SLICE, + _magic_offset=MAGIC_OFFSET): + next_slice = self._next_slice + if next_slice is None: + return None + if len(next_slice) < _min_slice: + raise CorruptRecordException( + "Record size is less than the minimum record overhead " + "({})".format(_min_slice - self.LOG_OVERHEAD)) + self._cache_next() + magic, = struct.unpack_from(">b", next_slice, _magic_offset) + if magic <= 1: + return LegacyRecordBatch(next_slice, magic) + else: + return DefaultRecordBatch(next_slice) + + +class MemoryRecordsBuilder(object): + + __slots__ = ("_builder", "_batch_size", "_buffer", "_next_offset", "_closed", + "_bytes_written") + + def __init__(self, magic, compression_type, batch_size): + assert magic in [0, 1, 2], "Not supported magic" + assert compression_type in [0, 1, 2, 3, 4], "Not valid compression type" + if magic >= 2: + self._builder = DefaultRecordBatchBuilder( + magic=magic, compression_type=compression_type, + is_transactional=False, producer_id=-1, producer_epoch=-1, + base_sequence=-1, batch_size=batch_size) + else: + self._builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=compression_type, + batch_size=batch_size) + self._batch_size = batch_size + self._buffer = None + + self._next_offset = 0 + self._closed = False + self._bytes_written = 0 + + def append(self, timestamp, key, value, headers=[]): + """ Append a message to the buffer. + + Returns: RecordMetadata or None if unable to append + """ + if self._closed: + return None + + offset = self._next_offset + metadata = self._builder.append(offset, timestamp, key, value, headers) + # Return of None means there's no space to add a new message + if metadata is None: + return None + + self._next_offset += 1 + return metadata + + def close(self): + # This method may be called multiple times on the same batch + # i.e., on retries + # we need to make sure we only close it out once + # otherwise compressed messages may be double-compressed + # see Issue 718 + if not self._closed: + self._bytes_written = self._builder.size() + self._buffer = bytes(self._builder.build()) + self._builder = None + self._closed = True + + def size_in_bytes(self): + if not self._closed: + return self._builder.size() + else: + return len(self._buffer) + + def compression_rate(self): + assert self._closed + return self.size_in_bytes() / self._bytes_written + + def is_full(self): + if self._closed: + return True + else: + return self._builder.size() >= self._batch_size + + def next_offset(self): + return self._next_offset + + def buffer(self): + assert self._closed + return self._buffer diff --git a/testbed/dpkp__kafka-python/kafka/record/util.py b/testbed/dpkp__kafka-python/kafka/record/util.py new file mode 100644 index 0000000000000000000000000000000000000000..3b712005de748426513e36b306f9ac5b0ca4adb7 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/record/util.py @@ -0,0 +1,135 @@ +import binascii + +from kafka.record._crc32c import crc as crc32c_py +try: + from crc32c import crc32c as crc32c_c +except ImportError: + crc32c_c = None + + +def encode_varint(value, write): + """ Encode an integer to a varint presentation. See + https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints + on how those can be produced. + + Arguments: + value (int): Value to encode + write (function): Called per byte that needs to be writen + + Returns: + int: Number of bytes written + """ + value = (value << 1) ^ (value >> 63) + + if value <= 0x7f: # 1 byte + write(value) + return 1 + if value <= 0x3fff: # 2 bytes + write(0x80 | (value & 0x7f)) + write(value >> 7) + return 2 + if value <= 0x1fffff: # 3 bytes + write(0x80 | (value & 0x7f)) + write(0x80 | ((value >> 7) & 0x7f)) + write(value >> 14) + return 3 + if value <= 0xfffffff: # 4 bytes + write(0x80 | (value & 0x7f)) + write(0x80 | ((value >> 7) & 0x7f)) + write(0x80 | ((value >> 14) & 0x7f)) + write(value >> 21) + return 4 + if value <= 0x7ffffffff: # 5 bytes + write(0x80 | (value & 0x7f)) + write(0x80 | ((value >> 7) & 0x7f)) + write(0x80 | ((value >> 14) & 0x7f)) + write(0x80 | ((value >> 21) & 0x7f)) + write(value >> 28) + return 5 + else: + # Return to general algorithm + bits = value & 0x7f + value >>= 7 + i = 0 + while value: + write(0x80 | bits) + bits = value & 0x7f + value >>= 7 + i += 1 + write(bits) + return i + + +def size_of_varint(value): + """ Number of bytes needed to encode an integer in variable-length format. + """ + value = (value << 1) ^ (value >> 63) + if value <= 0x7f: + return 1 + if value <= 0x3fff: + return 2 + if value <= 0x1fffff: + return 3 + if value <= 0xfffffff: + return 4 + if value <= 0x7ffffffff: + return 5 + if value <= 0x3ffffffffff: + return 6 + if value <= 0x1ffffffffffff: + return 7 + if value <= 0xffffffffffffff: + return 8 + if value <= 0x7fffffffffffffff: + return 9 + return 10 + + +def decode_varint(buffer, pos=0): + """ Decode an integer from a varint presentation. See + https://developers.google.com/protocol-buffers/docs/encoding?csw=1#varints + on how those can be produced. + + Arguments: + buffer (bytearray): buffer to read from. + pos (int): optional position to read from + + Returns: + (int, int): Decoded int value and next read position + """ + result = buffer[pos] + if not (result & 0x81): + return (result >> 1), pos + 1 + if not (result & 0x80): + return (result >> 1) ^ (~0), pos + 1 + + result &= 0x7f + pos += 1 + shift = 7 + while 1: + b = buffer[pos] + result |= ((b & 0x7f) << shift) + pos += 1 + if not (b & 0x80): + return ((result >> 1) ^ -(result & 1), pos) + shift += 7 + if shift >= 64: + raise ValueError("Out of int64 range") + + +_crc32c = crc32c_py +if crc32c_c is not None: + _crc32c = crc32c_c + + +def calc_crc32c(memview, _crc32c=_crc32c): + """ Calculate CRC-32C (Castagnoli) checksum over a memoryview of data + """ + return _crc32c(memview) + + +def calc_crc32(memview): + """ Calculate simple CRC-32 checksum over a memoryview of data + """ + crc = binascii.crc32(memview) & 0xffffffff + return crc diff --git a/testbed/dpkp__kafka-python/kafka/scram.py b/testbed/dpkp__kafka-python/kafka/scram.py new file mode 100644 index 0000000000000000000000000000000000000000..7f003750c1ef1bf8ee7f18f3140226b039cbc613 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/scram.py @@ -0,0 +1,81 @@ +from __future__ import absolute_import + +import base64 +import hashlib +import hmac +import uuid + +from kafka.vendor import six + + +if six.PY2: + def xor_bytes(left, right): + return bytearray(ord(lb) ^ ord(rb) for lb, rb in zip(left, right)) +else: + def xor_bytes(left, right): + return bytes(lb ^ rb for lb, rb in zip(left, right)) + + +class ScramClient: + MECHANISMS = { + 'SCRAM-SHA-256': hashlib.sha256, + 'SCRAM-SHA-512': hashlib.sha512 + } + + def __init__(self, user, password, mechanism): + self.nonce = str(uuid.uuid4()).replace('-', '') + self.auth_message = '' + self.salted_password = None + self.user = user + self.password = password.encode('utf-8') + self.hashfunc = self.MECHANISMS[mechanism] + self.hashname = ''.join(mechanism.lower().split('-')[1:3]) + self.stored_key = None + self.client_key = None + self.client_signature = None + self.client_proof = None + self.server_key = None + self.server_signature = None + + def first_message(self): + client_first_bare = 'n={},r={}'.format(self.user, self.nonce) + self.auth_message += client_first_bare + return 'n,,' + client_first_bare + + def process_server_first_message(self, server_first_message): + self.auth_message += ',' + server_first_message + params = dict(pair.split('=', 1) for pair in server_first_message.split(',')) + server_nonce = params['r'] + if not server_nonce.startswith(self.nonce): + raise ValueError("Server nonce, did not start with client nonce!") + self.nonce = server_nonce + self.auth_message += ',c=biws,r=' + self.nonce + + salt = base64.b64decode(params['s'].encode('utf-8')) + iterations = int(params['i']) + self.create_salted_password(salt, iterations) + + self.client_key = self.hmac(self.salted_password, b'Client Key') + self.stored_key = self.hashfunc(self.client_key).digest() + self.client_signature = self.hmac(self.stored_key, self.auth_message.encode('utf-8')) + self.client_proof = xor_bytes(self.client_key, self.client_signature) + self.server_key = self.hmac(self.salted_password, b'Server Key') + self.server_signature = self.hmac(self.server_key, self.auth_message.encode('utf-8')) + + def hmac(self, key, msg): + return hmac.new(key, msg, digestmod=self.hashfunc).digest() + + def create_salted_password(self, salt, iterations): + self.salted_password = hashlib.pbkdf2_hmac( + self.hashname, self.password, salt, iterations + ) + + def final_message(self): + return 'c=biws,r={},p={}'.format(self.nonce, base64.b64encode(self.client_proof).decode('utf-8')) + + def process_server_final_message(self, server_final_message): + params = dict(pair.split('=', 1) for pair in server_final_message.split(',')) + if self.server_signature != base64.b64decode(params['v'].encode('utf-8')): + raise ValueError("Server sent wrong signature!") + + diff --git a/testbed/dpkp__kafka-python/kafka/serializer/__init__.py b/testbed/dpkp__kafka-python/kafka/serializer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..90cd93ab288e1b900aa1b189b9fed4b4ccd388ef --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/serializer/__init__.py @@ -0,0 +1,3 @@ +from __future__ import absolute_import + +from kafka.serializer.abstract import Serializer, Deserializer diff --git a/testbed/dpkp__kafka-python/kafka/serializer/abstract.py b/testbed/dpkp__kafka-python/kafka/serializer/abstract.py new file mode 100644 index 0000000000000000000000000000000000000000..18ad8d69c74762f187223584639f9a70df6047e2 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/serializer/abstract.py @@ -0,0 +1,31 @@ +from __future__ import absolute_import + +import abc + + +class Serializer(object): + __meta__ = abc.ABCMeta + + def __init__(self, **config): + pass + + @abc.abstractmethod + def serialize(self, topic, value): + pass + + def close(self): + pass + + +class Deserializer(object): + __meta__ = abc.ABCMeta + + def __init__(self, **config): + pass + + @abc.abstractmethod + def deserialize(self, topic, bytes_): + pass + + def close(self): + pass diff --git a/testbed/dpkp__kafka-python/kafka/structs.py b/testbed/dpkp__kafka-python/kafka/structs.py new file mode 100644 index 0000000000000000000000000000000000000000..bcb0236709da62fc588329e551c92b5fc621ffd9 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/structs.py @@ -0,0 +1,87 @@ +""" Other useful structs """ +from __future__ import absolute_import + +from collections import namedtuple + + +"""A topic and partition tuple + +Keyword Arguments: + topic (str): A topic name + partition (int): A partition id +""" +TopicPartition = namedtuple("TopicPartition", + ["topic", "partition"]) + + +"""A Kafka broker metadata used by admin tools. + +Keyword Arguments: + nodeID (int): The Kafka broker id. + host (str): The Kafka broker hostname. + port (int): The Kafka broker port. + rack (str): The rack of the broker, which is used to in rack aware + partition assignment for fault tolerance. + Examples: `RACK1`, `us-east-1d`. Default: None +""" +BrokerMetadata = namedtuple("BrokerMetadata", + ["nodeId", "host", "port", "rack"]) + + +"""A topic partition metadata describing the state in the MetadataResponse. + +Keyword Arguments: + topic (str): The topic name of the partition this metadata relates to. + partition (int): The id of the partition this metadata relates to. + leader (int): The id of the broker that is the leader for the partition. + replicas (List[int]): The ids of all brokers that contain replicas of the + partition. + isr (List[int]): The ids of all brokers that contain in-sync replicas of + the partition. + error (KafkaError): A KafkaError object associated with the request for + this partition metadata. +""" +PartitionMetadata = namedtuple("PartitionMetadata", + ["topic", "partition", "leader", "replicas", "isr", "error"]) + + +"""The Kafka offset commit API + +The Kafka offset commit API allows users to provide additional metadata +(in the form of a string) when an offset is committed. This can be useful +(for example) to store information about which node made the commit, +what time the commit was made, etc. + +Keyword Arguments: + offset (int): The offset to be committed + metadata (str): Non-null metadata +""" +OffsetAndMetadata = namedtuple("OffsetAndMetadata", + # TODO add leaderEpoch: OffsetAndMetadata(offset, leaderEpoch, metadata) + ["offset", "metadata"]) + + +"""An offset and timestamp tuple + +Keyword Arguments: + offset (int): An offset + timestamp (int): The timestamp associated to the offset +""" +OffsetAndTimestamp = namedtuple("OffsetAndTimestamp", + ["offset", "timestamp"]) + +MemberInformation = namedtuple("MemberInformation", + ["member_id", "client_id", "client_host", "member_metadata", "member_assignment"]) + +GroupInformation = namedtuple("GroupInformation", + ["error_code", "group", "state", "protocol_type", "protocol", "members", "authorized_operations"]) + +"""Define retry policy for async producer + +Keyword Arguments: + Limit (int): Number of retries. limit >= 0, 0 means no retries + backoff_ms (int): Milliseconds to backoff. + retry_on_timeouts: +""" +RetryOptions = namedtuple("RetryOptions", + ["limit", "backoff_ms", "retry_on_timeouts"]) diff --git a/testbed/dpkp__kafka-python/kafka/util.py b/testbed/dpkp__kafka-python/kafka/util.py new file mode 100644 index 0000000000000000000000000000000000000000..e31d99305a815ab6c19d879cc5e5341c23097700 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/util.py @@ -0,0 +1,66 @@ +from __future__ import absolute_import + +import binascii +import weakref + +from kafka.vendor import six + + +if six.PY3: + MAX_INT = 2 ** 31 + TO_SIGNED = 2 ** 32 + + def crc32(data): + crc = binascii.crc32(data) + # py2 and py3 behave a little differently + # CRC is encoded as a signed int in kafka protocol + # so we'll convert the py3 unsigned result to signed + if crc >= MAX_INT: + crc -= TO_SIGNED + return crc +else: + from binascii import crc32 + + +class WeakMethod(object): + """ + Callable that weakly references a method and the object it is bound to. It + is based on https://stackoverflow.com/a/24287465. + + Arguments: + + object_dot_method: A bound instance method (i.e. 'object.method'). + """ + def __init__(self, object_dot_method): + try: + self.target = weakref.ref(object_dot_method.__self__) + except AttributeError: + self.target = weakref.ref(object_dot_method.im_self) + self._target_id = id(self.target()) + try: + self.method = weakref.ref(object_dot_method.__func__) + except AttributeError: + self.method = weakref.ref(object_dot_method.im_func) + self._method_id = id(self.method()) + + def __call__(self, *args, **kwargs): + """ + Calls the method on target with args and kwargs. + """ + return self.method()(self.target(), *args, **kwargs) + + def __hash__(self): + return hash(self.target) ^ hash(self.method) + + def __eq__(self, other): + if not isinstance(other, WeakMethod): + return False + return self._target_id == other._target_id and self._method_id == other._method_id + + +class Dict(dict): + """Utility class to support passing weakrefs to dicts + + See: https://docs.python.org/2/library/weakref.html + """ + pass diff --git a/testbed/dpkp__kafka-python/kafka/vendor/__init__.py b/testbed/dpkp__kafka-python/kafka/vendor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/dpkp__kafka-python/kafka/vendor/enum34.py b/testbed/dpkp__kafka-python/kafka/vendor/enum34.py new file mode 100644 index 0000000000000000000000000000000000000000..5f64bd2d8699053be3e87c21afdc8bccd263f381 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/vendor/enum34.py @@ -0,0 +1,841 @@ +# pylint: skip-file +# vendored from: +# https://bitbucket.org/stoneleaf/enum34/src/58c4cd7174ca35f164304c8a6f0a4d47b779c2a7/enum/__init__.py?at=1.1.6 + +"""Python Enumerations""" + +import sys as _sys + +__all__ = ['Enum', 'IntEnum', 'unique'] + +version = 1, 1, 6 + +pyver = float('%s.%s' % _sys.version_info[:2]) + +try: + any +except NameError: + def any(iterable): + for element in iterable: + if element: + return True + return False + +try: + from collections import OrderedDict +except ImportError: + OrderedDict = None + +try: + basestring +except NameError: + # In Python 2 basestring is the ancestor of both str and unicode + # in Python 3 it's just str, but was missing in 3.1 + basestring = str + +try: + unicode +except NameError: + # In Python 3 unicode no longer exists (it's just str) + unicode = str + +class _RouteClassAttributeToGetattr(object): + """Route attribute access on a class to __getattr__. + + This is a descriptor, used to define attributes that act differently when + accessed through an instance and through a class. Instance access remains + normal, but access to an attribute through a class will be routed to the + class's __getattr__ method; this is done by raising AttributeError. + + """ + def __init__(self, fget=None): + self.fget = fget + + def __get__(self, instance, ownerclass=None): + if instance is None: + raise AttributeError() + return self.fget(instance) + + def __set__(self, instance, value): + raise AttributeError("can't set attribute") + + def __delete__(self, instance): + raise AttributeError("can't delete attribute") + + +def _is_descriptor(obj): + """Returns True if obj is a descriptor, False otherwise.""" + return ( + hasattr(obj, '__get__') or + hasattr(obj, '__set__') or + hasattr(obj, '__delete__')) + + +def _is_dunder(name): + """Returns True if a __dunder__ name, False otherwise.""" + return (name[:2] == name[-2:] == '__' and + name[2:3] != '_' and + name[-3:-2] != '_' and + len(name) > 4) + + +def _is_sunder(name): + """Returns True if a _sunder_ name, False otherwise.""" + return (name[0] == name[-1] == '_' and + name[1:2] != '_' and + name[-2:-1] != '_' and + len(name) > 2) + + +def _make_class_unpicklable(cls): + """Make the given class un-picklable.""" + def _break_on_call_reduce(self, protocol=None): + raise TypeError('%r cannot be pickled' % self) + cls.__reduce_ex__ = _break_on_call_reduce + cls.__module__ = '' + + +class _EnumDict(dict): + """Track enum member order and ensure member names are not reused. + + EnumMeta will use the names found in self._member_names as the + enumeration member names. + + """ + def __init__(self): + super(_EnumDict, self).__init__() + self._member_names = [] + + def __setitem__(self, key, value): + """Changes anything not dundered or not a descriptor. + + If a descriptor is added with the same name as an enum member, the name + is removed from _member_names (this may leave a hole in the numerical + sequence of values). + + If an enum member name is used twice, an error is raised; duplicate + values are not checked for. + + Single underscore (sunder) names are reserved. + + Note: in 3.x __order__ is simply discarded as a not necessary piece + leftover from 2.x + + """ + if pyver >= 3.0 and key in ('_order_', '__order__'): + return + elif key == '__order__': + key = '_order_' + if _is_sunder(key): + if key != '_order_': + raise ValueError('_names_ are reserved for future Enum use') + elif _is_dunder(key): + pass + elif key in self._member_names: + # descriptor overwriting an enum? + raise TypeError('Attempted to reuse key: %r' % key) + elif not _is_descriptor(value): + if key in self: + # enum overwriting a descriptor? + raise TypeError('Key already defined as: %r' % self[key]) + self._member_names.append(key) + super(_EnumDict, self).__setitem__(key, value) + + +# Dummy value for Enum as EnumMeta explicity checks for it, but of course until +# EnumMeta finishes running the first time the Enum class doesn't exist. This +# is also why there are checks in EnumMeta like `if Enum is not None` +Enum = None + + +class EnumMeta(type): + """Metaclass for Enum""" + @classmethod + def __prepare__(metacls, cls, bases): + return _EnumDict() + + def __new__(metacls, cls, bases, classdict): + # an Enum class is final once enumeration items have been defined; it + # cannot be mixed with other types (int, float, etc.) if it has an + # inherited __new__ unless a new __new__ is defined (or the resulting + # class will fail). + if type(classdict) is dict: + original_dict = classdict + classdict = _EnumDict() + for k, v in original_dict.items(): + classdict[k] = v + + member_type, first_enum = metacls._get_mixins_(bases) + __new__, save_new, use_args = metacls._find_new_(classdict, member_type, + first_enum) + # save enum items into separate mapping so they don't get baked into + # the new class + members = dict((k, classdict[k]) for k in classdict._member_names) + for name in classdict._member_names: + del classdict[name] + + # py2 support for definition order + _order_ = classdict.get('_order_') + if _order_ is None: + if pyver < 3.0: + try: + _order_ = [name for (name, value) in sorted(members.items(), key=lambda item: item[1])] + except TypeError: + _order_ = [name for name in sorted(members.keys())] + else: + _order_ = classdict._member_names + else: + del classdict['_order_'] + if pyver < 3.0: + _order_ = _order_.replace(',', ' ').split() + aliases = [name for name in members if name not in _order_] + _order_ += aliases + + # check for illegal enum names (any others?) + invalid_names = set(members) & set(['mro']) + if invalid_names: + raise ValueError('Invalid enum member name(s): %s' % ( + ', '.join(invalid_names), )) + + # save attributes from super classes so we know if we can take + # the shortcut of storing members in the class dict + base_attributes = set([a for b in bases for a in b.__dict__]) + # create our new Enum type + enum_class = super(EnumMeta, metacls).__new__(metacls, cls, bases, classdict) + enum_class._member_names_ = [] # names in random order + if OrderedDict is not None: + enum_class._member_map_ = OrderedDict() + else: + enum_class._member_map_ = {} # name->value map + enum_class._member_type_ = member_type + + # Reverse value->name map for hashable values. + enum_class._value2member_map_ = {} + + # instantiate them, checking for duplicates as we go + # we instantiate first instead of checking for duplicates first in case + # a custom __new__ is doing something funky with the values -- such as + # auto-numbering ;) + if __new__ is None: + __new__ = enum_class.__new__ + for member_name in _order_: + value = members[member_name] + if not isinstance(value, tuple): + args = (value, ) + else: + args = value + if member_type is tuple: # special case for tuple enums + args = (args, ) # wrap it one more time + if not use_args or not args: + enum_member = __new__(enum_class) + if not hasattr(enum_member, '_value_'): + enum_member._value_ = value + else: + enum_member = __new__(enum_class, *args) + if not hasattr(enum_member, '_value_'): + enum_member._value_ = member_type(*args) + value = enum_member._value_ + enum_member._name_ = member_name + enum_member.__objclass__ = enum_class + enum_member.__init__(*args) + # If another member with the same value was already defined, the + # new member becomes an alias to the existing one. + for name, canonical_member in enum_class._member_map_.items(): + if canonical_member.value == enum_member._value_: + enum_member = canonical_member + break + else: + # Aliases don't appear in member names (only in __members__). + enum_class._member_names_.append(member_name) + # performance boost for any member that would not shadow + # a DynamicClassAttribute (aka _RouteClassAttributeToGetattr) + if member_name not in base_attributes: + setattr(enum_class, member_name, enum_member) + # now add to _member_map_ + enum_class._member_map_[member_name] = enum_member + try: + # This may fail if value is not hashable. We can't add the value + # to the map, and by-value lookups for this value will be + # linear. + enum_class._value2member_map_[value] = enum_member + except TypeError: + pass + + + # If a custom type is mixed into the Enum, and it does not know how + # to pickle itself, pickle.dumps will succeed but pickle.loads will + # fail. Rather than have the error show up later and possibly far + # from the source, sabotage the pickle protocol for this class so + # that pickle.dumps also fails. + # + # However, if the new class implements its own __reduce_ex__, do not + # sabotage -- it's on them to make sure it works correctly. We use + # __reduce_ex__ instead of any of the others as it is preferred by + # pickle over __reduce__, and it handles all pickle protocols. + unpicklable = False + if '__reduce_ex__' not in classdict: + if member_type is not object: + methods = ('__getnewargs_ex__', '__getnewargs__', + '__reduce_ex__', '__reduce__') + if not any(m in member_type.__dict__ for m in methods): + _make_class_unpicklable(enum_class) + unpicklable = True + + + # double check that repr and friends are not the mixin's or various + # things break (such as pickle) + for name in ('__repr__', '__str__', '__format__', '__reduce_ex__'): + class_method = getattr(enum_class, name) + obj_method = getattr(member_type, name, None) + enum_method = getattr(first_enum, name, None) + if name not in classdict and class_method is not enum_method: + if name == '__reduce_ex__' and unpicklable: + continue + setattr(enum_class, name, enum_method) + + # method resolution and int's are not playing nice + # Python's less than 2.6 use __cmp__ + + if pyver < 2.6: + + if issubclass(enum_class, int): + setattr(enum_class, '__cmp__', getattr(int, '__cmp__')) + + elif pyver < 3.0: + + if issubclass(enum_class, int): + for method in ( + '__le__', + '__lt__', + '__gt__', + '__ge__', + '__eq__', + '__ne__', + '__hash__', + ): + setattr(enum_class, method, getattr(int, method)) + + # replace any other __new__ with our own (as long as Enum is not None, + # anyway) -- again, this is to support pickle + if Enum is not None: + # if the user defined their own __new__, save it before it gets + # clobbered in case they subclass later + if save_new: + setattr(enum_class, '__member_new__', enum_class.__dict__['__new__']) + setattr(enum_class, '__new__', Enum.__dict__['__new__']) + return enum_class + + def __bool__(cls): + """ + classes/types should always be True. + """ + return True + + def __call__(cls, value, names=None, module=None, type=None, start=1): + """Either returns an existing member, or creates a new enum class. + + This method is used both when an enum class is given a value to match + to an enumeration member (i.e. Color(3)) and for the functional API + (i.e. Color = Enum('Color', names='red green blue')). + + When used for the functional API: `module`, if set, will be stored in + the new class' __module__ attribute; `type`, if set, will be mixed in + as the first base class. + + Note: if `module` is not set this routine will attempt to discover the + calling module by walking the frame stack; if this is unsuccessful + the resulting class will not be pickleable. + + """ + if names is None: # simple value lookup + return cls.__new__(cls, value) + # otherwise, functional API: we're creating a new Enum type + return cls._create_(value, names, module=module, type=type, start=start) + + def __contains__(cls, member): + return isinstance(member, cls) and member.name in cls._member_map_ + + def __delattr__(cls, attr): + # nicer error message when someone tries to delete an attribute + # (see issue19025). + if attr in cls._member_map_: + raise AttributeError( + "%s: cannot delete Enum member." % cls.__name__) + super(EnumMeta, cls).__delattr__(attr) + + def __dir__(self): + return (['__class__', '__doc__', '__members__', '__module__'] + + self._member_names_) + + @property + def __members__(cls): + """Returns a mapping of member name->value. + + This mapping lists all enum members, including aliases. Note that this + is a copy of the internal mapping. + + """ + return cls._member_map_.copy() + + def __getattr__(cls, name): + """Return the enum member matching `name` + + We use __getattr__ instead of descriptors or inserting into the enum + class' __dict__ in order to support `name` and `value` being both + properties for enum members (which live in the class' __dict__) and + enum members themselves. + + """ + if _is_dunder(name): + raise AttributeError(name) + try: + return cls._member_map_[name] + except KeyError: + raise AttributeError(name) + + def __getitem__(cls, name): + return cls._member_map_[name] + + def __iter__(cls): + return (cls._member_map_[name] for name in cls._member_names_) + + def __reversed__(cls): + return (cls._member_map_[name] for name in reversed(cls._member_names_)) + + def __len__(cls): + return len(cls._member_names_) + + __nonzero__ = __bool__ + + def __repr__(cls): + return "" % cls.__name__ + + def __setattr__(cls, name, value): + """Block attempts to reassign Enum members. + + A simple assignment to the class namespace only changes one of the + several possible ways to get an Enum member from the Enum class, + resulting in an inconsistent Enumeration. + + """ + member_map = cls.__dict__.get('_member_map_', {}) + if name in member_map: + raise AttributeError('Cannot reassign members.') + super(EnumMeta, cls).__setattr__(name, value) + + def _create_(cls, class_name, names=None, module=None, type=None, start=1): + """Convenience method to create a new Enum class. + + `names` can be: + + * A string containing member names, separated either with spaces or + commas. Values are auto-numbered from 1. + * An iterable of member names. Values are auto-numbered from 1. + * An iterable of (member name, value) pairs. + * A mapping of member name -> value. + + """ + if pyver < 3.0: + # if class_name is unicode, attempt a conversion to ASCII + if isinstance(class_name, unicode): + try: + class_name = class_name.encode('ascii') + except UnicodeEncodeError: + raise TypeError('%r is not representable in ASCII' % class_name) + metacls = cls.__class__ + if type is None: + bases = (cls, ) + else: + bases = (type, cls) + classdict = metacls.__prepare__(class_name, bases) + _order_ = [] + + # special processing needed for names? + if isinstance(names, basestring): + names = names.replace(',', ' ').split() + if isinstance(names, (tuple, list)) and isinstance(names[0], basestring): + names = [(e, i+start) for (i, e) in enumerate(names)] + + # Here, names is either an iterable of (name, value) or a mapping. + item = None # in case names is empty + for item in names: + if isinstance(item, basestring): + member_name, member_value = item, names[item] + else: + member_name, member_value = item + classdict[member_name] = member_value + _order_.append(member_name) + # only set _order_ in classdict if name/value was not from a mapping + if not isinstance(item, basestring): + classdict['_order_'] = ' '.join(_order_) + enum_class = metacls.__new__(metacls, class_name, bases, classdict) + + # TODO: replace the frame hack if a blessed way to know the calling + # module is ever developed + if module is None: + try: + module = _sys._getframe(2).f_globals['__name__'] + except (AttributeError, ValueError): + pass + if module is None: + _make_class_unpicklable(enum_class) + else: + enum_class.__module__ = module + + return enum_class + + @staticmethod + def _get_mixins_(bases): + """Returns the type for creating enum members, and the first inherited + enum class. + + bases: the tuple of bases that was given to __new__ + + """ + if not bases or Enum is None: + return object, Enum + + + # double check that we are not subclassing a class with existing + # enumeration members; while we're at it, see if any other data + # type has been mixed in so we can use the correct __new__ + member_type = first_enum = None + for base in bases: + if (base is not Enum and + issubclass(base, Enum) and + base._member_names_): + raise TypeError("Cannot extend enumerations") + # base is now the last base in bases + if not issubclass(base, Enum): + raise TypeError("new enumerations must be created as " + "`ClassName([mixin_type,] enum_type)`") + + # get correct mix-in type (either mix-in type of Enum subclass, or + # first base if last base is Enum) + if not issubclass(bases[0], Enum): + member_type = bases[0] # first data type + first_enum = bases[-1] # enum type + else: + for base in bases[0].__mro__: + # most common: (IntEnum, int, Enum, object) + # possible: (, , + # , , + # ) + if issubclass(base, Enum): + if first_enum is None: + first_enum = base + else: + if member_type is None: + member_type = base + + return member_type, first_enum + + if pyver < 3.0: + @staticmethod + def _find_new_(classdict, member_type, first_enum): + """Returns the __new__ to be used for creating the enum members. + + classdict: the class dictionary given to __new__ + member_type: the data type whose __new__ will be used by default + first_enum: enumeration to check for an overriding __new__ + + """ + # now find the correct __new__, checking to see of one was defined + # by the user; also check earlier enum classes in case a __new__ was + # saved as __member_new__ + __new__ = classdict.get('__new__', None) + if __new__: + return None, True, True # __new__, save_new, use_args + + N__new__ = getattr(None, '__new__') + O__new__ = getattr(object, '__new__') + if Enum is None: + E__new__ = N__new__ + else: + E__new__ = Enum.__dict__['__new__'] + # check all possibles for __member_new__ before falling back to + # __new__ + for method in ('__member_new__', '__new__'): + for possible in (member_type, first_enum): + try: + target = possible.__dict__[method] + except (AttributeError, KeyError): + target = getattr(possible, method, None) + if target not in [ + None, + N__new__, + O__new__, + E__new__, + ]: + if method == '__member_new__': + classdict['__new__'] = target + return None, False, True + if isinstance(target, staticmethod): + target = target.__get__(member_type) + __new__ = target + break + if __new__ is not None: + break + else: + __new__ = object.__new__ + + # if a non-object.__new__ is used then whatever value/tuple was + # assigned to the enum member name will be passed to __new__ and to the + # new enum member's __init__ + if __new__ is object.__new__: + use_args = False + else: + use_args = True + + return __new__, False, use_args + else: + @staticmethod + def _find_new_(classdict, member_type, first_enum): + """Returns the __new__ to be used for creating the enum members. + + classdict: the class dictionary given to __new__ + member_type: the data type whose __new__ will be used by default + first_enum: enumeration to check for an overriding __new__ + + """ + # now find the correct __new__, checking to see of one was defined + # by the user; also check earlier enum classes in case a __new__ was + # saved as __member_new__ + __new__ = classdict.get('__new__', None) + + # should __new__ be saved as __member_new__ later? + save_new = __new__ is not None + + if __new__ is None: + # check all possibles for __member_new__ before falling back to + # __new__ + for method in ('__member_new__', '__new__'): + for possible in (member_type, first_enum): + target = getattr(possible, method, None) + if target not in ( + None, + None.__new__, + object.__new__, + Enum.__new__, + ): + __new__ = target + break + if __new__ is not None: + break + else: + __new__ = object.__new__ + + # if a non-object.__new__ is used then whatever value/tuple was + # assigned to the enum member name will be passed to __new__ and to the + # new enum member's __init__ + if __new__ is object.__new__: + use_args = False + else: + use_args = True + + return __new__, save_new, use_args + + +######################################################## +# In order to support Python 2 and 3 with a single +# codebase we have to create the Enum methods separately +# and then use the `type(name, bases, dict)` method to +# create the class. +######################################################## +temp_enum_dict = {} +temp_enum_dict['__doc__'] = "Generic enumeration.\n\n Derive from this class to define new enumerations.\n\n" + +def __new__(cls, value): + # all enum instances are actually created during class construction + # without calling this method; this method is called by the metaclass' + # __call__ (i.e. Color(3) ), and by pickle + if type(value) is cls: + # For lookups like Color(Color.red) + value = value.value + #return value + # by-value search for a matching enum member + # see if it's in the reverse mapping (for hashable values) + try: + if value in cls._value2member_map_: + return cls._value2member_map_[value] + except TypeError: + # not there, now do long search -- O(n) behavior + for member in cls._member_map_.values(): + if member.value == value: + return member + raise ValueError("%s is not a valid %s" % (value, cls.__name__)) +temp_enum_dict['__new__'] = __new__ +del __new__ + +def __repr__(self): + return "<%s.%s: %r>" % ( + self.__class__.__name__, self._name_, self._value_) +temp_enum_dict['__repr__'] = __repr__ +del __repr__ + +def __str__(self): + return "%s.%s" % (self.__class__.__name__, self._name_) +temp_enum_dict['__str__'] = __str__ +del __str__ + +if pyver >= 3.0: + def __dir__(self): + added_behavior = [ + m + for cls in self.__class__.mro() + for m in cls.__dict__ + if m[0] != '_' and m not in self._member_map_ + ] + return (['__class__', '__doc__', '__module__', ] + added_behavior) + temp_enum_dict['__dir__'] = __dir__ + del __dir__ + +def __format__(self, format_spec): + # mixed-in Enums should use the mixed-in type's __format__, otherwise + # we can get strange results with the Enum name showing up instead of + # the value + + # pure Enum branch + if self._member_type_ is object: + cls = str + val = str(self) + # mix-in branch + else: + cls = self._member_type_ + val = self.value + return cls.__format__(val, format_spec) +temp_enum_dict['__format__'] = __format__ +del __format__ + + +#################################### +# Python's less than 2.6 use __cmp__ + +if pyver < 2.6: + + def __cmp__(self, other): + if type(other) is self.__class__: + if self is other: + return 0 + return -1 + return NotImplemented + raise TypeError("unorderable types: %s() and %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__cmp__'] = __cmp__ + del __cmp__ + +else: + + def __le__(self, other): + raise TypeError("unorderable types: %s() <= %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__le__'] = __le__ + del __le__ + + def __lt__(self, other): + raise TypeError("unorderable types: %s() < %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__lt__'] = __lt__ + del __lt__ + + def __ge__(self, other): + raise TypeError("unorderable types: %s() >= %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__ge__'] = __ge__ + del __ge__ + + def __gt__(self, other): + raise TypeError("unorderable types: %s() > %s()" % (self.__class__.__name__, other.__class__.__name__)) + temp_enum_dict['__gt__'] = __gt__ + del __gt__ + + +def __eq__(self, other): + if type(other) is self.__class__: + return self is other + return NotImplemented +temp_enum_dict['__eq__'] = __eq__ +del __eq__ + +def __ne__(self, other): + if type(other) is self.__class__: + return self is not other + return NotImplemented +temp_enum_dict['__ne__'] = __ne__ +del __ne__ + +def __hash__(self): + return hash(self._name_) +temp_enum_dict['__hash__'] = __hash__ +del __hash__ + +def __reduce_ex__(self, proto): + return self.__class__, (self._value_, ) +temp_enum_dict['__reduce_ex__'] = __reduce_ex__ +del __reduce_ex__ + +# _RouteClassAttributeToGetattr is used to provide access to the `name` +# and `value` properties of enum members while keeping some measure of +# protection from modification, while still allowing for an enumeration +# to have members named `name` and `value`. This works because enumeration +# members are not set directly on the enum class -- __getattr__ is +# used to look them up. + +@_RouteClassAttributeToGetattr +def name(self): + return self._name_ +temp_enum_dict['name'] = name +del name + +@_RouteClassAttributeToGetattr +def value(self): + return self._value_ +temp_enum_dict['value'] = value +del value + +@classmethod +def _convert(cls, name, module, filter, source=None): + """ + Create a new Enum subclass that replaces a collection of global constants + """ + # convert all constants from source (or module) that pass filter() to + # a new Enum called name, and export the enum and its members back to + # module; + # also, replace the __reduce_ex__ method so unpickling works in + # previous Python versions + module_globals = vars(_sys.modules[module]) + if source: + source = vars(source) + else: + source = module_globals + members = dict((name, value) for name, value in source.items() if filter(name)) + cls = cls(name, members, module=module) + cls.__reduce_ex__ = _reduce_ex_by_name + module_globals.update(cls.__members__) + module_globals[name] = cls + return cls +temp_enum_dict['_convert'] = _convert +del _convert + +Enum = EnumMeta('Enum', (object, ), temp_enum_dict) +del temp_enum_dict + +# Enum has now been created +########################### + +class IntEnum(int, Enum): + """Enum where members are also (and must be) ints""" + +def _reduce_ex_by_name(self, proto): + return self.name + +def unique(enumeration): + """Class decorator that ensures only unique members exist in an enumeration.""" + duplicates = [] + for name, member in enumeration.__members__.items(): + if name != member.name: + duplicates.append((name, member.name)) + if duplicates: + duplicate_names = ', '.join( + ["%s -> %s" % (alias, name) for (alias, name) in duplicates] + ) + raise ValueError('duplicate names found in %r: %s' % + (enumeration, duplicate_names) + ) + return enumeration diff --git a/testbed/dpkp__kafka-python/kafka/vendor/selectors34.py b/testbed/dpkp__kafka-python/kafka/vendor/selectors34.py new file mode 100644 index 0000000000000000000000000000000000000000..ebf5d515e6b7b7d039a937366e6ced8fa7cea999 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/vendor/selectors34.py @@ -0,0 +1,637 @@ +# pylint: skip-file +# vendored from https://github.com/berkerpeksag/selectors34 +# at commit ff61b82168d2cc9c4922ae08e2a8bf94aab61ea2 (unreleased, ~1.2) +# +# Original author: Charles-Francois Natali (c.f.natali[at]gmail.com) +# Maintainer: Berker Peksag (berker.peksag[at]gmail.com) +# Also see https://pypi.python.org/pypi/selectors34 +"""Selectors module. + +This module allows high-level and efficient I/O multiplexing, built upon the +`select` module primitives. + +The following code adapted from trollius.selectors. +""" +from __future__ import absolute_import + +from abc import ABCMeta, abstractmethod +from collections import namedtuple, Mapping +from errno import EINTR +import math +import select +import sys + +from kafka.vendor import six + + +def _wrap_error(exc, mapping, key): + if key not in mapping: + return + new_err_cls = mapping[key] + new_err = new_err_cls(*exc.args) + + # raise a new exception with the original traceback + if hasattr(exc, '__traceback__'): + traceback = exc.__traceback__ + else: + traceback = sys.exc_info()[2] + six.reraise(new_err_cls, new_err, traceback) + + +# generic events, that must be mapped to implementation-specific ones +EVENT_READ = (1 << 0) +EVENT_WRITE = (1 << 1) + + +def _fileobj_to_fd(fileobj): + """Return a file descriptor from a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + corresponding file descriptor + + Raises: + ValueError if the object is invalid + """ + if isinstance(fileobj, six.integer_types): + fd = fileobj + else: + try: + fd = int(fileobj.fileno()) + except (AttributeError, TypeError, ValueError): + raise ValueError("Invalid file object: " + "{0!r}".format(fileobj)) + if fd < 0: + raise ValueError("Invalid file descriptor: {0}".format(fd)) + return fd + + +SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data']) +"""Object used to associate a file object to its backing file descriptor, +selected event mask and attached data.""" + + +class _SelectorMapping(Mapping): + """Mapping of file objects to selector keys.""" + + def __init__(self, selector): + self._selector = selector + + def __len__(self): + return len(self._selector._fd_to_key) + + def __getitem__(self, fileobj): + try: + fd = self._selector._fileobj_lookup(fileobj) + return self._selector._fd_to_key[fd] + except KeyError: + raise KeyError("{0!r} is not registered".format(fileobj)) + + def __iter__(self): + return iter(self._selector._fd_to_key) + +# Using six.add_metaclass() decorator instead of six.with_metaclass() because +# the latter leaks temporary_class to garbage with gc disabled +@six.add_metaclass(ABCMeta) +class BaseSelector(object): + """Selector abstract base class. + + A selector supports registering file objects to be monitored for specific + I/O events. + + A file object is a file descriptor or any object with a `fileno()` method. + An arbitrary object can be attached to the file object, which can be used + for example to store context information, a callback, etc. + + A selector can use various implementations (select(), poll(), epoll()...) + depending on the platform. The default `Selector` class uses the most + efficient implementation on the current platform. + """ + + @abstractmethod + def register(self, fileobj, events, data=None): + """Register a file object. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + ValueError if events is invalid + KeyError if fileobj is already registered + OSError if fileobj is closed or otherwise is unacceptable to + the underlying system call (if a system call is made) + + Note: + OSError may or may not be raised + """ + raise NotImplementedError + + @abstractmethod + def unregister(self, fileobj): + """Unregister a file object. + + Parameters: + fileobj -- file object or file descriptor + + Returns: + SelectorKey instance + + Raises: + KeyError if fileobj is not registered + + Note: + If fileobj is registered but has since been closed this does + *not* raise OSError (even if the wrapped syscall does) + """ + raise NotImplementedError + + def modify(self, fileobj, events, data=None): + """Change a registered file object monitored events or attached data. + + Parameters: + fileobj -- file object or file descriptor + events -- events to monitor (bitwise mask of EVENT_READ|EVENT_WRITE) + data -- attached data + + Returns: + SelectorKey instance + + Raises: + Anything that unregister() or register() raises + """ + self.unregister(fileobj) + return self.register(fileobj, events, data) + + @abstractmethod + def select(self, timeout=None): + """Perform the actual selection, until some monitored file objects are + ready or a timeout expires. + + Parameters: + timeout -- if timeout > 0, this specifies the maximum wait time, in + seconds + if timeout <= 0, the select() call won't block, and will + report the currently ready file objects + if timeout is None, select() will block until a monitored + file object becomes ready + + Returns: + list of (key, events) for ready file objects + `events` is a bitwise mask of EVENT_READ|EVENT_WRITE + """ + raise NotImplementedError + + def close(self): + """Close the selector. + + This must be called to make sure that any underlying resource is freed. + """ + pass + + def get_key(self, fileobj): + """Return the key associated to a registered file object. + + Returns: + SelectorKey for this file object + """ + mapping = self.get_map() + if mapping is None: + raise RuntimeError('Selector is closed') + try: + return mapping[fileobj] + except KeyError: + raise KeyError("{0!r} is not registered".format(fileobj)) + + @abstractmethod + def get_map(self): + """Return a mapping of file objects to selector keys.""" + raise NotImplementedError + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + +class _BaseSelectorImpl(BaseSelector): + """Base selector implementation.""" + + def __init__(self): + # this maps file descriptors to keys + self._fd_to_key = {} + # read-only mapping returned by get_map() + self._map = _SelectorMapping(self) + + def _fileobj_lookup(self, fileobj): + """Return a file descriptor from a file object. + + This wraps _fileobj_to_fd() to do an exhaustive search in case + the object is invalid but we still have it in our map. This + is used by unregister() so we can unregister an object that + was previously registered even if it is closed. It is also + used by _SelectorMapping. + """ + try: + return _fileobj_to_fd(fileobj) + except ValueError: + # Do an exhaustive search. + for key in self._fd_to_key.values(): + if key.fileobj is fileobj: + return key.fd + # Raise ValueError after all. + raise + + def register(self, fileobj, events, data=None): + if (not events) or (events & ~(EVENT_READ | EVENT_WRITE)): + raise ValueError("Invalid events: {0!r}".format(events)) + + key = SelectorKey(fileobj, self._fileobj_lookup(fileobj), events, data) + + if key.fd in self._fd_to_key: + raise KeyError("{0!r} (FD {1}) is already registered" + .format(fileobj, key.fd)) + + self._fd_to_key[key.fd] = key + return key + + def unregister(self, fileobj): + try: + key = self._fd_to_key.pop(self._fileobj_lookup(fileobj)) + except KeyError: + raise KeyError("{0!r} is not registered".format(fileobj)) + return key + + def modify(self, fileobj, events, data=None): + # TODO: Subclasses can probably optimize this even further. + try: + key = self._fd_to_key[self._fileobj_lookup(fileobj)] + except KeyError: + raise KeyError("{0!r} is not registered".format(fileobj)) + if events != key.events: + self.unregister(fileobj) + key = self.register(fileobj, events, data) + elif data != key.data: + # Use a shortcut to update the data. + key = key._replace(data=data) + self._fd_to_key[key.fd] = key + return key + + def close(self): + self._fd_to_key.clear() + self._map = None + + def get_map(self): + return self._map + + def _key_from_fd(self, fd): + """Return the key associated to a given file descriptor. + + Parameters: + fd -- file descriptor + + Returns: + corresponding key, or None if not found + """ + try: + return self._fd_to_key[fd] + except KeyError: + return None + + +class SelectSelector(_BaseSelectorImpl): + """Select-based selector.""" + + def __init__(self): + super(SelectSelector, self).__init__() + self._readers = set() + self._writers = set() + + def register(self, fileobj, events, data=None): + key = super(SelectSelector, self).register(fileobj, events, data) + if events & EVENT_READ: + self._readers.add(key.fd) + if events & EVENT_WRITE: + self._writers.add(key.fd) + return key + + def unregister(self, fileobj): + key = super(SelectSelector, self).unregister(fileobj) + self._readers.discard(key.fd) + self._writers.discard(key.fd) + return key + + if sys.platform == 'win32': + def _select(self, r, w, _, timeout=None): + r, w, x = select.select(r, w, w, timeout) + return r, w + x, [] + else: + _select = staticmethod(select.select) + + def select(self, timeout=None): + timeout = None if timeout is None else max(timeout, 0) + ready = [] + try: + r, w, _ = self._select(self._readers, self._writers, [], timeout) + except select.error as exc: + if exc.args[0] == EINTR: + return ready + else: + raise + r = set(r) + w = set(w) + for fd in r | w: + events = 0 + if fd in r: + events |= EVENT_READ + if fd in w: + events |= EVENT_WRITE + + key = self._key_from_fd(fd) + if key: + ready.append((key, events & key.events)) + return ready + + +if hasattr(select, 'poll'): + + class PollSelector(_BaseSelectorImpl): + """Poll-based selector.""" + + def __init__(self): + super(PollSelector, self).__init__() + self._poll = select.poll() + + def register(self, fileobj, events, data=None): + key = super(PollSelector, self).register(fileobj, events, data) + poll_events = 0 + if events & EVENT_READ: + poll_events |= select.POLLIN + if events & EVENT_WRITE: + poll_events |= select.POLLOUT + self._poll.register(key.fd, poll_events) + return key + + def unregister(self, fileobj): + key = super(PollSelector, self).unregister(fileobj) + self._poll.unregister(key.fd) + return key + + def select(self, timeout=None): + if timeout is None: + timeout = None + elif timeout <= 0: + timeout = 0 + else: + # poll() has a resolution of 1 millisecond, round away from + # zero to wait *at least* timeout seconds. + timeout = int(math.ceil(timeout * 1e3)) + ready = [] + try: + fd_event_list = self._poll.poll(timeout) + except select.error as exc: + if exc.args[0] == EINTR: + return ready + else: + raise + for fd, event in fd_event_list: + events = 0 + if event & ~select.POLLIN: + events |= EVENT_WRITE + if event & ~select.POLLOUT: + events |= EVENT_READ + + key = self._key_from_fd(fd) + if key: + ready.append((key, events & key.events)) + return ready + + +if hasattr(select, 'epoll'): + + class EpollSelector(_BaseSelectorImpl): + """Epoll-based selector.""" + + def __init__(self): + super(EpollSelector, self).__init__() + self._epoll = select.epoll() + + def fileno(self): + return self._epoll.fileno() + + def register(self, fileobj, events, data=None): + key = super(EpollSelector, self).register(fileobj, events, data) + epoll_events = 0 + if events & EVENT_READ: + epoll_events |= select.EPOLLIN + if events & EVENT_WRITE: + epoll_events |= select.EPOLLOUT + self._epoll.register(key.fd, epoll_events) + return key + + def unregister(self, fileobj): + key = super(EpollSelector, self).unregister(fileobj) + try: + self._epoll.unregister(key.fd) + except IOError: + # This can happen if the FD was closed since it + # was registered. + pass + return key + + def select(self, timeout=None): + if timeout is None: + timeout = -1 + elif timeout <= 0: + timeout = 0 + else: + # epoll_wait() has a resolution of 1 millisecond, round away + # from zero to wait *at least* timeout seconds. + timeout = math.ceil(timeout * 1e3) * 1e-3 + + # epoll_wait() expects `maxevents` to be greater than zero; + # we want to make sure that `select()` can be called when no + # FD is registered. + max_ev = max(len(self._fd_to_key), 1) + + ready = [] + try: + fd_event_list = self._epoll.poll(timeout, max_ev) + except IOError as exc: + if exc.errno == EINTR: + return ready + else: + raise + for fd, event in fd_event_list: + events = 0 + if event & ~select.EPOLLIN: + events |= EVENT_WRITE + if event & ~select.EPOLLOUT: + events |= EVENT_READ + + key = self._key_from_fd(fd) + if key: + ready.append((key, events & key.events)) + return ready + + def close(self): + self._epoll.close() + super(EpollSelector, self).close() + + +if hasattr(select, 'devpoll'): + + class DevpollSelector(_BaseSelectorImpl): + """Solaris /dev/poll selector.""" + + def __init__(self): + super(DevpollSelector, self).__init__() + self._devpoll = select.devpoll() + + def fileno(self): + return self._devpoll.fileno() + + def register(self, fileobj, events, data=None): + key = super(DevpollSelector, self).register(fileobj, events, data) + poll_events = 0 + if events & EVENT_READ: + poll_events |= select.POLLIN + if events & EVENT_WRITE: + poll_events |= select.POLLOUT + self._devpoll.register(key.fd, poll_events) + return key + + def unregister(self, fileobj): + key = super(DevpollSelector, self).unregister(fileobj) + self._devpoll.unregister(key.fd) + return key + + def select(self, timeout=None): + if timeout is None: + timeout = None + elif timeout <= 0: + timeout = 0 + else: + # devpoll() has a resolution of 1 millisecond, round away from + # zero to wait *at least* timeout seconds. + timeout = math.ceil(timeout * 1e3) + ready = [] + try: + fd_event_list = self._devpoll.poll(timeout) + except OSError as exc: + if exc.errno == EINTR: + return ready + else: + raise + for fd, event in fd_event_list: + events = 0 + if event & ~select.POLLIN: + events |= EVENT_WRITE + if event & ~select.POLLOUT: + events |= EVENT_READ + + key = self._key_from_fd(fd) + if key: + ready.append((key, events & key.events)) + return ready + + def close(self): + self._devpoll.close() + super(DevpollSelector, self).close() + + +if hasattr(select, 'kqueue'): + + class KqueueSelector(_BaseSelectorImpl): + """Kqueue-based selector.""" + + def __init__(self): + super(KqueueSelector, self).__init__() + self._kqueue = select.kqueue() + + def fileno(self): + return self._kqueue.fileno() + + def register(self, fileobj, events, data=None): + key = super(KqueueSelector, self).register(fileobj, events, data) + if events & EVENT_READ: + kev = select.kevent(key.fd, select.KQ_FILTER_READ, + select.KQ_EV_ADD) + self._kqueue.control([kev], 0, 0) + if events & EVENT_WRITE: + kev = select.kevent(key.fd, select.KQ_FILTER_WRITE, + select.KQ_EV_ADD) + self._kqueue.control([kev], 0, 0) + return key + + def unregister(self, fileobj): + key = super(KqueueSelector, self).unregister(fileobj) + if key.events & EVENT_READ: + kev = select.kevent(key.fd, select.KQ_FILTER_READ, + select.KQ_EV_DELETE) + try: + self._kqueue.control([kev], 0, 0) + except OSError: + # This can happen if the FD was closed since it + # was registered. + pass + if key.events & EVENT_WRITE: + kev = select.kevent(key.fd, select.KQ_FILTER_WRITE, + select.KQ_EV_DELETE) + try: + self._kqueue.control([kev], 0, 0) + except OSError: + # See comment above. + pass + return key + + def select(self, timeout=None): + timeout = None if timeout is None else max(timeout, 0) + max_ev = len(self._fd_to_key) + ready = [] + try: + kev_list = self._kqueue.control(None, max_ev, timeout) + except OSError as exc: + if exc.errno == EINTR: + return ready + else: + raise + for kev in kev_list: + fd = kev.ident + flag = kev.filter + events = 0 + if flag == select.KQ_FILTER_READ: + events |= EVENT_READ + if flag == select.KQ_FILTER_WRITE: + events |= EVENT_WRITE + + key = self._key_from_fd(fd) + if key: + ready.append((key, events & key.events)) + return ready + + def close(self): + self._kqueue.close() + super(KqueueSelector, self).close() + + +# Choose the best implementation, roughly: +# epoll|kqueue|devpoll > poll > select. +# select() also can't accept a FD > FD_SETSIZE (usually around 1024) +if 'KqueueSelector' in globals(): + DefaultSelector = KqueueSelector +elif 'EpollSelector' in globals(): + DefaultSelector = EpollSelector +elif 'DevpollSelector' in globals(): + DefaultSelector = DevpollSelector +elif 'PollSelector' in globals(): + DefaultSelector = PollSelector +else: + DefaultSelector = SelectSelector diff --git a/testbed/dpkp__kafka-python/kafka/vendor/six.py b/testbed/dpkp__kafka-python/kafka/vendor/six.py new file mode 100644 index 0000000000000000000000000000000000000000..3621a0ab4ee0b877a7620bbe876c746e282664ee --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/vendor/six.py @@ -0,0 +1,897 @@ +# pylint: skip-file + +# Copyright (c) 2010-2017 Benjamin Peterson +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""Utilities for writing code that runs on Python 2 and 3""" + +from __future__ import absolute_import + +import functools +import itertools +import operator +import sys +import types + +__author__ = "Benjamin Peterson " +__version__ = "1.11.0" + + +# Useful for very coarse version differentiation. +PY2 = sys.version_info[0] == 2 +PY3 = sys.version_info[0] == 3 +PY34 = sys.version_info[0:2] >= (3, 4) + +if PY3: + string_types = str, + integer_types = int, + class_types = type, + text_type = str + binary_type = bytes + + MAXSIZE = sys.maxsize +else: + string_types = basestring, + integer_types = (int, long) + class_types = (type, types.ClassType) + text_type = unicode + binary_type = str + + if sys.platform.startswith("java"): + # Jython always uses 32 bits. + MAXSIZE = int((1 << 31) - 1) + else: + # It's possible to have sizeof(long) != sizeof(Py_ssize_t). + class X(object): + + def __len__(self): + return 1 << 31 + try: + len(X()) + except OverflowError: + # 32-bit + MAXSIZE = int((1 << 31) - 1) + else: + # 64-bit + MAXSIZE = int((1 << 63) - 1) + + # Don't del it here, cause with gc disabled this "leaks" to garbage. + # Note: This is a kafka-python customization, details at: + # https://github.com/dpkp/kafka-python/pull/979#discussion_r100403389 + # del X + + +def _add_doc(func, doc): + """Add documentation to a function.""" + func.__doc__ = doc + + +def _import_module(name): + """Import module, returning the module after the last dot.""" + __import__(name) + return sys.modules[name] + + +class _LazyDescr(object): + + def __init__(self, name): + self.name = name + + def __get__(self, obj, tp): + result = self._resolve() + setattr(obj, self.name, result) # Invokes __set__. + try: + # This is a bit ugly, but it avoids running this again by + # removing this descriptor. + delattr(obj.__class__, self.name) + except AttributeError: + pass + return result + + +class MovedModule(_LazyDescr): + + def __init__(self, name, old, new=None): + super(MovedModule, self).__init__(name) + if PY3: + if new is None: + new = name + self.mod = new + else: + self.mod = old + + def _resolve(self): + return _import_module(self.mod) + + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + + +class MovedAttribute(_LazyDescr): + + def __init__(self, name, old_mod, new_mod, old_attr=None, new_attr=None): + super(MovedAttribute, self).__init__(name) + if PY3: + if new_mod is None: + new_mod = name + self.mod = new_mod + if new_attr is None: + if old_attr is None: + new_attr = name + else: + new_attr = old_attr + self.attr = new_attr + else: + self.mod = old_mod + if old_attr is None: + old_attr = name + self.attr = old_attr + + def _resolve(self): + module = _import_module(self.mod) + return getattr(module, self.attr) + + +class _SixMetaPathImporter(object): + + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") + + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): + + """Lazy loading of moved objects""" + __path__ = [] # mark as package + + +_moved_attributes = [ + MovedAttribute("cStringIO", "cStringIO", "io", "StringIO"), + MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), + MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), + MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), + MovedAttribute("map", "itertools", "builtins", "imap", "map"), + MovedAttribute("getcwd", "os", "os", "getcwdu", "getcwd"), + MovedAttribute("getcwdb", "os", "os", "getcwd", "getcwdb"), + MovedAttribute("getoutput", "commands", "subprocess"), + MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("reload_module", "__builtin__", "importlib" if PY34 else "imp", "reload"), + MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), + MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), + MovedAttribute("UserString", "UserString", "collections"), + MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), + MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), + MovedAttribute("zip_longest", "itertools", "itertools", "izip_longest", "zip_longest"), + MovedModule("builtins", "__builtin__"), + MovedModule("configparser", "ConfigParser"), + MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), + MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), + MovedModule("http_cookies", "Cookie", "http.cookies"), + MovedModule("html_entities", "htmlentitydefs", "html.entities"), + MovedModule("html_parser", "HTMLParser", "html.parser"), + MovedModule("http_client", "httplib", "http.client"), + MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), + MovedModule("email_mime_image", "email.MIMEImage", "email.mime.image"), + MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), + MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), + MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), + MovedModule("CGIHTTPServer", "CGIHTTPServer", "http.server"), + MovedModule("SimpleHTTPServer", "SimpleHTTPServer", "http.server"), + MovedModule("cPickle", "cPickle", "pickle"), + MovedModule("queue", "Queue"), + MovedModule("reprlib", "repr"), + MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), + MovedModule("tkinter", "Tkinter"), + MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), + MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), + MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), + MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), + MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), + MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), + MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), + MovedModule("tkinter_colorchooser", "tkColorChooser", + "tkinter.colorchooser"), + MovedModule("tkinter_commondialog", "tkCommonDialog", + "tkinter.commondialog"), + MovedModule("tkinter_tkfiledialog", "tkFileDialog", "tkinter.filedialog"), + MovedModule("tkinter_font", "tkFont", "tkinter.font"), + MovedModule("tkinter_messagebox", "tkMessageBox", "tkinter.messagebox"), + MovedModule("tkinter_tksimpledialog", "tkSimpleDialog", + "tkinter.simpledialog"), + MovedModule("urllib_parse", __name__ + ".moves.urllib_parse", "urllib.parse"), + MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), + MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), + MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), +] +# Add windows specific modules. +if sys.platform == "win32": + _moved_attributes += [ + MovedModule("winreg", "_winreg"), + ] + +for attr in _moved_attributes: + setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) +del attr + +_MovedItems._moved_attributes = _moved_attributes + +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") + + +class Module_six_moves_urllib_parse(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_parse""" + + +_urllib_parse_moved_attributes = [ + MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), + MovedAttribute("parse_qs", "urlparse", "urllib.parse"), + MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), + MovedAttribute("urldefrag", "urlparse", "urllib.parse"), + MovedAttribute("urljoin", "urlparse", "urllib.parse"), + MovedAttribute("urlparse", "urlparse", "urllib.parse"), + MovedAttribute("urlsplit", "urlparse", "urllib.parse"), + MovedAttribute("urlunparse", "urlparse", "urllib.parse"), + MovedAttribute("urlunsplit", "urlparse", "urllib.parse"), + MovedAttribute("quote", "urllib", "urllib.parse"), + MovedAttribute("quote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote", "urllib", "urllib.parse"), + MovedAttribute("unquote_plus", "urllib", "urllib.parse"), + MovedAttribute("unquote_to_bytes", "urllib", "urllib.parse", "unquote", "unquote_to_bytes"), + MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("splitvalue", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), +] +for attr in _urllib_parse_moved_attributes: + setattr(Module_six_moves_urllib_parse, attr.name, attr) +del attr + +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") + + +class Module_six_moves_urllib_error(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_error""" + + +_urllib_error_moved_attributes = [ + MovedAttribute("URLError", "urllib2", "urllib.error"), + MovedAttribute("HTTPError", "urllib2", "urllib.error"), + MovedAttribute("ContentTooShortError", "urllib", "urllib.error"), +] +for attr in _urllib_error_moved_attributes: + setattr(Module_six_moves_urllib_error, attr.name, attr) +del attr + +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") + + +class Module_six_moves_urllib_request(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_request""" + + +_urllib_request_moved_attributes = [ + MovedAttribute("urlopen", "urllib2", "urllib.request"), + MovedAttribute("install_opener", "urllib2", "urllib.request"), + MovedAttribute("build_opener", "urllib2", "urllib.request"), + MovedAttribute("pathname2url", "urllib", "urllib.request"), + MovedAttribute("url2pathname", "urllib", "urllib.request"), + MovedAttribute("getproxies", "urllib", "urllib.request"), + MovedAttribute("Request", "urllib2", "urllib.request"), + MovedAttribute("OpenerDirector", "urllib2", "urllib.request"), + MovedAttribute("HTTPDefaultErrorHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPRedirectHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPCookieProcessor", "urllib2", "urllib.request"), + MovedAttribute("ProxyHandler", "urllib2", "urllib.request"), + MovedAttribute("BaseHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgr", "urllib2", "urllib.request"), + MovedAttribute("HTTPPasswordMgrWithDefaultRealm", "urllib2", "urllib.request"), + MovedAttribute("AbstractBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyBasicAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("AbstractDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("ProxyDigestAuthHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPSHandler", "urllib2", "urllib.request"), + MovedAttribute("FileHandler", "urllib2", "urllib.request"), + MovedAttribute("FTPHandler", "urllib2", "urllib.request"), + MovedAttribute("CacheFTPHandler", "urllib2", "urllib.request"), + MovedAttribute("UnknownHandler", "urllib2", "urllib.request"), + MovedAttribute("HTTPErrorProcessor", "urllib2", "urllib.request"), + MovedAttribute("urlretrieve", "urllib", "urllib.request"), + MovedAttribute("urlcleanup", "urllib", "urllib.request"), + MovedAttribute("URLopener", "urllib", "urllib.request"), + MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), + MovedAttribute("parse_http_list", "urllib2", "urllib.request"), + MovedAttribute("parse_keqv_list", "urllib2", "urllib.request"), +] +for attr in _urllib_request_moved_attributes: + setattr(Module_six_moves_urllib_request, attr.name, attr) +del attr + +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes + +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") + + +class Module_six_moves_urllib_response(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_response""" + + +_urllib_response_moved_attributes = [ + MovedAttribute("addbase", "urllib", "urllib.response"), + MovedAttribute("addclosehook", "urllib", "urllib.response"), + MovedAttribute("addinfo", "urllib", "urllib.response"), + MovedAttribute("addinfourl", "urllib", "urllib.response"), +] +for attr in _urllib_response_moved_attributes: + setattr(Module_six_moves_urllib_response, attr.name, attr) +del attr + +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") + + +class Module_six_moves_urllib_robotparser(_LazyModule): + + """Lazy loading of moved objects in six.moves.urllib_robotparser""" + + +_urllib_robotparser_moved_attributes = [ + MovedAttribute("RobotFileParser", "robotparser", "urllib.robotparser"), +] +for attr in _urllib_robotparser_moved_attributes: + setattr(Module_six_moves_urllib_robotparser, attr.name, attr) +del attr + +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") + + +class Module_six_moves_urllib(types.ModuleType): + + """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] + +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") + + +def add_move(move): + """Add an item to six.moves.""" + setattr(_MovedItems, move.name, move) + + +def remove_move(name): + """Remove item from six.moves.""" + try: + delattr(_MovedItems, name) + except AttributeError: + try: + del moves.__dict__[name] + except KeyError: + raise AttributeError("no such move, %r" % (name,)) + + +if PY3: + _meth_func = "__func__" + _meth_self = "__self__" + + _func_closure = "__closure__" + _func_code = "__code__" + _func_defaults = "__defaults__" + _func_globals = "__globals__" +else: + _meth_func = "im_func" + _meth_self = "im_self" + + _func_closure = "func_closure" + _func_code = "func_code" + _func_defaults = "func_defaults" + _func_globals = "func_globals" + + +try: + advance_iterator = next +except NameError: + def advance_iterator(it): + return it.next() +next = advance_iterator + + +try: + callable = callable +except NameError: + def callable(obj): + return any("__call__" in klass.__dict__ for klass in type(obj).__mro__) + + +if PY3: + def get_unbound_function(unbound): + return unbound + + create_bound_method = types.MethodType + + def create_unbound_method(func, cls): + return func + + Iterator = object +else: + def get_unbound_function(unbound): + return unbound.im_func + + def create_bound_method(func, obj): + return types.MethodType(func, obj, obj.__class__) + + def create_unbound_method(func, cls): + return types.MethodType(func, None, cls) + + class Iterator(object): + + def next(self): + return type(self).__next__(self) + + callable = callable +_add_doc(get_unbound_function, + """Get the function out of a possibly unbound function""") + + +get_method_function = operator.attrgetter(_meth_func) +get_method_self = operator.attrgetter(_meth_self) +get_function_closure = operator.attrgetter(_func_closure) +get_function_code = operator.attrgetter(_func_code) +get_function_defaults = operator.attrgetter(_func_defaults) +get_function_globals = operator.attrgetter(_func_globals) + + +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) + + viewkeys = operator.methodcaller("keys") + + viewvalues = operator.methodcaller("values") + + viewitems = operator.methodcaller("items") +else: + def iterkeys(d, **kw): + return d.iterkeys(**kw) + + def itervalues(d, **kw): + return d.itervalues(**kw) + + def iteritems(d, **kw): + return d.iteritems(**kw) + + def iterlists(d, **kw): + return d.iterlists(**kw) + + viewkeys = operator.methodcaller("viewkeys") + + viewvalues = operator.methodcaller("viewvalues") + + viewitems = operator.methodcaller("viewitems") + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") + + +if PY3: + def b(s): + return s.encode("latin-1") + + def u(s): + return s + unichr = chr + import struct + int2byte = struct.Struct(">B").pack + del struct + byte2int = operator.itemgetter(0) + indexbytes = operator.getitem + iterbytes = iter + import io + StringIO = io.StringIO + BytesIO = io.BytesIO + _assertCountEqual = "assertCountEqual" + if sys.version_info[1] <= 1: + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" + else: + _assertRaisesRegex = "assertRaisesRegex" + _assertRegex = "assertRegex" +else: + def b(s): + return s + # Workaround for standalone backslash + + def u(s): + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") + unichr = unichr + int2byte = chr + + def byte2int(bs): + return ord(bs[0]) + + def indexbytes(buf, i): + return ord(buf[i]) + iterbytes = functools.partial(itertools.imap, ord) + import StringIO + StringIO = BytesIO = StringIO.StringIO + _assertCountEqual = "assertItemsEqual" + _assertRaisesRegex = "assertRaisesRegexp" + _assertRegex = "assertRegexpMatches" +_add_doc(b, """Byte literal""") +_add_doc(u, """Text literal""") + + +def assertCountEqual(self, *args, **kwargs): + return getattr(self, _assertCountEqual)(*args, **kwargs) + + +def assertRaisesRegex(self, *args, **kwargs): + return getattr(self, _assertRaisesRegex)(*args, **kwargs) + + +def assertRegex(self, *args, **kwargs): + return getattr(self, _assertRegex)(*args, **kwargs) + + +if PY3: + exec_ = getattr(moves.builtins, "exec") + + def reraise(tp, value, tb=None): + try: + if value is None: + value = tp() + if value.__traceback__ is not tb: + raise value.with_traceback(tb) + raise value + finally: + value = None + tb = None + +else: + def exec_(_code_, _globs_=None, _locs_=None): + """Execute code in a namespace.""" + if _globs_ is None: + frame = sys._getframe(1) + _globs_ = frame.f_globals + if _locs_ is None: + _locs_ = frame.f_locals + del frame + elif _locs_ is None: + _locs_ = _globs_ + exec("""exec _code_ in _globs_, _locs_""") + + exec_("""def reraise(tp, value, tb=None): + try: + raise tp, value, tb + finally: + tb = None +""") + + +if sys.version_info[:2] == (3, 2): + exec_("""def raise_from(value, from_value): + try: + if from_value is None: + raise value + raise value from from_value + finally: + value = None +""") +elif sys.version_info[:2] > (3, 2): + exec_("""def raise_from(value, from_value): + try: + raise value from from_value + finally: + value = None +""") +else: + def raise_from(value, from_value): + raise value + + +print_ = getattr(moves.builtins, "print", None) +if print_ is None: + def print_(*args, **kwargs): + """The new-style print function for Python 2.4 and 2.5.""" + fp = kwargs.pop("file", sys.stdout) + if fp is None: + return + + def write(data): + if not isinstance(data, basestring): + data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) + fp.write(data) + want_unicode = False + sep = kwargs.pop("sep", None) + if sep is not None: + if isinstance(sep, unicode): + want_unicode = True + elif not isinstance(sep, str): + raise TypeError("sep must be None or a string") + end = kwargs.pop("end", None) + if end is not None: + if isinstance(end, unicode): + want_unicode = True + elif not isinstance(end, str): + raise TypeError("end must be None or a string") + if kwargs: + raise TypeError("invalid keyword arguments to print()") + if not want_unicode: + for arg in args: + if isinstance(arg, unicode): + want_unicode = True + break + if want_unicode: + newline = unicode("\n") + space = unicode(" ") + else: + newline = "\n" + space = " " + if sep is None: + sep = space + if end is None: + end = newline + for i, arg in enumerate(args): + if i: + write(sep) + write(arg) + write(end) +if sys.version_info[:2] < (3, 3): + _print = print_ + + def print_(*args, **kwargs): + fp = kwargs.get("file", sys.stdout) + flush = kwargs.pop("flush", False) + _print(*args, **kwargs) + if flush and fp is not None: + fp.flush() + +_add_doc(reraise, """Reraise an exception.""") + +if sys.version_info[0:2] < (3, 4): + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + def wrapper(f): + f = functools.wraps(wrapped, assigned, updated)(f) + f.__wrapped__ = wrapped + return f + return wrapper +else: + wraps = functools.wraps + + +def with_metaclass(meta, *bases): + """Create a base class with a metaclass.""" + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(type): + + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + + @classmethod + def __prepare__(cls, name, this_bases): + return meta.__prepare__(name, bases) + return type.__new__(metaclass, 'temporary_class', (), {}) + + +def add_metaclass(metaclass): + """Class decorator for creating a class with a metaclass.""" + def wrapper(cls): + orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) + orig_vars.pop('__dict__', None) + orig_vars.pop('__weakref__', None) + return metaclass(cls.__name__, cls.__bases__, orig_vars) + return wrapper + + +def python_2_unicode_compatible(klass): + """ + A decorator that defines __unicode__ and __str__ methods under Python 2. + Under Python 3 it does nothing. + + To support Python 2 and 3 with a single code base, define a __str__ method + returning text and apply this decorator to the class. + """ + if PY2: + if '__str__' not in klass.__dict__: + raise ValueError("@python_2_unicode_compatible cannot be applied " + "to %s because it doesn't define __str__()." % + klass.__name__) + klass.__unicode__ = klass.__str__ + klass.__str__ = lambda self: self.__unicode__().encode('utf-8') + return klass + + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/testbed/dpkp__kafka-python/kafka/vendor/socketpair.py b/testbed/dpkp__kafka-python/kafka/vendor/socketpair.py new file mode 100644 index 0000000000000000000000000000000000000000..b55e629ee2f3f846e5daa0e46759b6fa1fd2ecba --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/vendor/socketpair.py @@ -0,0 +1,58 @@ +# pylint: skip-file +# vendored from https://github.com/mhils/backports.socketpair +from __future__ import absolute_import + +import sys +import socket +import errno + +_LOCALHOST = '127.0.0.1' +_LOCALHOST_V6 = '::1' + +if not hasattr(socket, "socketpair"): + # Origin: https://gist.github.com/4325783, by Geert Jansen. Public domain. + def socketpair(family=socket.AF_INET, type=socket.SOCK_STREAM, proto=0): + if family == socket.AF_INET: + host = _LOCALHOST + elif family == socket.AF_INET6: + host = _LOCALHOST_V6 + else: + raise ValueError("Only AF_INET and AF_INET6 socket address families " + "are supported") + if type != socket.SOCK_STREAM: + raise ValueError("Only SOCK_STREAM socket type is supported") + if proto != 0: + raise ValueError("Only protocol zero is supported") + + # We create a connected TCP socket. Note the trick with + # setblocking(False) that prevents us from having to create a thread. + lsock = socket.socket(family, type, proto) + try: + lsock.bind((host, 0)) + lsock.listen(min(socket.SOMAXCONN, 128)) + # On IPv6, ignore flow_info and scope_id + addr, port = lsock.getsockname()[:2] + csock = socket.socket(family, type, proto) + try: + csock.setblocking(False) + if sys.version_info >= (3, 0): + try: + csock.connect((addr, port)) + except (BlockingIOError, InterruptedError): + pass + else: + try: + csock.connect((addr, port)) + except socket.error as e: + if e.errno != errno.WSAEWOULDBLOCK: + raise + csock.setblocking(True) + ssock, _ = lsock.accept() + except Exception: + csock.close() + raise + finally: + lsock.close() + return (ssock, csock) + + socket.socketpair = socketpair diff --git a/testbed/dpkp__kafka-python/kafka/version.py b/testbed/dpkp__kafka-python/kafka/version.py new file mode 100644 index 0000000000000000000000000000000000000000..06306bd1f68e523ab9b0bae13a5ed8200f44cff8 --- /dev/null +++ b/testbed/dpkp__kafka-python/kafka/version.py @@ -0,0 +1 @@ +__version__ = '2.0.3-dev' diff --git a/testbed/dpkp__kafka-python/pylint.rc b/testbed/dpkp__kafka-python/pylint.rc new file mode 100644 index 0000000000000000000000000000000000000000..851275bccaf1242f75f8d41f6ac29894d74e66cd --- /dev/null +++ b/testbed/dpkp__kafka-python/pylint.rc @@ -0,0 +1,7 @@ +[TYPECHECK] +ignored-classes=SyncManager,_socketobject +ignored-modules=kafka.vendor.six.moves +generated-members=py.* + +[MESSAGES CONTROL] +disable=E1129 diff --git a/testbed/dpkp__kafka-python/requirements-dev.txt b/testbed/dpkp__kafka-python/requirements-dev.txt new file mode 100644 index 0000000000000000000000000000000000000000..00ad68c2272b9989b27d5cb1aaaf675a4fb7b65b --- /dev/null +++ b/testbed/dpkp__kafka-python/requirements-dev.txt @@ -0,0 +1,17 @@ +coveralls==2.1.2 +crc32c==2.1 +docker-py==1.10.6 +flake8==3.8.3 +lz4==3.1.0 +mock==4.0.2 +py==1.9.0 +pylint==2.6.0 +pytest==6.0.2 +pytest-cov==2.10.1 +pytest-mock==3.3.1 +pytest-pylint==0.17.0 +python-snappy==0.5.4 +Sphinx==3.2.1 +sphinx-rtd-theme==0.5.0 +tox==3.20.0 +xxhash==2.0.0 diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..daab312b0e5f42ae7f541f06d6f3279bd476fad3 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/kafka.properties @@ -0,0 +1,144 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..daab312b0e5f42ae7f541f06d6f3279bd476fad3 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/kafka.properties @@ -0,0 +1,144 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.0.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..daab312b0e5f42ae7f541f06d6f3279bd476fad3 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/kafka.properties @@ -0,0 +1,144 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.1.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..daab312b0e5f42ae7f541f06d6f3279bd476fad3 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/kafka.properties @@ -0,0 +1,144 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..daab312b0e5f42ae7f541f06d6f3279bd476fad3 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/kafka.properties @@ -0,0 +1,144 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.10.2.2/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.2/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.11.0.3/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.8.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.8.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..b9f5c498fdd283ae453f8c9dd2aa54470a5bcca1 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.0/resources/kafka.properties @@ -0,0 +1,67 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +############################# Server Basics ############################# + +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +port={port} +host.name={host} + +num.network.threads=2 +num.io.threads=2 + +socket.send.buffer.bytes=1048576 +socket.receive.buffer.bytes=1048576 +socket.request.max.bytes=104857600 + +############################# Log Basics ############################# + +log.dirs={tmp_dir}/data +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +log.flush.interval.messages=10000 +log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +log.retention.hours=168 +log.segment.bytes=536870912 +log.cleanup.interval.mins=1 + +############################# Zookeeper ############################# + +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 + +kafka.metrics.polling.interval.secs=5 +kafka.metrics.reporters=kafka.metrics.KafkaCSVMetricsReporter +kafka.csv.metrics.dir={tmp_dir} +kafka.csv.metrics.reporter.enabled=false + +log.cleanup.policy=delete diff --git a/testbed/dpkp__kafka-python/servers/0.8.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.8.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.8.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.8.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..68e1ef98665d38805d68acd0d7762142e111ee8c --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.0/resources/zookeeper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +dataDir={tmp_dir} +clientPortAddress={host} +clientPort={port} +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..685aed15e9786f3e29c8754a87f0b7232e771509 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/kafka.properties @@ -0,0 +1,124 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +# The port the socket server listens on +port={port} + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +host.name={host} + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=2 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=1048576 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=1048576 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=536870912 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=60000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.1.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.8.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.8.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..76b0cb4acac961dbcd244f476de8dbfb2a2ee547 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.1/resources/kafka.properties @@ -0,0 +1,67 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +############################# Server Basics ############################# + +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +port={port} +host.name={host} + +num.network.threads=2 +num.io.threads=2 + +socket.send.buffer.bytes=1048576 +socket.receive.buffer.bytes=1048576 +socket.request.max.bytes=104857600 + +############################# Log Basics ############################# + +log.dirs={tmp_dir}/data +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +log.flush.interval.messages=10000 +log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +log.retention.hours=168 +log.segment.bytes=536870912 +log.retention.check.interval.ms=60000 +log.cleanup.interval.mins=1 +log.cleaner.enable=false + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.8.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.8.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.8.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.8.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..68e1ef98665d38805d68acd0d7762142e111ee8c --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.1/resources/zookeeper.properties @@ -0,0 +1,19 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +dataDir={tmp_dir} +clientPortAddress={host} +clientPort={port} +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..685aed15e9786f3e29c8754a87f0b7232e771509 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/kafka.properties @@ -0,0 +1,124 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +# The port the socket server listens on +port={port} + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +host.name={host} + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=2 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=1048576 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=1048576 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=536870912 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=60000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..685aed15e9786f3e29c8754a87f0b7232e771509 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/kafka.properties @@ -0,0 +1,124 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +# The port the socket server listens on +port={port} + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +host.name={host} + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=2 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=1048576 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=1048576 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=536870912 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=60000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..685aed15e9786f3e29c8754a87f0b7232e771509 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/kafka.properties @@ -0,0 +1,124 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +# The port the socket server listens on +port={port} + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +host.name={host} + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=2 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=1048576 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=1048576 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=536870912 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=60000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.8.2.2/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..fb859dd44d5c3a32d50f1071c8d0062a08c6d0c2 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/kafka.properties @@ -0,0 +1,141 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=536870912 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=60000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.9.0.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..28668db95a8b56ba9688d1d372b8794757d793e2 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/kafka.properties @@ -0,0 +1,142 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/0.9.0.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/1.0.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/1.0.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/1.0.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/1.0.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/1.0.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/1.0.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/1.0.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/1.0.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/1.0.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/1.0.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.1/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/1.0.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/1.0.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/1.0.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/1.0.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/1.0.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/1.0.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/1.0.2/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/1.0.2/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.2/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/1.0.2/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/1.0.2/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.2/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/1.0.2/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/1.0.2/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.2/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/1.0.2/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/1.0.2/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.0.2/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/1.1.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/1.1.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/1.1.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/1.1.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/1.1.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/1.1.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/1.1.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/1.1.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/1.1.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/1.1.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.1/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/1.1.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/1.1.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/1.1.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/1.1.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/1.1.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/1.1.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/1.1.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.0.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.0.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.0.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.0.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.0.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.0.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.0.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.0.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.0.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.0.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.1/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.0.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.0.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.0.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.0.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.0.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.0.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.0.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.1.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.1.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.1.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.1.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.1.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.1.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.1.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.1.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.1.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.1.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.1/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.1.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.1.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.1.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.1.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.1.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.1.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.1.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.2.1/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.2.1/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.2.1/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.2.1/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.2.1/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.2.1/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.2.1/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.2.1/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.2.1/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.2.1/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.2.1/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.2.1/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.3.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.3.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.3.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.3.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.3.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.3.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.3.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.3.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.3.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.3.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.3.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.3.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.4.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.4.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.4.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.4.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.4.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.4.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.4.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.4.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.4.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.4.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.4.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.4.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.5.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.5.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.5.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.5.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.5.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.5.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/2.5.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.5.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.5.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.5.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.5.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.5.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/2.6.0/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/2.6.0/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..5775cfdc4a000d94d730de3e4222b8b4f6d8f5d4 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.6.0/resources/kafka.properties @@ -0,0 +1,147 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +listeners={transport}://{host}:{port} +security.inter.broker.protocol={transport} + +{sasl_config} + +ssl.keystore.location={ssl_dir}/kafka.server.keystore.jks +ssl.keystore.password=foobar +ssl.key.password=foobar +ssl.truststore.location={ssl_dir}/kafka.server.truststore.jks +ssl.truststore.password=foobar + +authorizer.class.name=kafka.security.auth.SimpleAclAuthorizer +allow.everyone.if.no.acl.found=true + +# The port the socket server listens on +#port=9092 + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +#host.name=localhost + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=3 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=102400 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=102400 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +## Short Replica Lag -- Drops failed brokers out of ISR +replica.lag.time.max.ms=1000 +replica.socket.timeout.ms=1000 + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=1073741824 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=300000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +# tune down offset topics to reduce setup time in tests +offsets.commit.timeout.ms=500 +offsets.topic.num.partitions=2 +offsets.topic.replication.factor=1 + +# Allow shorter session timeouts for tests +group.min.session.timeout.ms=1000 + + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=30000 +# We want to expire kafka broker sessions quickly when brokers die b/c we restart them quickly +zookeeper.session.timeout.ms=500 diff --git a/testbed/dpkp__kafka-python/servers/2.6.0/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/2.6.0/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..af4306c86745bdbf2811cc6c89695a3112914909 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.6.0/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; diff --git a/testbed/dpkp__kafka-python/servers/2.6.0/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/2.6.0/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..b0b76aa79830b610a641a6a99ac36533a07f9616 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.6.0/resources/log4j.properties @@ -0,0 +1,25 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout, logfile + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.appender.logfile=org.apache.log4j.FileAppender +log4j.appender.logfile.File=${kafka.logs.dir}/server.log +log4j.appender.logfile.layout=org.apache.log4j.PatternLayout +log4j.appender.logfile.layout.ConversionPattern=[%d] %p %m (%c)%n diff --git a/testbed/dpkp__kafka-python/servers/2.6.0/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/2.6.0/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/2.6.0/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/servers/trunk/resources/kafka.properties b/testbed/dpkp__kafka-python/servers/trunk/resources/kafka.properties new file mode 100644 index 0000000000000000000000000000000000000000..a638f394a544db7f5e2aba6e6f07875c14919047 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/trunk/resources/kafka.properties @@ -0,0 +1,118 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# see kafka.server.KafkaConfig for additional details and defaults + +############################# Server Basics ############################# + +# The id of the broker. This must be set to a unique integer for each broker. +broker.id={broker_id} + +############################# Socket Server Settings ############################# + +# The port the socket server listens on +port={port} + +# Hostname the broker will bind to. If not set, the server will bind to all interfaces +host.name={host} + +# Hostname the broker will advertise to producers and consumers. If not set, it uses the +# value for "host.name" if configured. Otherwise, it will use the value returned from +# java.net.InetAddress.getCanonicalHostName(). +#advertised.host.name= + +# The port to publish to ZooKeeper for clients to use. If this is not set, +# it will publish the same port that the broker binds to. +#advertised.port= + +# The number of threads handling network requests +num.network.threads=2 + +# The number of threads doing disk I/O +num.io.threads=8 + +# The send buffer (SO_SNDBUF) used by the socket server +socket.send.buffer.bytes=1048576 + +# The receive buffer (SO_RCVBUF) used by the socket server +socket.receive.buffer.bytes=1048576 + +# The maximum size of a request that the socket server will accept (protection against OOM) +socket.request.max.bytes=104857600 + + +############################# Log Basics ############################# + +# A comma seperated list of directories under which to store log files +log.dirs={tmp_dir}/data + +# The default number of log partitions per topic. More partitions allow greater +# parallelism for consumption, but this will also result in more files across +# the brokers. +num.partitions={partitions} +default.replication.factor={replicas} + +############################# Log Flush Policy ############################# + +# Messages are immediately written to the filesystem but by default we only fsync() to sync +# the OS cache lazily. The following configurations control the flush of data to disk. +# There are a few important trade-offs here: +# 1. Durability: Unflushed data may be lost if you are not using replication. +# 2. Latency: Very large flush intervals may lead to latency spikes when the flush does occur as there will be a lot of data to flush. +# 3. Throughput: The flush is generally the most expensive operation, and a small flush interval may lead to exceessive seeks. +# The settings below allow one to configure the flush policy to flush data after a period of time or +# every N messages (or both). This can be done globally and overridden on a per-topic basis. + +# The number of messages to accept before forcing a flush of data to disk +#log.flush.interval.messages=10000 + +# The maximum amount of time a message can sit in a log before we force a flush +#log.flush.interval.ms=1000 + +############################# Log Retention Policy ############################# + +# The following configurations control the disposal of log segments. The policy can +# be set to delete segments after a period of time, or after a given size has accumulated. +# A segment will be deleted whenever *either* of these criteria are met. Deletion always happens +# from the end of the log. + +# The minimum age of a log file to be eligible for deletion +log.retention.hours=168 + +# A size-based retention policy for logs. Segments are pruned from the log as long as the remaining +# segments don't drop below log.retention.bytes. +#log.retention.bytes=1073741824 + +# The maximum size of a log segment file. When this size is reached a new log segment will be created. +log.segment.bytes=536870912 + +# The interval at which log segments are checked to see if they can be deleted according +# to the retention policies +log.retention.check.interval.ms=60000 + +# By default the log cleaner is disabled and the log retention policy will default to just delete segments after their retention expires. +# If log.cleaner.enable=true is set the cleaner will be enabled and individual logs can then be marked for log compaction. +log.cleaner.enable=false + +############################# Zookeeper ############################# + +# Zookeeper connection string (see zookeeper docs for details). +# This is a comma separated host:port pairs, each corresponding to a zk +# server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002". +# You can also append an optional chroot string to the urls to specify the +# root directory for all kafka znodes. +zookeeper.connect={zk_host}:{zk_port}/{zk_chroot} + +# Timeout in ms for connecting to zookeeper +zookeeper.connection.timeout.ms=1000000 diff --git a/testbed/dpkp__kafka-python/servers/trunk/resources/kafka_server_jaas.conf b/testbed/dpkp__kafka-python/servers/trunk/resources/kafka_server_jaas.conf new file mode 100644 index 0000000000000000000000000000000000000000..18efe4369c04af46a83adcef14aff8fad41ea994 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/trunk/resources/kafka_server_jaas.conf @@ -0,0 +1,4 @@ +KafkaServer {{ + {jaas_config} +}}; +Client {{}}; \ No newline at end of file diff --git a/testbed/dpkp__kafka-python/servers/trunk/resources/log4j.properties b/testbed/dpkp__kafka-python/servers/trunk/resources/log4j.properties new file mode 100644 index 0000000000000000000000000000000000000000..f863b3bd7d2dead3e07b824100f9eb52c4805c31 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/trunk/resources/log4j.properties @@ -0,0 +1,24 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. + +log4j.rootLogger=INFO, stdout + +log4j.appender.stdout=org.apache.log4j.ConsoleAppender +log4j.appender.stdout.layout=org.apache.log4j.PatternLayout +log4j.appender.stdout.layout.ConversionPattern=[%d] %p %m (%c)%n + +log4j.logger.kafka=DEBUG, stdout +log4j.logger.org.I0Itec.zkclient.ZkClient=INFO, stdout +log4j.logger.org.apache.zookeeper=INFO, stdout diff --git a/testbed/dpkp__kafka-python/servers/trunk/resources/zookeeper.properties b/testbed/dpkp__kafka-python/servers/trunk/resources/zookeeper.properties new file mode 100644 index 0000000000000000000000000000000000000000..e3fd0974290a29ab335526a57238c2b82c07e756 --- /dev/null +++ b/testbed/dpkp__kafka-python/servers/trunk/resources/zookeeper.properties @@ -0,0 +1,21 @@ +# Licensed to the Apache Software Foundation (ASF) under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You 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. +# the directory where the snapshot is stored. +dataDir={tmp_dir} +# the port at which the clients will connect +clientPort={port} +clientPortAddress={host} +# disable the per-ip limit on the number of connections since this is a non-production config +maxClientCnxns=0 diff --git a/testbed/dpkp__kafka-python/setup.cfg b/testbed/dpkp__kafka-python/setup.cfg new file mode 100644 index 0000000000000000000000000000000000000000..5c6311daf8ff59a9699c660d006da4dbccea8458 --- /dev/null +++ b/testbed/dpkp__kafka-python/setup.cfg @@ -0,0 +1,5 @@ +[bdist_wheel] +universal=1 + +[metadata] +license_file = LICENSE diff --git a/testbed/dpkp__kafka-python/setup.py b/testbed/dpkp__kafka-python/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..fe8a594f331fc4a6ab2f7607d859610ec3d11c8d --- /dev/null +++ b/testbed/dpkp__kafka-python/setup.py @@ -0,0 +1,70 @@ +import os +import sys + +from setuptools import setup, Command, find_packages + +# Pull version from source without importing +# since we can't import something we haven't built yet :) +exec(open('kafka/version.py').read()) + + +class Tox(Command): + + user_options = [] + + def initialize_options(self): + pass + + def finalize_options(self): + pass + + @classmethod + def run(cls): + import tox + sys.exit(tox.cmdline([])) + + +test_require = ['tox', 'mock'] + +here = os.path.abspath(os.path.dirname(__file__)) + +with open(os.path.join(here, 'README.rst')) as f: + README = f.read() + +setup( + name="kafka-python", + version=__version__, + + tests_require=test_require, + extras_require={ + "crc32c": ["crc32c"], + "lz4": ["lz4"], + "snappy": ["python-snappy"], + "zstd": ["python-zstandard"], + }, + cmdclass={"test": Tox}, + packages=find_packages(exclude=['test']), + author="Dana Powers", + author_email="dana.powers@gmail.com", + url="https://github.com/dpkp/kafka-python", + license="Apache License 2.0", + description="Pure Python client for Apache Kafka", + long_description=README, + keywords="apache kafka", + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: Apache Software License", + "Programming Language :: Python", + "Programming Language :: Python :: 2", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.4", + "Programming Language :: Python :: 3.5", + "Programming Language :: Python :: 3.6", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: Implementation :: PyPy", + "Topic :: Software Development :: Libraries :: Python Modules", + ] +) diff --git a/testbed/dpkp__kafka-python/test/__init__.py b/testbed/dpkp__kafka-python/test/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..329277dc6390d16931e571b074f46644700e44a2 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/__init__.py @@ -0,0 +1,8 @@ +from __future__ import absolute_import + +# Set default logging handler to avoid "No handler found" warnings. +import logging +logging.basicConfig(level=logging.INFO) + +from kafka.future import Future +Future.error_on_callbacks = True # always fail during testing diff --git a/testbed/dpkp__kafka-python/test/conftest.py b/testbed/dpkp__kafka-python/test/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa0262fd8906e49e6df864046be72379f3ad94b --- /dev/null +++ b/testbed/dpkp__kafka-python/test/conftest.py @@ -0,0 +1,175 @@ +from __future__ import absolute_import + +import uuid + +import pytest + +from test.testutil import env_kafka_version, random_string +from test.fixtures import KafkaFixture, ZookeeperFixture + +@pytest.fixture(scope="module") +def zookeeper(): + """Return a Zookeeper fixture""" + zk_instance = ZookeeperFixture.instance() + yield zk_instance + zk_instance.close() + + +@pytest.fixture(scope="module") +def kafka_broker(kafka_broker_factory): + """Return a Kafka broker fixture""" + return kafka_broker_factory()[0] + + +@pytest.fixture(scope="module") +def kafka_broker_factory(zookeeper): + """Return a Kafka broker fixture factory""" + assert env_kafka_version(), 'KAFKA_VERSION must be specified to run integration tests' + + _brokers = [] + def factory(**broker_params): + params = {} if broker_params is None else broker_params.copy() + params.setdefault('partitions', 4) + num_brokers = params.pop('num_brokers', 1) + brokers = tuple(KafkaFixture.instance(x, zookeeper, **params) + for x in range(num_brokers)) + _brokers.extend(brokers) + return brokers + + yield factory + + for broker in _brokers: + broker.close() + + +@pytest.fixture +def kafka_client(kafka_broker, request): + """Return a KafkaClient fixture""" + (client,) = kafka_broker.get_clients(cnt=1, client_id='%s_client' % (request.node.name,)) + yield client + client.close() + + +@pytest.fixture +def kafka_consumer(kafka_consumer_factory): + """Return a KafkaConsumer fixture""" + return kafka_consumer_factory() + + +@pytest.fixture +def kafka_consumer_factory(kafka_broker, topic, request): + """Return a KafkaConsumer factory fixture""" + _consumer = [None] + + def factory(**kafka_consumer_params): + params = {} if kafka_consumer_params is None else kafka_consumer_params.copy() + params.setdefault('client_id', 'consumer_%s' % (request.node.name,)) + params.setdefault('auto_offset_reset', 'earliest') + _consumer[0] = next(kafka_broker.get_consumers(cnt=1, topics=[topic], **params)) + return _consumer[0] + + yield factory + + if _consumer[0]: + _consumer[0].close() + + +@pytest.fixture +def kafka_producer(kafka_producer_factory): + """Return a KafkaProducer fixture""" + yield kafka_producer_factory() + + +@pytest.fixture +def kafka_producer_factory(kafka_broker, request): + """Return a KafkaProduce factory fixture""" + _producer = [None] + + def factory(**kafka_producer_params): + params = {} if kafka_producer_params is None else kafka_producer_params.copy() + params.setdefault('client_id', 'producer_%s' % (request.node.name,)) + _producer[0] = next(kafka_broker.get_producers(cnt=1, **params)) + return _producer[0] + + yield factory + + if _producer[0]: + _producer[0].close() + +@pytest.fixture +def kafka_admin_client(kafka_admin_client_factory): + """Return a KafkaAdminClient fixture""" + yield kafka_admin_client_factory() + +@pytest.fixture +def kafka_admin_client_factory(kafka_broker): + """Return a KafkaAdminClient factory fixture""" + _admin_client = [None] + + def factory(**kafka_admin_client_params): + params = {} if kafka_admin_client_params is None else kafka_admin_client_params.copy() + _admin_client[0] = next(kafka_broker.get_admin_clients(cnt=1, **params)) + return _admin_client[0] + + yield factory + + if _admin_client[0]: + _admin_client[0].close() + +@pytest.fixture +def topic(kafka_broker, request): + """Return a topic fixture""" + topic_name = '%s_%s' % (request.node.name, random_string(10)) + kafka_broker.create_topics([topic_name]) + return topic_name + + +@pytest.fixture +def conn(mocker): + """Return a connection mocker fixture""" + from kafka.conn import ConnectionStates + from kafka.future import Future + from kafka.protocol.metadata import MetadataResponse + conn = mocker.patch('kafka.client_async.BrokerConnection') + conn.return_value = conn + conn.state = ConnectionStates.CONNECTED + conn.send.return_value = Future().success( + MetadataResponse[0]( + [(0, 'foo', 12), (1, 'bar', 34)], # brokers + [])) # topics + conn.blacked_out.return_value = False + def _set_conn_state(state): + conn.state = state + return state + conn._set_conn_state = _set_conn_state + conn.connect.side_effect = lambda: conn.state + conn.connect_blocking.return_value = True + conn.connecting = lambda: conn.state in (ConnectionStates.CONNECTING, + ConnectionStates.HANDSHAKE) + conn.connected = lambda: conn.state is ConnectionStates.CONNECTED + conn.disconnected = lambda: conn.state is ConnectionStates.DISCONNECTED + return conn + + +@pytest.fixture() +def send_messages(topic, kafka_producer, request): + """A factory that returns a send_messages function with a pre-populated + topic topic / producer.""" + + def _send_messages(number_range, partition=0, topic=topic, producer=kafka_producer, request=request): + """ + messages is typically `range(0,100)` + partition is an int + """ + messages_and_futures = [] # [(message, produce_future),] + for i in number_range: + # request.node.name provides the test name (including parametrized values) + encoded_msg = '{}-{}-{}'.format(i, request.node.name, uuid.uuid4()).encode('utf-8') + future = kafka_producer.send(topic, value=encoded_msg, partition=partition) + messages_and_futures.append((encoded_msg, future)) + kafka_producer.flush() + for (msg, f) in messages_and_futures: + assert f.succeeded() + return [msg for (msg, f) in messages_and_futures] + + return _send_messages diff --git a/testbed/dpkp__kafka-python/test/fixtures.py b/testbed/dpkp__kafka-python/test/fixtures.py new file mode 100644 index 0000000000000000000000000000000000000000..26fb5e89d669cba967b383ad58b981ff35298f15 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/fixtures.py @@ -0,0 +1,673 @@ +from __future__ import absolute_import + +import atexit +import logging +import os +import os.path +import socket +import subprocess +import time +import uuid + +import py +from kafka.vendor.six.moves import urllib, range +from kafka.vendor.six.moves.urllib.parse import urlparse # pylint: disable=E0611,F0401 + +from kafka import errors, KafkaAdminClient, KafkaClient, KafkaConsumer, KafkaProducer +from kafka.errors import InvalidReplicationFactorError +from kafka.protocol.admin import CreateTopicsRequest +from kafka.protocol.metadata import MetadataRequest +from test.testutil import env_kafka_version, random_string +from test.service import ExternalService, SpawnedService + +log = logging.getLogger(__name__) + + +def get_open_port(): + sock = socket.socket() + sock.bind(("", 0)) + port = sock.getsockname()[1] + sock.close() + return port + + +def gen_ssl_resources(directory): + os.system(""" + cd {0} + echo Generating SSL resources in {0} + + # Step 1 + keytool -keystore kafka.server.keystore.jks -alias localhost -validity 1 \ + -genkey -storepass foobar -keypass foobar \ + -dname "CN=localhost, OU=kafka-python, O=kafka-python, L=SF, ST=CA, C=US" \ + -ext SAN=dns:localhost + + # Step 2 + openssl genrsa -out ca-key 2048 + openssl req -new -x509 -key ca-key -out ca-cert -days 1 \ + -subj "/C=US/ST=CA/O=MyOrg, Inc./CN=mydomain.com" + keytool -keystore kafka.server.truststore.jks -alias CARoot -import \ + -file ca-cert -storepass foobar -noprompt + + # Step 3 + keytool -keystore kafka.server.keystore.jks -alias localhost -certreq \ + -file cert-file -storepass foobar + openssl x509 -req -CA ca-cert -CAkey ca-key -in cert-file -out cert-signed \ + -days 1 -CAcreateserial -passin pass:foobar + keytool -keystore kafka.server.keystore.jks -alias CARoot -import \ + -file ca-cert -storepass foobar -noprompt + keytool -keystore kafka.server.keystore.jks -alias localhost -import \ + -file cert-signed -storepass foobar -noprompt + """.format(directory)) + + +class Fixture(object): + kafka_version = os.environ.get('KAFKA_VERSION', '0.11.0.2') + scala_version = os.environ.get("SCALA_VERSION", '2.8.0') + project_root = os.environ.get('PROJECT_ROOT', + os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) + kafka_root = os.environ.get("KAFKA_ROOT", + os.path.join(project_root, 'servers', kafka_version, "kafka-bin")) + + def __init__(self): + self.child = None + + @classmethod + def download_official_distribution(cls, + kafka_version=None, + scala_version=None, + output_dir=None): + if not kafka_version: + kafka_version = cls.kafka_version + if not scala_version: + scala_version = cls.scala_version + if not output_dir: + output_dir = os.path.join(cls.project_root, 'servers', 'dist') + + distfile = 'kafka_%s-%s' % (scala_version, kafka_version,) + url_base = 'https://archive.apache.org/dist/kafka/%s/' % (kafka_version,) + output_file = os.path.join(output_dir, distfile + '.tgz') + + if os.path.isfile(output_file): + log.info("Found file already on disk: %s", output_file) + return output_file + + # New tarballs are .tgz, older ones are sometimes .tar.gz + try: + url = url_base + distfile + '.tgz' + log.info("Attempting to download %s", url) + response = urllib.request.urlopen(url) + except urllib.error.HTTPError: + log.exception("HTTP Error") + url = url_base + distfile + '.tar.gz' + log.info("Attempting to download %s", url) + response = urllib.request.urlopen(url) + + log.info("Saving distribution file to %s", output_file) + with open(output_file, 'w') as output_file_fd: + output_file_fd.write(response.read()) + + return output_file + + @classmethod + def test_resource(cls, filename): + return os.path.join(cls.project_root, "servers", cls.kafka_version, "resources", filename) + + @classmethod + def kafka_run_class_args(cls, *args): + result = [os.path.join(cls.kafka_root, 'bin', 'kafka-run-class.sh')] + result.extend([str(arg) for arg in args]) + return result + + def kafka_run_class_env(self): + env = os.environ.copy() + env['KAFKA_LOG4J_OPTS'] = "-Dlog4j.configuration=file:%s" % \ + (self.test_resource("log4j.properties"),) + return env + + @classmethod + def render_template(cls, source_file, target_file, binding): + log.info('Rendering %s from template %s', target_file.strpath, source_file) + with open(source_file, "r") as handle: + template = handle.read() + assert len(template) > 0, 'Empty template %s' % (source_file,) + with open(target_file.strpath, "w") as handle: + handle.write(template.format(**binding)) + handle.flush() + os.fsync(handle) + + # fsync directory for durability + # https://blog.gocept.com/2013/07/15/reliable-file-updates-with-python/ + dirfd = os.open(os.path.dirname(target_file.strpath), os.O_DIRECTORY) + os.fsync(dirfd) + os.close(dirfd) + log.debug("Template string:") + for line in template.splitlines(): + log.debug(' ' + line.strip()) + log.debug("Rendered template:") + with open(target_file.strpath, 'r') as o: + for line in o: + log.debug(' ' + line.strip()) + log.debug("binding:") + for key, value in binding.items(): + log.debug(" {key}={value}".format(key=key, value=value)) + + def dump_logs(self): + self.child.dump_logs() + + +class ZookeeperFixture(Fixture): + @classmethod + def instance(cls): + if "ZOOKEEPER_URI" in os.environ: + parse = urlparse(os.environ["ZOOKEEPER_URI"]) + (host, port) = (parse.hostname, parse.port) + fixture = ExternalService(host, port) + else: + (host, port) = ("127.0.0.1", None) + fixture = cls(host, port) + + fixture.open() + return fixture + + def __init__(self, host, port, tmp_dir=None): + super(ZookeeperFixture, self).__init__() + self.host = host + self.port = port + + self.tmp_dir = tmp_dir + + def kafka_run_class_env(self): + env = super(ZookeeperFixture, self).kafka_run_class_env() + env['LOG_DIR'] = self.tmp_dir.join('logs').strpath + return env + + def out(self, message): + log.info("*** Zookeeper [%s:%s]: %s", self.host, self.port or '(auto)', message) + + def open(self): + if self.tmp_dir is None: + self.tmp_dir = py.path.local.mkdtemp() #pylint: disable=no-member + self.tmp_dir.ensure(dir=True) + + self.out("Running local instance...") + log.info(" host = %s", self.host) + log.info(" port = %s", self.port or '(auto)') + log.info(" tmp_dir = %s", self.tmp_dir.strpath) + + # Configure Zookeeper child process + template = self.test_resource("zookeeper.properties") + properties = self.tmp_dir.join("zookeeper.properties") + args = self.kafka_run_class_args("org.apache.zookeeper.server.quorum.QuorumPeerMain", + properties.strpath) + env = self.kafka_run_class_env() + + # Party! + timeout = 5 + max_timeout = 120 + backoff = 1 + end_at = time.time() + max_timeout + tries = 1 + auto_port = (self.port is None) + while time.time() < end_at: + if auto_port: + self.port = get_open_port() + self.out('Attempting to start on port %d (try #%d)' % (self.port, tries)) + self.render_template(template, properties, vars(self)) + self.child = SpawnedService(args, env) + self.child.start() + timeout = min(timeout, max(end_at - time.time(), 0)) + if self.child.wait_for(r"binding to port", timeout=timeout): + break + self.child.dump_logs() + self.child.stop() + timeout *= 2 + time.sleep(backoff) + tries += 1 + backoff += 1 + else: + raise RuntimeError('Failed to start Zookeeper before max_timeout') + self.out("Done!") + atexit.register(self.close) + + def close(self): + if self.child is None: + return + self.out("Stopping...") + self.child.stop() + self.child = None + self.out("Done!") + self.tmp_dir.remove() + + def __del__(self): + self.close() + + +class KafkaFixture(Fixture): + broker_user = 'alice' + broker_password = 'alice-secret' + + @classmethod + def instance(cls, broker_id, zookeeper, zk_chroot=None, + host=None, port=None, + transport='PLAINTEXT', replicas=1, partitions=2, + sasl_mechanism=None, auto_create_topic=True, tmp_dir=None): + + if zk_chroot is None: + zk_chroot = "kafka-python_" + str(uuid.uuid4()).replace("-", "_") + if "KAFKA_URI" in os.environ: + parse = urlparse(os.environ["KAFKA_URI"]) + (host, port) = (parse.hostname, parse.port) + fixture = ExternalService(host, port) + else: + if host is None: + host = "localhost" + fixture = KafkaFixture(host, port, broker_id, + zookeeper, zk_chroot, + transport=transport, + replicas=replicas, partitions=partitions, + sasl_mechanism=sasl_mechanism, + auto_create_topic=auto_create_topic, + tmp_dir=tmp_dir) + + fixture.open() + return fixture + + def __init__(self, host, port, broker_id, zookeeper, zk_chroot, + replicas=1, partitions=2, transport='PLAINTEXT', + sasl_mechanism=None, auto_create_topic=True, + tmp_dir=None): + super(KafkaFixture, self).__init__() + + self.host = host + self.port = port + + self.broker_id = broker_id + self.auto_create_topic = auto_create_topic + self.transport = transport.upper() + if sasl_mechanism is not None: + self.sasl_mechanism = sasl_mechanism.upper() + else: + self.sasl_mechanism = None + self.ssl_dir = self.test_resource('ssl') + + # TODO: checking for port connection would be better than scanning logs + # until then, we need the pattern to work across all supported broker versions + # The logging format changed slightly in 1.0.0 + self.start_pattern = r"\[Kafka ?Server (id=)?%d\],? started" % (broker_id,) + # Need to wait until the broker has fetched user configs from zookeeper in case we use scram as sasl mechanism + self.scram_pattern = r"Removing Produce quota for user %s" % (self.broker_user) + + self.zookeeper = zookeeper + self.zk_chroot = zk_chroot + # Add the attributes below for the template binding + self.zk_host = self.zookeeper.host + self.zk_port = self.zookeeper.port + + self.replicas = replicas + self.partitions = partitions + + self.tmp_dir = tmp_dir + self.running = False + + self._client = None + self.sasl_config = '' + self.jaas_config = '' + + def _sasl_config(self): + if not self.sasl_enabled: + return '' + + sasl_config = ( + 'sasl.enabled.mechanisms={mechanism}\n' + 'sasl.mechanism.inter.broker.protocol={mechanism}\n' + ) + return sasl_config.format(mechanism=self.sasl_mechanism) + + def _jaas_config(self): + if not self.sasl_enabled: + return '' + + elif self.sasl_mechanism == 'PLAIN': + jaas_config = ( + 'org.apache.kafka.common.security.plain.PlainLoginModule required\n' + ' username="{user}" password="{password}" user_{user}="{password}";\n' + ) + elif self.sasl_mechanism in ("SCRAM-SHA-256", "SCRAM-SHA-512"): + jaas_config = ( + 'org.apache.kafka.common.security.scram.ScramLoginModule required\n' + ' username="{user}" password="{password}";\n' + ) + else: + raise ValueError("SASL mechanism {} currently not supported".format(self.sasl_mechanism)) + return jaas_config.format(user=self.broker_user, password=self.broker_password) + + def _add_scram_user(self): + self.out("Adding SCRAM credentials for user {} to zookeeper.".format(self.broker_user)) + args = self.kafka_run_class_args( + "kafka.admin.ConfigCommand", + "--zookeeper", + "%s:%d/%s" % (self.zookeeper.host, + self.zookeeper.port, + self.zk_chroot), + "--alter", + "--entity-type", "users", + "--entity-name", self.broker_user, + "--add-config", + "{}=[password={}]".format(self.sasl_mechanism, self.broker_password), + ) + env = self.kafka_run_class_env() + proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + stdout, stderr = proc.communicate() + + if proc.returncode != 0: + self.out("Failed to save credentials to zookeeper!") + self.out(stdout) + self.out(stderr) + raise RuntimeError("Failed to save credentials to zookeeper!") + self.out("User created.") + + @property + def sasl_enabled(self): + return self.sasl_mechanism is not None + + def bootstrap_server(self): + return '%s:%d' % (self.host, self.port) + + def kafka_run_class_env(self): + env = super(KafkaFixture, self).kafka_run_class_env() + env['LOG_DIR'] = self.tmp_dir.join('logs').strpath + return env + + def out(self, message): + log.info("*** Kafka [%s:%s]: %s", self.host, self.port or '(auto)', message) + + def _create_zk_chroot(self): + self.out("Creating Zookeeper chroot node...") + args = self.kafka_run_class_args("org.apache.zookeeper.ZooKeeperMain", + "-server", + "%s:%d" % (self.zookeeper.host, + self.zookeeper.port), + "create", + "/%s" % (self.zk_chroot,), + "kafka-python") + env = self.kafka_run_class_env() + proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + + stdout, stderr = proc.communicate() + + if proc.returncode != 0: + self.out("Failed to create Zookeeper chroot node") + self.out(stdout) + self.out(stderr) + raise RuntimeError("Failed to create Zookeeper chroot node") + self.out("Kafka chroot created in Zookeeper!") + + def start(self): + # Configure Kafka child process + properties = self.tmp_dir.join("kafka.properties") + jaas_conf = self.tmp_dir.join("kafka_server_jaas.conf") + properties_template = self.test_resource("kafka.properties") + jaas_conf_template = self.test_resource("kafka_server_jaas.conf") + + args = self.kafka_run_class_args("kafka.Kafka", properties.strpath) + env = self.kafka_run_class_env() + if self.sasl_enabled: + opts = env.get('KAFKA_OPTS', '').strip() + opts += ' -Djava.security.auth.login.config={}'.format(jaas_conf.strpath) + env['KAFKA_OPTS'] = opts + self.render_template(jaas_conf_template, jaas_conf, vars(self)) + + timeout = 5 + max_timeout = 120 + backoff = 1 + end_at = time.time() + max_timeout + tries = 1 + auto_port = (self.port is None) + while time.time() < end_at: + # We have had problems with port conflicts on travis + # so we will try a different port on each retry + # unless the fixture was passed a specific port + if auto_port: + self.port = get_open_port() + self.out('Attempting to start on port %d (try #%d)' % (self.port, tries)) + self.render_template(properties_template, properties, vars(self)) + + self.child = SpawnedService(args, env) + self.child.start() + timeout = min(timeout, max(end_at - time.time(), 0)) + if self._broker_ready(timeout) and self._scram_user_present(timeout): + break + + self.child.dump_logs() + self.child.stop() + + timeout *= 2 + time.sleep(backoff) + tries += 1 + backoff += 1 + else: + raise RuntimeError('Failed to start KafkaInstance before max_timeout') + + (self._client,) = self.get_clients(1, client_id='_internal_client') + + self.out("Done!") + self.running = True + + def _broker_ready(self, timeout): + return self.child.wait_for(self.start_pattern, timeout=timeout) + + def _scram_user_present(self, timeout): + # no need to wait for scram user if scram is not used + if not self.sasl_enabled or not self.sasl_mechanism.startswith('SCRAM-SHA-'): + return True + return self.child.wait_for(self.scram_pattern, timeout=timeout) + + def open(self): + if self.running: + self.out("Instance already running") + return + + # Create directories + if self.tmp_dir is None: + self.tmp_dir = py.path.local.mkdtemp() #pylint: disable=no-member + self.tmp_dir.ensure(dir=True) + self.tmp_dir.ensure('logs', dir=True) + self.tmp_dir.ensure('data', dir=True) + + self.out("Running local instance...") + log.info(" host = %s", self.host) + log.info(" port = %s", self.port or '(auto)') + log.info(" transport = %s", self.transport) + log.info(" sasl_mechanism = %s", self.sasl_mechanism) + log.info(" broker_id = %s", self.broker_id) + log.info(" zk_host = %s", self.zookeeper.host) + log.info(" zk_port = %s", self.zookeeper.port) + log.info(" zk_chroot = %s", self.zk_chroot) + log.info(" replicas = %s", self.replicas) + log.info(" partitions = %s", self.partitions) + log.info(" tmp_dir = %s", self.tmp_dir.strpath) + + self._create_zk_chroot() + self.sasl_config = self._sasl_config() + self.jaas_config = self._jaas_config() + # add user to zookeeper for the first server + if self.sasl_enabled and self.sasl_mechanism.startswith("SCRAM-SHA") and self.broker_id == 0: + self._add_scram_user() + self.start() + + atexit.register(self.close) + + def __del__(self): + self.close() + + def stop(self): + if not self.running: + self.out("Instance already stopped") + return + + self.out("Stopping...") + self.child.stop() + self.child = None + self.running = False + self.out("Stopped!") + + def close(self): + self.stop() + if self.tmp_dir is not None: + self.tmp_dir.remove() + self.tmp_dir = None + self.out("Done!") + + def dump_logs(self): + super(KafkaFixture, self).dump_logs() + self.zookeeper.dump_logs() + + def _send_request(self, request, timeout=None): + def _failure(error): + raise error + retries = 10 + while True: + node_id = self._client.least_loaded_node() + for connect_retry in range(40): + self._client.maybe_connect(node_id) + if self._client.connected(node_id): + break + self._client.poll(timeout_ms=100) + else: + raise RuntimeError('Could not connect to broker with node id %d' % (node_id,)) + + try: + future = self._client.send(node_id, request) + future.error_on_callbacks = True + future.add_errback(_failure) + self._client.poll(future=future, timeout_ms=timeout) + return future.value + except Exception as exc: + time.sleep(1) + retries -= 1 + if retries == 0: + raise exc + else: + pass # retry + + def _create_topic(self, topic_name, num_partitions=None, replication_factor=None, timeout_ms=10000): + if num_partitions is None: + num_partitions = self.partitions + if replication_factor is None: + replication_factor = self.replicas + + # Try different methods to create a topic, from the fastest to the slowest + if self.auto_create_topic and num_partitions == self.partitions and replication_factor == self.replicas: + self._create_topic_via_metadata(topic_name, timeout_ms) + elif env_kafka_version() >= (0, 10, 1, 0): + try: + self._create_topic_via_admin_api(topic_name, num_partitions, replication_factor, timeout_ms) + except InvalidReplicationFactorError: + # wait and try again + # on travis the brokers sometimes take a while to find themselves + time.sleep(0.5) + self._create_topic_via_admin_api(topic_name, num_partitions, replication_factor, timeout_ms) + else: + self._create_topic_via_cli(topic_name, num_partitions, replication_factor) + + def _create_topic_via_metadata(self, topic_name, timeout_ms=10000): + self._send_request(MetadataRequest[0]([topic_name]), timeout_ms) + + def _create_topic_via_admin_api(self, topic_name, num_partitions, replication_factor, timeout_ms=10000): + request = CreateTopicsRequest[0]([(topic_name, num_partitions, + replication_factor, [], [])], timeout_ms) + response = self._send_request(request, timeout=timeout_ms) + for topic_result in response.topic_errors: + error_code = topic_result[1] + if error_code != 0: + raise errors.for_code(error_code) + + def _create_topic_via_cli(self, topic_name, num_partitions, replication_factor): + args = self.kafka_run_class_args('kafka.admin.TopicCommand', + '--zookeeper', '%s:%s/%s' % (self.zookeeper.host, + self.zookeeper.port, + self.zk_chroot), + '--create', + '--topic', topic_name, + '--partitions', self.partitions \ + if num_partitions is None else num_partitions, + '--replication-factor', self.replicas \ + if replication_factor is None \ + else replication_factor) + if env_kafka_version() >= (0, 10): + args.append('--if-not-exists') + env = self.kafka_run_class_env() + proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = proc.communicate() + if proc.returncode != 0: + if 'kafka.common.TopicExistsException' not in stdout: + self.out("Failed to create topic %s" % (topic_name,)) + self.out(stdout) + self.out(stderr) + raise RuntimeError("Failed to create topic %s" % (topic_name,)) + + def get_topic_names(self): + args = self.kafka_run_class_args('kafka.admin.TopicCommand', + '--zookeeper', '%s:%s/%s' % (self.zookeeper.host, + self.zookeeper.port, + self.zk_chroot), + '--list' + ) + env = self.kafka_run_class_env() + env.pop('KAFKA_LOG4J_OPTS') + proc = subprocess.Popen(args, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE) + stdout, stderr = proc.communicate() + if proc.returncode != 0: + self.out("Failed to list topics!") + self.out(stdout) + self.out(stderr) + raise RuntimeError("Failed to list topics!") + return stdout.decode().splitlines(False) + + def create_topics(self, topic_names, num_partitions=None, replication_factor=None): + for topic_name in topic_names: + self._create_topic(topic_name, num_partitions, replication_factor) + + def _enrich_client_params(self, params, **defaults): + params = params.copy() + for key, value in defaults.items(): + params.setdefault(key, value) + params.setdefault('bootstrap_servers', self.bootstrap_server()) + if self.sasl_enabled: + params.setdefault('sasl_mechanism', self.sasl_mechanism) + params.setdefault('security_protocol', self.transport) + if self.sasl_mechanism in ('PLAIN', 'SCRAM-SHA-256', 'SCRAM-SHA-512'): + params.setdefault('sasl_plain_username', self.broker_user) + params.setdefault('sasl_plain_password', self.broker_password) + return params + + @staticmethod + def _create_many_clients(cnt, cls, *args, **params): + client_id = params['client_id'] + for _ in range(cnt): + params['client_id'] = '%s_%s' % (client_id, random_string(4)) + yield cls(*args, **params) + + def get_clients(self, cnt=1, **params): + params = self._enrich_client_params(params, client_id='client') + for client in self._create_many_clients(cnt, KafkaClient, **params): + yield client + + def get_admin_clients(self, cnt, **params): + params = self._enrich_client_params(params, client_id='admin_client') + for client in self._create_many_clients(cnt, KafkaAdminClient, **params): + yield client + + def get_consumers(self, cnt, topics, **params): + params = self._enrich_client_params( + params, client_id='consumer', heartbeat_interval_ms=500, auto_offset_reset='earliest' + ) + for client in self._create_many_clients(cnt, KafkaConsumer, *topics, **params): + yield client + + def get_producers(self, cnt, **params): + params = self._enrich_client_params(params, client_id='producer') + for client in self._create_many_clients(cnt, KafkaProducer, **params): + yield client diff --git a/testbed/dpkp__kafka-python/test/record/test_default_records.py b/testbed/dpkp__kafka-python/test/record/test_default_records.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a7b02c8b0d1fd54120ccd2198c862935f1e63c --- /dev/null +++ b/testbed/dpkp__kafka-python/test/record/test_default_records.py @@ -0,0 +1,208 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +import pytest +from mock import patch +import kafka.codec +from kafka.record.default_records import ( + DefaultRecordBatch, DefaultRecordBatchBuilder +) +from kafka.errors import UnsupportedCodecError + + +@pytest.mark.parametrize("compression_type", [ + DefaultRecordBatch.CODEC_NONE, + DefaultRecordBatch.CODEC_GZIP, + DefaultRecordBatch.CODEC_SNAPPY, + DefaultRecordBatch.CODEC_LZ4 +]) +def test_read_write_serde_v2(compression_type): + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=compression_type, is_transactional=1, + producer_id=123456, producer_epoch=123, base_sequence=9999, + batch_size=999999) + headers = [("header1", b"aaa"), ("header2", b"bbb")] + for offset in range(10): + builder.append( + offset, timestamp=9999999, key=b"test", value=b"Super", + headers=headers) + buffer = builder.build() + reader = DefaultRecordBatch(bytes(buffer)) + msgs = list(reader) + + assert reader.is_transactional is True + assert reader.compression_type == compression_type + assert reader.magic == 2 + assert reader.timestamp_type == 0 + assert reader.base_offset == 0 + for offset, msg in enumerate(msgs): + assert msg.offset == offset + assert msg.timestamp == 9999999 + assert msg.key == b"test" + assert msg.value == b"Super" + assert msg.headers == headers + + +def test_written_bytes_equals_size_in_bytes_v2(): + key = b"test" + value = b"Super" + headers = [("header1", b"aaa"), ("header2", b"bbb"), ("xx", None)] + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=0, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=999999) + + size_in_bytes = builder.size_in_bytes( + 0, timestamp=9999999, key=key, value=value, headers=headers) + + pos = builder.size() + meta = builder.append( + 0, timestamp=9999999, key=key, value=value, headers=headers) + + assert builder.size() - pos == size_in_bytes + assert meta.size == size_in_bytes + + +def test_estimate_size_in_bytes_bigger_than_batch_v2(): + key = b"Super Key" + value = b"1" * 100 + headers = [("header1", b"aaa"), ("header2", b"bbb")] + estimate_size = DefaultRecordBatchBuilder.estimate_size_in_bytes( + key, value, headers) + + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=0, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=999999) + builder.append( + 0, timestamp=9999999, key=key, value=value, headers=headers) + buf = builder.build() + assert len(buf) <= estimate_size, \ + "Estimate should always be upper bound" + + +def test_default_batch_builder_validates_arguments(): + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=0, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=999999) + + # Key should not be str + with pytest.raises(TypeError): + builder.append( + 0, timestamp=9999999, key="some string", value=None, headers=[]) + + # Value should not be str + with pytest.raises(TypeError): + builder.append( + 0, timestamp=9999999, key=None, value="some string", headers=[]) + + # Timestamp should be of proper type + with pytest.raises(TypeError): + builder.append( + 0, timestamp="1243812793", key=None, value=b"some string", + headers=[]) + + # Offset of invalid type + with pytest.raises(TypeError): + builder.append( + "0", timestamp=9999999, key=None, value=b"some string", headers=[]) + + # Ok to pass value as None + builder.append( + 0, timestamp=9999999, key=b"123", value=None, headers=[]) + + # Timestamp can be None + builder.append( + 1, timestamp=None, key=None, value=b"some string", headers=[]) + + # Ok to pass offsets in not incremental order. This should not happen thou + builder.append( + 5, timestamp=9999999, key=b"123", value=None, headers=[]) + + # Check record with headers + builder.append( + 6, timestamp=9999999, key=b"234", value=None, headers=[("hkey", b"hval")]) + + # in case error handling code fails to fix inner buffer in builder + assert len(builder.build()) == 124 + + +def test_default_correct_metadata_response(): + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=0, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=1024 * 1024) + meta = builder.append( + 0, timestamp=9999999, key=b"test", value=b"Super", headers=[]) + + assert meta.offset == 0 + assert meta.timestamp == 9999999 + assert meta.crc is None + assert meta.size == 16 + assert repr(meta) == ( + "DefaultRecordMetadata(offset=0, size={}, timestamp={})" + .format(meta.size, meta.timestamp) + ) + + +def test_default_batch_size_limit(): + # First message can be added even if it's too big + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=0, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=1024) + + meta = builder.append( + 0, timestamp=None, key=None, value=b"M" * 2000, headers=[]) + assert meta.size > 0 + assert meta.crc is None + assert meta.offset == 0 + assert meta.timestamp is not None + assert len(builder.build()) > 2000 + + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=0, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=1024) + meta = builder.append( + 0, timestamp=None, key=None, value=b"M" * 700, headers=[]) + assert meta is not None + meta = builder.append( + 1, timestamp=None, key=None, value=b"M" * 700, headers=[]) + assert meta is None + meta = builder.append( + 2, timestamp=None, key=None, value=b"M" * 700, headers=[]) + assert meta is None + assert len(builder.build()) < 1000 + + +@pytest.mark.parametrize("compression_type,name,checker_name", [ + (DefaultRecordBatch.CODEC_GZIP, "gzip", "has_gzip"), + (DefaultRecordBatch.CODEC_SNAPPY, "snappy", "has_snappy"), + (DefaultRecordBatch.CODEC_LZ4, "lz4", "has_lz4") +]) +@pytest.mark.parametrize("magic", [0, 1]) +def test_unavailable_codec(magic, compression_type, name, checker_name): + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=compression_type, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=1024) + builder.append(0, timestamp=None, key=None, value=b"M" * 2000, headers=[]) + correct_buffer = builder.build() + + with patch.object(kafka.codec, checker_name) as mocked: + mocked.return_value = False + # Check that builder raises error + builder = DefaultRecordBatchBuilder( + magic=2, compression_type=compression_type, is_transactional=0, + producer_id=-1, producer_epoch=-1, base_sequence=-1, + batch_size=1024) + error_msg = "Libraries for {} compression codec not found".format(name) + with pytest.raises(UnsupportedCodecError, match=error_msg): + builder.append(0, timestamp=None, key=None, value=b"M", headers=[]) + builder.build() + + # Check that reader raises same error + batch = DefaultRecordBatch(bytes(correct_buffer)) + with pytest.raises(UnsupportedCodecError, match=error_msg): + list(batch) diff --git a/testbed/dpkp__kafka-python/test/record/test_legacy_records.py b/testbed/dpkp__kafka-python/test/record/test_legacy_records.py new file mode 100644 index 0000000000000000000000000000000000000000..43970f7c9548e977d501995a6e16b7c27ff8d981 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/record/test_legacy_records.py @@ -0,0 +1,197 @@ +from __future__ import unicode_literals +import pytest +from mock import patch +from kafka.record.legacy_records import ( + LegacyRecordBatch, LegacyRecordBatchBuilder +) +import kafka.codec +from kafka.errors import UnsupportedCodecError + + +@pytest.mark.parametrize("magic", [0, 1]) +def test_read_write_serde_v0_v1_no_compression(magic): + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=9999999) + builder.append( + 0, timestamp=9999999, key=b"test", value=b"Super") + buffer = builder.build() + + batch = LegacyRecordBatch(bytes(buffer), magic) + msgs = list(batch) + assert len(msgs) == 1 + msg = msgs[0] + + assert msg.offset == 0 + assert msg.timestamp == (9999999 if magic else None) + assert msg.timestamp_type == (0 if magic else None) + assert msg.key == b"test" + assert msg.value == b"Super" + assert msg.checksum == (-2095076219 if magic else 278251978) & 0xffffffff + + +@pytest.mark.parametrize("compression_type", [ + LegacyRecordBatch.CODEC_GZIP, + LegacyRecordBatch.CODEC_SNAPPY, + LegacyRecordBatch.CODEC_LZ4 +]) +@pytest.mark.parametrize("magic", [0, 1]) +def test_read_write_serde_v0_v1_with_compression(compression_type, magic): + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=compression_type, batch_size=9999999) + for offset in range(10): + builder.append( + offset, timestamp=9999999, key=b"test", value=b"Super") + buffer = builder.build() + + batch = LegacyRecordBatch(bytes(buffer), magic) + msgs = list(batch) + + for offset, msg in enumerate(msgs): + assert msg.offset == offset + assert msg.timestamp == (9999999 if magic else None) + assert msg.timestamp_type == (0 if magic else None) + assert msg.key == b"test" + assert msg.value == b"Super" + assert msg.checksum == (-2095076219 if magic else 278251978) & \ + 0xffffffff + + +@pytest.mark.parametrize("magic", [0, 1]) +def test_written_bytes_equals_size_in_bytes(magic): + key = b"test" + value = b"Super" + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=9999999) + + size_in_bytes = builder.size_in_bytes( + 0, timestamp=9999999, key=key, value=value) + + pos = builder.size() + builder.append(0, timestamp=9999999, key=key, value=value) + + assert builder.size() - pos == size_in_bytes + + +@pytest.mark.parametrize("magic", [0, 1]) +def test_estimate_size_in_bytes_bigger_than_batch(magic): + key = b"Super Key" + value = b"1" * 100 + estimate_size = LegacyRecordBatchBuilder.estimate_size_in_bytes( + magic, compression_type=0, key=key, value=value) + + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=9999999) + builder.append( + 0, timestamp=9999999, key=key, value=value) + buf = builder.build() + assert len(buf) <= estimate_size, \ + "Estimate should always be upper bound" + + +@pytest.mark.parametrize("magic", [0, 1]) +def test_legacy_batch_builder_validates_arguments(magic): + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=1024 * 1024) + + # Key should not be str + with pytest.raises(TypeError): + builder.append( + 0, timestamp=9999999, key="some string", value=None) + + # Value should not be str + with pytest.raises(TypeError): + builder.append( + 0, timestamp=9999999, key=None, value="some string") + + # Timestamp should be of proper type + if magic != 0: + with pytest.raises(TypeError): + builder.append( + 0, timestamp="1243812793", key=None, value=b"some string") + + # Offset of invalid type + with pytest.raises(TypeError): + builder.append( + "0", timestamp=9999999, key=None, value=b"some string") + + # Ok to pass value as None + builder.append( + 0, timestamp=9999999, key=b"123", value=None) + + # Timestamp can be None + builder.append( + 1, timestamp=None, key=None, value=b"some string") + + # Ok to pass offsets in not incremental order. This should not happen thou + builder.append( + 5, timestamp=9999999, key=b"123", value=None) + + # in case error handling code fails to fix inner buffer in builder + assert len(builder.build()) == 119 if magic else 95 + + +@pytest.mark.parametrize("magic", [0, 1]) +def test_legacy_correct_metadata_response(magic): + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=1024 * 1024) + meta = builder.append( + 0, timestamp=9999999, key=b"test", value=b"Super") + + assert meta.offset == 0 + assert meta.timestamp == (9999999 if magic else -1) + assert meta.crc == (-2095076219 if magic else 278251978) & 0xffffffff + assert repr(meta) == ( + "LegacyRecordMetadata(offset=0, crc={!r}, size={}, " + "timestamp={})".format(meta.crc, meta.size, meta.timestamp) + ) + + +@pytest.mark.parametrize("magic", [0, 1]) +def test_legacy_batch_size_limit(magic): + # First message can be added even if it's too big + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=1024) + meta = builder.append(0, timestamp=None, key=None, value=b"M" * 2000) + assert meta.size > 0 + assert meta.crc is not None + assert meta.offset == 0 + assert meta.timestamp is not None + assert len(builder.build()) > 2000 + + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=0, batch_size=1024) + meta = builder.append(0, timestamp=None, key=None, value=b"M" * 700) + assert meta is not None + meta = builder.append(1, timestamp=None, key=None, value=b"M" * 700) + assert meta is None + meta = builder.append(2, timestamp=None, key=None, value=b"M" * 700) + assert meta is None + assert len(builder.build()) < 1000 + + +@pytest.mark.parametrize("compression_type,name,checker_name", [ + (LegacyRecordBatch.CODEC_GZIP, "gzip", "has_gzip"), + (LegacyRecordBatch.CODEC_SNAPPY, "snappy", "has_snappy"), + (LegacyRecordBatch.CODEC_LZ4, "lz4", "has_lz4") +]) +@pytest.mark.parametrize("magic", [0, 1]) +def test_unavailable_codec(magic, compression_type, name, checker_name): + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=compression_type, batch_size=1024) + builder.append(0, timestamp=None, key=None, value=b"M") + correct_buffer = builder.build() + + with patch.object(kafka.codec, checker_name) as mocked: + mocked.return_value = False + # Check that builder raises error + builder = LegacyRecordBatchBuilder( + magic=magic, compression_type=compression_type, batch_size=1024) + error_msg = "Libraries for {} compression codec not found".format(name) + with pytest.raises(UnsupportedCodecError, match=error_msg): + builder.append(0, timestamp=None, key=None, value=b"M") + builder.build() + + # Check that reader raises same error + batch = LegacyRecordBatch(bytes(correct_buffer), magic) + with pytest.raises(UnsupportedCodecError, match=error_msg): + list(batch) diff --git a/testbed/dpkp__kafka-python/test/record/test_records.py b/testbed/dpkp__kafka-python/test/record/test_records.py new file mode 100644 index 0000000000000000000000000000000000000000..9f72234ae399284bb7259f2175f412206b0f1b4c --- /dev/null +++ b/testbed/dpkp__kafka-python/test/record/test_records.py @@ -0,0 +1,232 @@ +# -*- coding: utf-8 -*- +from __future__ import unicode_literals +import pytest +from kafka.record import MemoryRecords, MemoryRecordsBuilder +from kafka.errors import CorruptRecordException + +# This is real live data from Kafka 11 broker +record_batch_data_v2 = [ + # First Batch value == "123" + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00;\x00\x00\x00\x01\x02\x03' + b'\x18\xa2p\x00\x00\x00\x00\x00\x00\x00\x00\x01]\xff{\x06<\x00\x00\x01]' + b'\xff{\x06<\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00' + b'\x00\x00\x01\x12\x00\x00\x00\x01\x06123\x00', + # Second Batch value = "" and value = "". 2 records + b'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00@\x00\x00\x00\x02\x02\xc8' + b'\\\xbd#\x00\x00\x00\x00\x00\x01\x00\x00\x01]\xff|\xddl\x00\x00\x01]\xff' + b'|\xde\x14\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x00' + b'\x00\x00\x02\x0c\x00\x00\x00\x01\x00\x00\x0e\x00\xd0\x02\x02\x01\x00' + b'\x00', + # Third batch value = "123" + b'\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00;\x00\x00\x00\x02\x02.\x0b' + b'\x85\xb7\x00\x00\x00\x00\x00\x00\x00\x00\x01]\xff|\xe7\x9d\x00\x00\x01]' + b'\xff|\xe7\x9d\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' + b'\x00\x00\x00\x01\x12\x00\x00\x00\x01\x06123\x00' + # Fourth batch value = "hdr" with header hkey=hval + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00E\x00\x00\x00\x00\x02\\' + b'\xd8\xefR\x00\x00\x00\x00\x00\x00\x00\x00\x01e\x85\xb6\xf3\xc1\x00\x00' + b'\x01e\x85\xb6\xf3\xc1\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' + b'\xff\xff\x00\x00\x00\x01&\x00\x00\x00\x01\x06hdr\x02\x08hkey\x08hval' +] + +record_batch_data_v1 = [ + # First Message value == "123" + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x19G\x86(\xc2\x01\x00\x00' + b'\x00\x01^\x18g\xab\xae\xff\xff\xff\xff\x00\x00\x00\x03123', + # Second Message value == "" + b'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x16\xef\x98\xc9 \x01\x00' + b'\x00\x00\x01^\x18g\xaf\xc0\xff\xff\xff\xff\x00\x00\x00\x00', + # Third Message value == "" + b'\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x16_\xaf\xfb^\x01\x00\x00' + b'\x00\x01^\x18g\xb0r\xff\xff\xff\xff\x00\x00\x00\x00', + # Fourth Message value = "123" + b'\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x19\xa8\x12W \x01\x00\x00' + b'\x00\x01^\x18g\xb8\x03\xff\xff\xff\xff\x00\x00\x00\x03123' +] + +# This is real live data from Kafka 10 broker +record_batch_data_v0 = [ + # First Message value == "123" + b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x11\xfe\xb0\x1d\xbf\x00' + b'\x00\xff\xff\xff\xff\x00\x00\x00\x03123', + # Second Message value == "" + b'\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x0eyWH\xe0\x00\x00\xff' + b'\xff\xff\xff\x00\x00\x00\x00', + # Third Message value == "" + b'\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x0eyWH\xe0\x00\x00\xff' + b'\xff\xff\xff\x00\x00\x00\x00', + # Fourth Message value = "123" + b'\x00\x00\x00\x00\x00\x00\x00\x03\x00\x00\x00\x11\xfe\xb0\x1d\xbf\x00' + b'\x00\xff\xff\xff\xff\x00\x00\x00\x03123' +] + + +def test_memory_records_v2(): + data_bytes = b"".join(record_batch_data_v2) + b"\x00" * 4 + records = MemoryRecords(data_bytes) + + assert records.size_in_bytes() == 303 + assert records.valid_bytes() == 299 + + assert records.has_next() is True + batch = records.next_batch() + recs = list(batch) + assert len(recs) == 1 + assert recs[0].value == b"123" + assert recs[0].key is None + assert recs[0].timestamp == 1503229838908 + assert recs[0].timestamp_type == 0 + assert recs[0].checksum is None + assert recs[0].headers == [] + + assert records.next_batch() is not None + assert records.next_batch() is not None + + batch = records.next_batch() + recs = list(batch) + assert len(recs) == 1 + assert recs[0].value == b"hdr" + assert recs[0].headers == [('hkey', b'hval')] + + assert records.has_next() is False + assert records.next_batch() is None + assert records.next_batch() is None + + +def test_memory_records_v1(): + data_bytes = b"".join(record_batch_data_v1) + b"\x00" * 4 + records = MemoryRecords(data_bytes) + + assert records.size_in_bytes() == 146 + assert records.valid_bytes() == 142 + + assert records.has_next() is True + batch = records.next_batch() + recs = list(batch) + assert len(recs) == 1 + assert recs[0].value == b"123" + assert recs[0].key is None + assert recs[0].timestamp == 1503648000942 + assert recs[0].timestamp_type == 0 + assert recs[0].checksum == 1199974594 & 0xffffffff + + assert records.next_batch() is not None + assert records.next_batch() is not None + assert records.next_batch() is not None + + assert records.has_next() is False + assert records.next_batch() is None + assert records.next_batch() is None + + +def test_memory_records_v0(): + data_bytes = b"".join(record_batch_data_v0) + records = MemoryRecords(data_bytes + b"\x00" * 4) + + assert records.size_in_bytes() == 114 + assert records.valid_bytes() == 110 + + records = MemoryRecords(data_bytes) + + assert records.has_next() is True + batch = records.next_batch() + recs = list(batch) + assert len(recs) == 1 + assert recs[0].value == b"123" + assert recs[0].key is None + assert recs[0].timestamp is None + assert recs[0].timestamp_type is None + assert recs[0].checksum == -22012481 & 0xffffffff + + assert records.next_batch() is not None + assert records.next_batch() is not None + assert records.next_batch() is not None + + assert records.has_next() is False + assert records.next_batch() is None + assert records.next_batch() is None + + +def test_memory_records_corrupt(): + records = MemoryRecords(b"") + assert records.size_in_bytes() == 0 + assert records.valid_bytes() == 0 + assert records.has_next() is False + + records = MemoryRecords(b"\x00\x00\x00") + assert records.size_in_bytes() == 3 + assert records.valid_bytes() == 0 + assert records.has_next() is False + + records = MemoryRecords( + b"\x00\x00\x00\x00\x00\x00\x00\x03" # Offset=3 + b"\x00\x00\x00\x03" # Length=3 + b"\xfe\xb0\x1d", # Some random bytes + ) + with pytest.raises(CorruptRecordException): + records.next_batch() + + +@pytest.mark.parametrize("compression_type", [0, 1, 2, 3]) +@pytest.mark.parametrize("magic", [0, 1, 2]) +def test_memory_records_builder(magic, compression_type): + builder = MemoryRecordsBuilder( + magic=magic, compression_type=compression_type, batch_size=1024 * 10) + base_size = builder.size_in_bytes() # V2 has a header before + + msg_sizes = [] + for offset in range(10): + metadata = builder.append( + timestamp=10000 + offset, key=b"test", value=b"Super") + msg_sizes.append(metadata.size) + assert metadata.offset == offset + if magic > 0: + assert metadata.timestamp == 10000 + offset + else: + assert metadata.timestamp == -1 + assert builder.next_offset() == offset + 1 + + # Error appends should not leave junk behind, like null bytes or something + with pytest.raises(TypeError): + builder.append( + timestamp=None, key="test", value="Super") # Not bytes, but str + + assert not builder.is_full() + size_before_close = builder.size_in_bytes() + assert size_before_close == sum(msg_sizes) + base_size + + # Size should remain the same after closing. No trailing bytes + builder.close() + assert builder.compression_rate() > 0 + expected_size = size_before_close * builder.compression_rate() + assert builder.is_full() + assert builder.size_in_bytes() == expected_size + buffer = builder.buffer() + assert len(buffer) == expected_size + + # We can close second time, as in retry + builder.close() + assert builder.size_in_bytes() == expected_size + assert builder.buffer() == buffer + + # Can't append after close + meta = builder.append(timestamp=None, key=b"test", value=b"Super") + assert meta is None + + +@pytest.mark.parametrize("compression_type", [0, 1, 2, 3]) +@pytest.mark.parametrize("magic", [0, 1, 2]) +def test_memory_records_builder_full(magic, compression_type): + builder = MemoryRecordsBuilder( + magic=magic, compression_type=compression_type, batch_size=1024 * 10) + + # 1 message should always be appended + metadata = builder.append( + key=None, timestamp=None, value=b"M" * 10240) + assert metadata is not None + assert builder.is_full() + + metadata = builder.append( + key=None, timestamp=None, value=b"M") + assert metadata is None + assert builder.next_offset() == 1 diff --git a/testbed/dpkp__kafka-python/test/record/test_util.py b/testbed/dpkp__kafka-python/test/record/test_util.py new file mode 100644 index 0000000000000000000000000000000000000000..0b2782e7abfebd1bd8f01285369b28016b7411f3 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/record/test_util.py @@ -0,0 +1,96 @@ +import struct +import pytest +from kafka.record import util + + +varint_data = [ + (b"\x00", 0), + (b"\x01", -1), + (b"\x02", 1), + (b"\x7E", 63), + (b"\x7F", -64), + (b"\x80\x01", 64), + (b"\x81\x01", -65), + (b"\xFE\x7F", 8191), + (b"\xFF\x7F", -8192), + (b"\x80\x80\x01", 8192), + (b"\x81\x80\x01", -8193), + (b"\xFE\xFF\x7F", 1048575), + (b"\xFF\xFF\x7F", -1048576), + (b"\x80\x80\x80\x01", 1048576), + (b"\x81\x80\x80\x01", -1048577), + (b"\xFE\xFF\xFF\x7F", 134217727), + (b"\xFF\xFF\xFF\x7F", -134217728), + (b"\x80\x80\x80\x80\x01", 134217728), + (b"\x81\x80\x80\x80\x01", -134217729), + (b"\xFE\xFF\xFF\xFF\x7F", 17179869183), + (b"\xFF\xFF\xFF\xFF\x7F", -17179869184), + (b"\x80\x80\x80\x80\x80\x01", 17179869184), + (b"\x81\x80\x80\x80\x80\x01", -17179869185), + (b"\xFE\xFF\xFF\xFF\xFF\x7F", 2199023255551), + (b"\xFF\xFF\xFF\xFF\xFF\x7F", -2199023255552), + (b"\x80\x80\x80\x80\x80\x80\x01", 2199023255552), + (b"\x81\x80\x80\x80\x80\x80\x01", -2199023255553), + (b"\xFE\xFF\xFF\xFF\xFF\xFF\x7F", 281474976710655), + (b"\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -281474976710656), + (b"\x80\x80\x80\x80\x80\x80\x80\x01", 281474976710656), + (b"\x81\x80\x80\x80\x80\x80\x80\x01", -281474976710657), + (b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 36028797018963967), + (b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -36028797018963968), + (b"\x80\x80\x80\x80\x80\x80\x80\x80\x01", 36028797018963968), + (b"\x81\x80\x80\x80\x80\x80\x80\x80\x01", -36028797018963969), + (b"\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", 4611686018427387903), + (b"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x7F", -4611686018427387904), + (b"\x80\x80\x80\x80\x80\x80\x80\x80\x80\x01", 4611686018427387904), + (b"\x81\x80\x80\x80\x80\x80\x80\x80\x80\x01", -4611686018427387905), +] + + +@pytest.mark.parametrize("encoded, decoded", varint_data) +def test_encode_varint(encoded, decoded): + res = bytearray() + util.encode_varint(decoded, res.append) + assert res == encoded + + +@pytest.mark.parametrize("encoded, decoded", varint_data) +def test_decode_varint(encoded, decoded): + # We add a bit of bytes around just to check position is calculated + # correctly + value, pos = util.decode_varint( + bytearray(b"\x01\xf0" + encoded + b"\xff\x01"), 2) + assert value == decoded + assert pos - 2 == len(encoded) + + +@pytest.mark.parametrize("encoded, decoded", varint_data) +def test_size_of_varint(encoded, decoded): + assert util.size_of_varint(decoded) == len(encoded) + + +@pytest.mark.parametrize("crc32_func", [util.crc32c_c, util.crc32c_py]) +def test_crc32c(crc32_func): + def make_crc(data): + crc = crc32_func(data) + return struct.pack(">I", crc) + assert make_crc(b"") == b"\x00\x00\x00\x00" + assert make_crc(b"a") == b"\xc1\xd0\x43\x30" + + # Took from librdkafka testcase + long_text = b"""\ + This software is provided 'as-is', without any express or implied + warranty. In no event will the author be held liable for any damages + arising from the use of this software. + + Permission is granted to anyone to use this software for any purpose, + including commercial applications, and to alter it and redistribute it + freely, subject to the following restrictions: + + 1. The origin of this software must not be misrepresented; you must not + claim that you wrote the original software. If you use this software + in a product, an acknowledgment in the product documentation would be + appreciated but is not required. + 2. Altered source versions must be plainly marked as such, and must not be + misrepresented as being the original software. + 3. This notice may not be removed or altered from any source distribution.""" + assert make_crc(long_text) == b"\x7d\xcd\xe1\x13" diff --git a/testbed/dpkp__kafka-python/test/service.py b/testbed/dpkp__kafka-python/test/service.py new file mode 100644 index 0000000000000000000000000000000000000000..045d780e7582d52759941f8bf405698b961c95c0 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/service.py @@ -0,0 +1,133 @@ +from __future__ import absolute_import + +import logging +import os +import re +import select +import subprocess +import sys +import threading +import time + +__all__ = [ + 'ExternalService', + 'SpawnedService', +] + +log = logging.getLogger(__name__) + + +class ExternalService(object): + def __init__(self, host, port): + log.info("Using already running service at %s:%d", host, port) + self.host = host + self.port = port + + def open(self): + pass + + def close(self): + pass + + +class SpawnedService(threading.Thread): + def __init__(self, args=None, env=None): + super(SpawnedService, self).__init__() + + if args is None: + raise TypeError("args parameter is required") + self.args = args + self.env = env + self.captured_stdout = [] + self.captured_stderr = [] + + self.should_die = threading.Event() + self.child = None + self.alive = False + self.daemon = True + log.info("Created service for command:") + log.info(" "+' '.join(self.args)) + log.debug("With environment:") + for key, value in self.env.items(): + log.debug(" {key}={value}".format(key=key, value=value)) + + def _spawn(self): + if self.alive: return + if self.child and self.child.poll() is None: return + + self.child = subprocess.Popen( + self.args, + preexec_fn=os.setsid, # to avoid propagating signals + env=self.env, + bufsize=1, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + self.alive = self.child.poll() is None + + def _despawn(self): + if self.child.poll() is None: + self.child.terminate() + self.alive = False + for _ in range(50): + if self.child.poll() is not None: + self.child = None + break + time.sleep(0.1) + else: + self.child.kill() + + def run(self): + self._spawn() + while True: + try: + (rds, _, _) = select.select([self.child.stdout, self.child.stderr], [], [], 1) + except select.error as ex: + if ex.args[0] == 4: + continue + else: + raise + + if self.child.stdout in rds: + line = self.child.stdout.readline().decode('utf-8').rstrip() + if line: + self.captured_stdout.append(line) + + if self.child.stderr in rds: + line = self.child.stderr.readline().decode('utf-8').rstrip() + if line: + self.captured_stderr.append(line) + + if self.child.poll() is not None: + self.dump_logs() + break + + if self.should_die.is_set(): + self._despawn() + break + + def dump_logs(self): + sys.stderr.write('\n'.join(self.captured_stderr)) + sys.stdout.write('\n'.join(self.captured_stdout)) + + def wait_for(self, pattern, timeout=30): + start = time.time() + while True: + if not self.is_alive(): + raise RuntimeError("Child thread died already.") + + elapsed = time.time() - start + if elapsed >= timeout: + log.error("Waiting for %r timed out after %d seconds", pattern, timeout) + return False + + if re.search(pattern, '\n'.join(self.captured_stdout), re.IGNORECASE) is not None: + log.info("Found pattern %r in %d seconds via stdout", pattern, elapsed) + return True + if re.search(pattern, '\n'.join(self.captured_stderr), re.IGNORECASE) is not None: + log.info("Found pattern %r in %d seconds via stderr", pattern, elapsed) + return True + time.sleep(0.1) + + def stop(self): + self.should_die.set() + self.join() diff --git a/testbed/dpkp__kafka-python/test/test_acl_comparisons.py b/testbed/dpkp__kafka-python/test/test_acl_comparisons.py new file mode 100644 index 0000000000000000000000000000000000000000..291bf0e2fee7287ce41dc9c02d47f5745461e73e --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_acl_comparisons.py @@ -0,0 +1,92 @@ +from kafka.admin.acl_resource import ACL +from kafka.admin.acl_resource import ACLOperation +from kafka.admin.acl_resource import ACLPermissionType +from kafka.admin.acl_resource import ResourcePattern +from kafka.admin.acl_resource import ResourceType +from kafka.admin.acl_resource import ACLResourcePatternType + + +def test_different_acls_are_different(): + one = ACL( + principal='User:A', + host='*', + operation=ACLOperation.ALL, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern( + resource_type=ResourceType.TOPIC, + resource_name='some-topic', + pattern_type=ACLResourcePatternType.LITERAL + ) + ) + + two = ACL( + principal='User:B', # Different principal + host='*', + operation=ACLOperation.ALL, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern( + resource_type=ResourceType.TOPIC, + resource_name='some-topic', + pattern_type=ACLResourcePatternType.LITERAL + ) + ) + + assert one != two + assert hash(one) != hash(two) + +def test_different_acls_are_different_with_glob_topics(): + one = ACL( + principal='User:A', + host='*', + operation=ACLOperation.ALL, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern( + resource_type=ResourceType.TOPIC, + resource_name='*', + pattern_type=ACLResourcePatternType.LITERAL + ) + ) + + two = ACL( + principal='User:B', # Different principal + host='*', + operation=ACLOperation.ALL, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern( + resource_type=ResourceType.TOPIC, + resource_name='*', + pattern_type=ACLResourcePatternType.LITERAL + ) + ) + + assert one != two + assert hash(one) != hash(two) + +def test_same_acls_are_same(): + one = ACL( + principal='User:A', + host='*', + operation=ACLOperation.ALL, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern( + resource_type=ResourceType.TOPIC, + resource_name='some-topic', + pattern_type=ACLResourcePatternType.LITERAL + ) + ) + + two = ACL( + principal='User:A', + host='*', + operation=ACLOperation.ALL, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern( + resource_type=ResourceType.TOPIC, + resource_name='some-topic', + pattern_type=ACLResourcePatternType.LITERAL + ) + ) + + assert one == two + assert hash(one) == hash(two) + assert len(set((one, two))) == 1 diff --git a/testbed/dpkp__kafka-python/test/test_admin.py b/testbed/dpkp__kafka-python/test/test_admin.py new file mode 100644 index 0000000000000000000000000000000000000000..279f85abfa950b1467c294753a178d53e3e08463 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_admin.py @@ -0,0 +1,78 @@ +import pytest + +import kafka.admin +from kafka.errors import IllegalArgumentError + + +def test_config_resource(): + with pytest.raises(KeyError): + bad_resource = kafka.admin.ConfigResource('something', 'foo') + good_resource = kafka.admin.ConfigResource('broker', 'bar') + assert good_resource.resource_type == kafka.admin.ConfigResourceType.BROKER + assert good_resource.name == 'bar' + assert good_resource.configs is None + good_resource = kafka.admin.ConfigResource(kafka.admin.ConfigResourceType.TOPIC, 'baz', {'frob': 'nob'}) + assert good_resource.resource_type == kafka.admin.ConfigResourceType.TOPIC + assert good_resource.name == 'baz' + assert good_resource.configs == {'frob': 'nob'} + + +def test_new_partitions(): + good_partitions = kafka.admin.NewPartitions(6) + assert good_partitions.total_count == 6 + assert good_partitions.new_assignments is None + good_partitions = kafka.admin.NewPartitions(7, [[1, 2, 3]]) + assert good_partitions.total_count == 7 + assert good_partitions.new_assignments == [[1, 2, 3]] + + +def test_acl_resource(): + good_acl = kafka.admin.ACL( + "User:bar", + "*", + kafka.admin.ACLOperation.ALL, + kafka.admin.ACLPermissionType.ALLOW, + kafka.admin.ResourcePattern( + kafka.admin.ResourceType.TOPIC, + "foo", + kafka.admin.ACLResourcePatternType.LITERAL + ) + ) + + assert(good_acl.resource_pattern.resource_type == kafka.admin.ResourceType.TOPIC) + assert(good_acl.operation == kafka.admin.ACLOperation.ALL) + assert(good_acl.permission_type == kafka.admin.ACLPermissionType.ALLOW) + assert(good_acl.resource_pattern.pattern_type == kafka.admin.ACLResourcePatternType.LITERAL) + + with pytest.raises(IllegalArgumentError): + kafka.admin.ACL( + "User:bar", + "*", + kafka.admin.ACLOperation.ANY, + kafka.admin.ACLPermissionType.ANY, + kafka.admin.ResourcePattern( + kafka.admin.ResourceType.TOPIC, + "foo", + kafka.admin.ACLResourcePatternType.LITERAL + ) + ) + +def test_new_topic(): + with pytest.raises(IllegalArgumentError): + bad_topic = kafka.admin.NewTopic('foo', -1, -1) + with pytest.raises(IllegalArgumentError): + bad_topic = kafka.admin.NewTopic('foo', 1, -1) + with pytest.raises(IllegalArgumentError): + bad_topic = kafka.admin.NewTopic('foo', 1, 1, {1: [1, 1, 1]}) + good_topic = kafka.admin.NewTopic('foo', 1, 2) + assert good_topic.name == 'foo' + assert good_topic.num_partitions == 1 + assert good_topic.replication_factor == 2 + assert good_topic.replica_assignments == {} + assert good_topic.topic_configs == {} + good_topic = kafka.admin.NewTopic('bar', -1, -1, {1: [1, 2, 3]}, {'key': 'value'}) + assert good_topic.name == 'bar' + assert good_topic.num_partitions == -1 + assert good_topic.replication_factor == -1 + assert good_topic.replica_assignments == {1: [1, 2, 3]} + assert good_topic.topic_configs == {'key': 'value'} diff --git a/testbed/dpkp__kafka-python/test/test_admin_integration.py b/testbed/dpkp__kafka-python/test/test_admin_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..06c40a223a0f7ac98752f15e824215dcd7b8c972 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_admin_integration.py @@ -0,0 +1,314 @@ +import pytest + +from logging import info +from test.testutil import env_kafka_version, random_string +from threading import Event, Thread +from time import time, sleep + +from kafka.admin import ( + ACLFilter, ACLOperation, ACLPermissionType, ResourcePattern, ResourceType, ACL, ConfigResource, ConfigResourceType) +from kafka.errors import (NoError, GroupCoordinatorNotAvailableError, NonEmptyGroupError, GroupIdNotFoundError) + + +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason="ACL features require broker >=0.11") +def test_create_describe_delete_acls(kafka_admin_client): + """Tests that we can add, list and remove ACLs + """ + + # Check that we don't have any ACLs in the cluster + acls, error = kafka_admin_client.describe_acls( + ACLFilter( + principal=None, + host="*", + operation=ACLOperation.ANY, + permission_type=ACLPermissionType.ANY, + resource_pattern=ResourcePattern(ResourceType.TOPIC, "topic") + ) + ) + + assert error is NoError + assert len(acls) == 0 + + # Try to add an ACL + acl = ACL( + principal="User:test", + host="*", + operation=ACLOperation.READ, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern(ResourceType.TOPIC, "topic") + ) + result = kafka_admin_client.create_acls([acl]) + + assert len(result["failed"]) == 0 + assert len(result["succeeded"]) == 1 + + # Check that we can list the ACL we created + acl_filter = ACLFilter( + principal=None, + host="*", + operation=ACLOperation.ANY, + permission_type=ACLPermissionType.ANY, + resource_pattern=ResourcePattern(ResourceType.TOPIC, "topic") + ) + acls, error = kafka_admin_client.describe_acls(acl_filter) + + assert error is NoError + assert len(acls) == 1 + + # Remove the ACL + delete_results = kafka_admin_client.delete_acls( + [ + ACLFilter( + principal="User:test", + host="*", + operation=ACLOperation.READ, + permission_type=ACLPermissionType.ALLOW, + resource_pattern=ResourcePattern(ResourceType.TOPIC, "topic") + ) + ] + ) + + assert len(delete_results) == 1 + assert len(delete_results[0][1]) == 1 # Check number of affected ACLs + + # Make sure the ACL does not exist in the cluster anymore + acls, error = kafka_admin_client.describe_acls( + ACLFilter( + principal="*", + host="*", + operation=ACLOperation.ANY, + permission_type=ACLPermissionType.ANY, + resource_pattern=ResourcePattern(ResourceType.TOPIC, "topic") + ) + ) + + assert error is NoError + assert len(acls) == 0 + + +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason="Describe config features require broker >=0.11") +def test_describe_configs_broker_resource_returns_configs(kafka_admin_client): + """Tests that describe config returns configs for broker + """ + broker_id = kafka_admin_client._client.cluster._brokers[0].nodeId + configs = kafka_admin_client.describe_configs([ConfigResource(ConfigResourceType.BROKER, broker_id)]) + + assert len(configs) == 1 + assert configs[0].resources[0][2] == ConfigResourceType.BROKER + assert configs[0].resources[0][3] == str(broker_id) + assert len(configs[0].resources[0][4]) > 1 + + +@pytest.mark.xfail(condition=True, + reason="https://github.com/dpkp/kafka-python/issues/1929", + raises=AssertionError) +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason="Describe config features require broker >=0.11") +def test_describe_configs_topic_resource_returns_configs(topic, kafka_admin_client): + """Tests that describe config returns configs for topic + """ + configs = kafka_admin_client.describe_configs([ConfigResource(ConfigResourceType.TOPIC, topic)]) + + assert len(configs) == 1 + assert configs[0].resources[0][2] == ConfigResourceType.TOPIC + assert configs[0].resources[0][3] == topic + assert len(configs[0].resources[0][4]) > 1 + + +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason="Describe config features require broker >=0.11") +def test_describe_configs_mixed_resources_returns_configs(topic, kafka_admin_client): + """Tests that describe config returns configs for mixed resource types (topic + broker) + """ + broker_id = kafka_admin_client._client.cluster._brokers[0].nodeId + configs = kafka_admin_client.describe_configs([ + ConfigResource(ConfigResourceType.TOPIC, topic), + ConfigResource(ConfigResourceType.BROKER, broker_id)]) + + assert len(configs) == 2 + + for config in configs: + assert (config.resources[0][2] == ConfigResourceType.TOPIC + and config.resources[0][3] == topic) or \ + (config.resources[0][2] == ConfigResourceType.BROKER + and config.resources[0][3] == str(broker_id)) + assert len(config.resources[0][4]) > 1 + + +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason="Describe config features require broker >=0.11") +def test_describe_configs_invalid_broker_id_raises(kafka_admin_client): + """Tests that describe config raises exception on non-integer broker id + """ + broker_id = "str" + + with pytest.raises(ValueError): + configs = kafka_admin_client.describe_configs([ConfigResource(ConfigResourceType.BROKER, broker_id)]) + + +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason='Describe consumer group requires broker >=0.11') +def test_describe_consumer_group_does_not_exist(kafka_admin_client): + """Tests that the describe consumer group call fails if the group coordinator is not available + """ + with pytest.raises(GroupCoordinatorNotAvailableError): + group_description = kafka_admin_client.describe_consumer_groups(['test']) + + +@pytest.mark.skipif(env_kafka_version() < (0, 11), reason='Describe consumer group requires broker >=0.11') +def test_describe_consumer_group_exists(kafka_admin_client, kafka_consumer_factory, topic): + """Tests that the describe consumer group call returns valid consumer group information + This test takes inspiration from the test 'test_group' in test_consumer_group.py. + """ + consumers = {} + stop = {} + threads = {} + random_group_id = 'test-group-' + random_string(6) + group_id_list = [random_group_id, random_group_id + '_2'] + generations = {group_id_list[0]: set(), group_id_list[1]: set()} + def consumer_thread(i, group_id): + assert i not in consumers + assert i not in stop + stop[i] = Event() + consumers[i] = kafka_consumer_factory(group_id=group_id) + while not stop[i].is_set(): + consumers[i].poll(20) + consumers[i].close() + consumers[i] = None + stop[i] = None + + num_consumers = 3 + for i in range(num_consumers): + group_id = group_id_list[i % 2] + t = Thread(target=consumer_thread, args=(i, group_id,)) + t.start() + threads[i] = t + + try: + timeout = time() + 35 + while True: + for c in range(num_consumers): + + # Verify all consumers have been created + if c not in consumers: + break + + # Verify all consumers have an assignment + elif not consumers[c].assignment(): + break + + # If all consumers exist and have an assignment + else: + + info('All consumers have assignment... checking for stable group') + # Verify all consumers are in the same generation + # then log state and break while loop + + for consumer in consumers.values(): + generations[consumer.config['group_id']].add(consumer._coordinator._generation.generation_id) + + is_same_generation = any([len(consumer_generation) == 1 for consumer_generation in generations.values()]) + + # New generation assignment is not complete until + # coordinator.rejoining = False + rejoining = any([consumer._coordinator.rejoining + for consumer in list(consumers.values())]) + + if not rejoining and is_same_generation: + break + else: + sleep(1) + assert time() < timeout, "timeout waiting for assignments" + + info('Group stabilized; verifying assignment') + output = kafka_admin_client.describe_consumer_groups(group_id_list) + assert len(output) == 2 + consumer_groups = set() + for consumer_group in output: + assert(consumer_group.group in group_id_list) + if consumer_group.group == group_id_list[0]: + assert(len(consumer_group.members) == 2) + else: + assert(len(consumer_group.members) == 1) + for member in consumer_group.members: + assert(member.member_metadata.subscription[0] == topic) + assert(member.member_assignment.assignment[0][0] == topic) + consumer_groups.add(consumer_group.group) + assert(sorted(list(consumer_groups)) == group_id_list) + finally: + info('Shutting down %s consumers', num_consumers) + for c in range(num_consumers): + info('Stopping consumer %s', c) + stop[c].set() + threads[c].join() + threads[c] = None + + +@pytest.mark.skipif(env_kafka_version() < (1, 1), reason="Delete consumer groups requires broker >=1.1") +def test_delete_consumergroups(kafka_admin_client, kafka_consumer_factory, send_messages): + random_group_id = 'test-group-' + random_string(6) + group1 = random_group_id + "_1" + group2 = random_group_id + "_2" + group3 = random_group_id + "_3" + + send_messages(range(0, 100), partition=0) + consumer1 = kafka_consumer_factory(group_id=group1) + next(consumer1) + consumer1.close() + + consumer2 = kafka_consumer_factory(group_id=group2) + next(consumer2) + consumer2.close() + + consumer3 = kafka_consumer_factory(group_id=group3) + next(consumer3) + consumer3.close() + + consumergroups = {group_id for group_id, _ in kafka_admin_client.list_consumer_groups()} + assert group1 in consumergroups + assert group2 in consumergroups + assert group3 in consumergroups + + delete_results = { + group_id: error + for group_id, error in kafka_admin_client.delete_consumer_groups([group1, group2]) + } + assert delete_results[group1] == NoError + assert delete_results[group2] == NoError + assert group3 not in delete_results + + consumergroups = {group_id for group_id, _ in kafka_admin_client.list_consumer_groups()} + assert group1 not in consumergroups + assert group2 not in consumergroups + assert group3 in consumergroups + + +@pytest.mark.skipif(env_kafka_version() < (1, 1), reason="Delete consumer groups requires broker >=1.1") +def test_delete_consumergroups_with_errors(kafka_admin_client, kafka_consumer_factory, send_messages): + random_group_id = 'test-group-' + random_string(6) + group1 = random_group_id + "_1" + group2 = random_group_id + "_2" + group3 = random_group_id + "_3" + + send_messages(range(0, 100), partition=0) + consumer1 = kafka_consumer_factory(group_id=group1) + next(consumer1) + consumer1.close() + + consumer2 = kafka_consumer_factory(group_id=group2) + next(consumer2) + + consumergroups = {group_id for group_id, _ in kafka_admin_client.list_consumer_groups()} + assert group1 in consumergroups + assert group2 in consumergroups + assert group3 not in consumergroups + + delete_results = { + group_id: error + for group_id, error in kafka_admin_client.delete_consumer_groups([group1, group2, group3]) + } + + assert delete_results[group1] == NoError + assert delete_results[group2] == NonEmptyGroupError + assert delete_results[group3] == GroupIdNotFoundError + + consumergroups = {group_id for group_id, _ in kafka_admin_client.list_consumer_groups()} + assert group1 not in consumergroups + assert group2 in consumergroups + assert group3 not in consumergroups diff --git a/testbed/dpkp__kafka-python/test/test_api_object_implementation.py b/testbed/dpkp__kafka-python/test/test_api_object_implementation.py new file mode 100644 index 0000000000000000000000000000000000000000..da80f148c1be2362018925ec034b900bf42f9468 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_api_object_implementation.py @@ -0,0 +1,18 @@ +import abc +import pytest + +from kafka.protocol.api import Request +from kafka.protocol.api import Response + + +attr_names = [n for n in dir(Request) if isinstance(getattr(Request, n), abc.abstractproperty)] +@pytest.mark.parametrize('klass', Request.__subclasses__()) +@pytest.mark.parametrize('attr_name', attr_names) +def test_request_type_conformance(klass, attr_name): + assert hasattr(klass, attr_name) + +attr_names = [n for n in dir(Response) if isinstance(getattr(Response, n), abc.abstractproperty)] +@pytest.mark.parametrize('klass', Response.__subclasses__()) +@pytest.mark.parametrize('attr_name', attr_names) +def test_response_type_conformance(klass, attr_name): + assert hasattr(klass, attr_name) diff --git a/testbed/dpkp__kafka-python/test/test_assignors.py b/testbed/dpkp__kafka-python/test/test_assignors.py new file mode 100644 index 0000000000000000000000000000000000000000..67e91e131a339b1f4596a6dee0b9f17dae0a2a2e --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_assignors.py @@ -0,0 +1,871 @@ +# pylint: skip-file +from __future__ import absolute_import + +from collections import defaultdict +from random import randint, sample + +import pytest + +from kafka.structs import TopicPartition +from kafka.coordinator.assignors.range import RangePartitionAssignor +from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor +from kafka.coordinator.assignors.sticky.sticky_assignor import StickyPartitionAssignor, StickyAssignorUserDataV1 +from kafka.coordinator.protocol import ConsumerProtocolMemberAssignment, ConsumerProtocolMemberMetadata +from kafka.vendor import six + + +@pytest.fixture(autouse=True) +def reset_sticky_assignor(): + yield + StickyPartitionAssignor.member_assignment = None + StickyPartitionAssignor.generation = -1 + + +def create_cluster(mocker, topics, topics_partitions=None, topic_partitions_lambda=None): + cluster = mocker.MagicMock() + cluster.topics.return_value = topics + if topics_partitions is not None: + cluster.partitions_for_topic.return_value = topics_partitions + if topic_partitions_lambda is not None: + cluster.partitions_for_topic.side_effect = topic_partitions_lambda + return cluster + + +def test_assignor_roundrobin(mocker): + assignor = RoundRobinPartitionAssignor + + member_metadata = { + 'C0': assignor.metadata({'t0', 't1'}), + 'C1': assignor.metadata({'t0', 't1'}), + } + + cluster = create_cluster(mocker, {'t0', 't1'}, topics_partitions={0, 1, 2}) + ret = assignor.assign(cluster, member_metadata) + expected = { + 'C0': ConsumerProtocolMemberAssignment( + assignor.version, [('t0', [0, 2]), ('t1', [1])], b''), + 'C1': ConsumerProtocolMemberAssignment( + assignor.version, [('t0', [1]), ('t1', [0, 2])], b'') + } + assert ret == expected + assert set(ret) == set(expected) + for member in ret: + assert ret[member].encode() == expected[member].encode() + + +def test_assignor_range(mocker): + assignor = RangePartitionAssignor + + member_metadata = { + 'C0': assignor.metadata({'t0', 't1'}), + 'C1': assignor.metadata({'t0', 't1'}), + } + + cluster = create_cluster(mocker, {'t0', 't1'}, topics_partitions={0, 1, 2}) + ret = assignor.assign(cluster, member_metadata) + expected = { + 'C0': ConsumerProtocolMemberAssignment( + assignor.version, [('t0', [0, 1]), ('t1', [0, 1])], b''), + 'C1': ConsumerProtocolMemberAssignment( + assignor.version, [('t0', [2]), ('t1', [2])], b'') + } + assert ret == expected + assert set(ret) == set(expected) + for member in ret: + assert ret[member].encode() == expected[member].encode() + + +def test_sticky_assignor1(mocker): + """ + Given: there are three consumers C0, C1, C2, + four topics t0, t1, t2, t3, and each topic has 2 partitions, + resulting in partitions t0p0, t0p1, t1p0, t1p1, t2p0, t2p1, t3p0, t3p1. + Each consumer is subscribed to all three topics. + Then: perform fresh assignment + Expected: the assignment is + - C0: [t0p0, t1p1, t3p0] + - C1: [t0p1, t2p0, t3p1] + - C2: [t1p0, t2p1] + Then: remove C1 consumer and perform the reassignment + Expected: the new assignment is + - C0 [t0p0, t1p1, t2p0, t3p0] + - C2 [t0p1, t1p0, t2p1, t3p1] + """ + cluster = create_cluster(mocker, topics={'t0', 't1', 't2', 't3'}, topics_partitions={0, 1}) + + subscriptions = { + 'C0': {'t0', 't1', 't2', 't3'}, + 'C1': {'t0', 't1', 't2', 't3'}, + 'C2': {'t0', 't1', 't2', 't3'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C0': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t0', [0]), ('t1', [1]), ('t3', [0])], b''), + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t0', [1]), ('t2', [0]), ('t3', [1])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0]), ('t2', [1])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + del subscriptions['C1'] + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, sticky_assignment[member].partitions()) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C0': ConsumerProtocolMemberAssignment( + StickyPartitionAssignor.version, [('t0', [0]), ('t1', [1]), ('t2', [0]), ('t3', [0])], b'' + ), + 'C2': ConsumerProtocolMemberAssignment( + StickyPartitionAssignor.version, [('t0', [1]), ('t1', [0]), ('t2', [1]), ('t3', [1])], b'' + ), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_assignor2(mocker): + """ + Given: there are three consumers C0, C1, C2, + and three topics t0, t1, t2, with 1, 2, and 3 partitions respectively. + Therefore, the partitions are t0p0, t1p0, t1p1, t2p0, t2p1, t2p2. + C0 is subscribed to t0; + C1 is subscribed to t0, t1; + and C2 is subscribed to t0, t1, t2. + Then: perform the assignment + Expected: the assignment is + - C0 [t0p0] + - C1 [t1p0, t1p1] + - C2 [t2p0, t2p1, t2p2] + Then: remove C0 and perform the assignment + Expected: the assignment is + - C1 [t0p0, t1p0, t1p1] + - C2 [t2p0, t2p1, t2p2] + """ + + partitions = {'t0': {0}, 't1': {0, 1}, 't2': {0, 1, 2}} + cluster = create_cluster(mocker, topics={'t0', 't1', 't2'}, topic_partitions_lambda=lambda t: partitions[t]) + + subscriptions = { + 'C0': {'t0'}, + 'C1': {'t0', 't1'}, + 'C2': {'t0', 't1', 't2'}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, []) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C0': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t0', [0])], b''), + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0, 1])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t2', [0, 1, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + del subscriptions['C0'] + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, sticky_assignment[member].partitions()) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t0', [0]), ('t1', [0, 1])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t2', [0, 1, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_one_consumer_no_topic(mocker): + cluster = create_cluster(mocker, topics={}, topics_partitions={}) + + subscriptions = { + 'C': set(), + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_one_consumer_nonexisting_topic(mocker): + cluster = create_cluster(mocker, topics={}, topics_partitions={}) + + subscriptions = { + 'C': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_one_consumer_one_topic(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2}) + + subscriptions = { + 'C': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [0, 1, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_should_only_assign_partitions_from_subscribed_topics(mocker): + cluster = create_cluster(mocker, topics={'t', 'other-t'}, topics_partitions={0, 1, 2}) + + subscriptions = { + 'C': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [0, 1, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_one_consumer_multiple_topics(mocker): + cluster = create_cluster(mocker, topics={'t1', 't2'}, topics_partitions={0, 1, 2}) + + subscriptions = { + 'C': {'t1', 't2'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0, 1, 2]), ('t2', [0, 1, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_two_consumers_one_topic_one_partition(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0}) + + subscriptions = { + 'C1': {'t'}, + 'C2': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [0])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_two_consumers_one_topic_two_partitions(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1}) + + subscriptions = { + 'C1': {'t'}, + 'C2': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [0])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [1])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_multiple_consumers_mixed_topic_subscriptions(mocker): + partitions = {'t1': {0, 1, 2}, 't2': {0, 1}} + cluster = create_cluster(mocker, topics={'t1', 't2'}, topic_partitions_lambda=lambda t: partitions[t]) + + subscriptions = { + 'C1': {'t1'}, + 'C2': {'t1', 't2'}, + 'C3': {'t1'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0, 2])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t2', [0, 1])], b''), + 'C3': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [1])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_add_remove_consumer_one_topic(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2}) + + subscriptions = { + 'C1': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [0, 1, 2])], b''), + } + assert_assignment(assignment, expected_assignment) + + subscriptions = { + 'C1': {'t'}, + 'C2': {'t'}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata( + topics, assignment[member].partitions() if member in assignment else [] + ) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + subscriptions = { + 'C2': {'t'}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, assignment[member].partitions()) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert len(assignment['C2'].assignment[0][1]) == 3 + + +def test_sticky_add_remove_topic_two_consumers(mocker): + cluster = create_cluster(mocker, topics={'t1', 't2'}, topics_partitions={0, 1, 2}) + + subscriptions = { + 'C1': {'t1'}, + 'C2': {'t1'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0, 2])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [1])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + subscriptions = { + 'C1': {'t1', 't2'}, + 'C2': {'t1', 't2'}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, sticky_assignment[member].partitions()) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0, 2]), ('t2', [1])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [1]), ('t2', [0, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + subscriptions = { + 'C1': {'t2'}, + 'C2': {'t2'}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, sticky_assignment[member].partitions()) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C1': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t2', [1])], b''), + 'C2': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t2', [0, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_sticky_reassignment_after_one_consumer_leaves(mocker): + partitions = dict([('t{}'.format(i), set(range(i))) for i in range(1, 20)]) + cluster = create_cluster( + mocker, topics=set(['t{}'.format(i) for i in range(1, 20)]), topic_partitions_lambda=lambda t: partitions[t] + ) + + subscriptions = {} + for i in range(1, 20): + topics = set() + for j in range(1, i + 1): + topics.add('t{}'.format(j)) + subscriptions['C{}'.format(i)] = topics + + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + del subscriptions['C10'] + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, assignment[member].partitions()) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_sticky_reassignment_after_one_consumer_added(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions=set(range(20))) + + subscriptions = defaultdict(set) + for i in range(1, 10): + subscriptions['C{}'.format(i)] = {'t'} + + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + subscriptions['C10'] = {'t'} + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata( + topics, assignment[member].partitions() if member in assignment else [] + ) + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_sticky_same_subscriptions(mocker): + partitions = dict([('t{}'.format(i), set(range(i))) for i in range(1, 15)]) + cluster = create_cluster( + mocker, topics=set(['t{}'.format(i) for i in range(1, 15)]), topic_partitions_lambda=lambda t: partitions[t] + ) + + subscriptions = defaultdict(set) + for i in range(1, 9): + for j in range(1, len(six.viewkeys(partitions)) + 1): + subscriptions['C{}'.format(i)].add('t{}'.format(j)) + + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + del subscriptions['C5'] + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, assignment[member].partitions()) + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_sticky_large_assignment_with_multiple_consumers_leaving(mocker): + n_topics = 40 + n_consumers = 200 + + all_topics = set(['t{}'.format(i) for i in range(1, n_topics + 1)]) + partitions = dict([(t, set(range(1, randint(0, 10) + 1))) for t in all_topics]) + cluster = create_cluster(mocker, topics=all_topics, topic_partitions_lambda=lambda t: partitions[t]) + + subscriptions = defaultdict(set) + for i in range(1, n_consumers + 1): + for j in range(0, randint(1, 20)): + subscriptions['C{}'.format(i)].add('t{}'.format(randint(1, n_topics))) + + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, assignment[member].partitions()) + + for i in range(50): + member = 'C{}'.format(randint(1, n_consumers)) + if member in subscriptions: + del subscriptions[member] + del member_metadata[member] + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_new_subscription(mocker): + cluster = create_cluster(mocker, topics={'t1', 't2', 't3', 't4'}, topics_partitions={0}) + + subscriptions = defaultdict(set) + for i in range(3): + for j in range(i, 3 * i - 2 + 1): + subscriptions['C{}'.format(i)].add('t{}'.format(j)) + + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + subscriptions['C0'].add('t1') + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, []) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_move_existing_assignments(mocker): + cluster = create_cluster(mocker, topics={'t1', 't2', 't3', 't4', 't5', 't6'}, topics_partitions={0}) + + subscriptions = { + 'C1': {'t1', 't2'}, + 'C2': {'t1', 't2', 't3', 't4'}, + 'C3': {'t2', 't3', 't4', 't5', 't6'}, + } + member_assignments = { + 'C1': [TopicPartition('t1', 0)], + 'C2': [TopicPartition('t2', 0), TopicPartition('t3', 0)], + 'C3': [TopicPartition('t4', 0), TopicPartition('t5', 0), TopicPartition('t6', 0)], + } + + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, member_assignments[member]) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + +def test_stickiness(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2}) + subscriptions = { + 'C1': {'t'}, + 'C2': {'t'}, + 'C3': {'t'}, + 'C4': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + partitions_assigned = {} + for consumer, consumer_assignment in six.iteritems(assignment): + assert ( + len(consumer_assignment.partitions()) <= 1 + ), 'Consumer {} is assigned more topic partitions than expected.'.format(consumer) + if len(consumer_assignment.partitions()) == 1: + partitions_assigned[consumer] = consumer_assignment.partitions()[0] + + # removing the potential group leader + del subscriptions['C1'] + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, assignment[member].partitions()) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + for consumer, consumer_assignment in six.iteritems(assignment): + assert ( + len(consumer_assignment.partitions()) <= 1 + ), 'Consumer {} is assigned more topic partitions than expected.'.format(consumer) + assert ( + consumer not in partitions_assigned or partitions_assigned[consumer] in consumer_assignment.partitions() + ), 'Stickiness was not honored for consumer {}'.format(consumer) + + +def test_assignment_updated_for_deleted_topic(mocker): + def topic_partitions(topic): + if topic == 't1': + return {0} + if topic == 't3': + return set(range(100)) + + cluster = create_cluster(mocker, topics={'t1', 't3'}, topic_partitions_lambda=topic_partitions) + + subscriptions = { + 'C': {'t1', 't2', 't3'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t1', [0]), ('t3', list(range(100)))], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_no_exceptions_when_only_subscribed_topic_is_deleted(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2}) + + subscriptions = { + 'C': {'t'}, + } + member_metadata = make_member_metadata(subscriptions) + + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [('t', [0, 1, 2])], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + subscriptions = { + 'C': {}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, sticky_assignment[member].partitions()) + + cluster = create_cluster(mocker, topics={}, topics_partitions={}) + sticky_assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + expected_assignment = { + 'C': ConsumerProtocolMemberAssignment(StickyPartitionAssignor.version, [], b''), + } + assert_assignment(sticky_assignment, expected_assignment) + + +def test_conflicting_previous_assignments(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1}) + + subscriptions = { + 'C1': {'t'}, + 'C2': {'t'}, + } + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + # assume both C1 and C2 have partition 1 assigned to them in generation 1 + member_metadata[member] = StickyPartitionAssignor._metadata(topics, [TopicPartition('t', 0), TopicPartition('t', 0)], 1) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + +@pytest.mark.parametrize( + 'execution_number,n_topics,n_consumers', [(i, randint(10, 20), randint(20, 40)) for i in range(100)] +) +def test_reassignment_with_random_subscriptions_and_changes(mocker, execution_number, n_topics, n_consumers): + all_topics = set(['t{}'.format(i) for i in range(1, n_topics + 1)]) + partitions = dict([(t, set(range(1, i + 1))) for i, t in enumerate(all_topics)]) + cluster = create_cluster(mocker, topics=all_topics, topic_partitions_lambda=lambda t: partitions[t]) + + subscriptions = defaultdict(set) + for i in range(n_consumers): + topics_sample = sample(all_topics, randint(1, len(all_topics) - 1)) + subscriptions['C{}'.format(i)].update(topics_sample) + + member_metadata = make_member_metadata(subscriptions) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + + subscriptions = defaultdict(set) + for i in range(n_consumers): + topics_sample = sample(all_topics, randint(1, len(all_topics) - 1)) + subscriptions['C{}'.format(i)].update(topics_sample) + + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, assignment[member].partitions()) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance(subscriptions, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_assignment_with_multiple_generations1(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2, 3, 4, 5}) + + member_metadata = { + 'C1': StickyPartitionAssignor._metadata({'t'}, []), + 'C2': StickyPartitionAssignor._metadata({'t'}, []), + 'C3': StickyPartitionAssignor._metadata({'t'}, []), + } + + assignment1 = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C1': {'t'}, 'C2': {'t'}, 'C3': {'t'}}, assignment1) + assert len(assignment1['C1'].assignment[0][1]) == 2 + assert len(assignment1['C2'].assignment[0][1]) == 2 + assert len(assignment1['C3'].assignment[0][1]) == 2 + + member_metadata = { + 'C1': StickyPartitionAssignor._metadata({'t'}, assignment1['C1'].partitions()), + 'C2': StickyPartitionAssignor._metadata({'t'}, assignment1['C2'].partitions()), + } + + assignment2 = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C1': {'t'}, 'C2': {'t'}}, assignment2) + assert len(assignment2['C1'].assignment[0][1]) == 3 + assert len(assignment2['C2'].assignment[0][1]) == 3 + assert all([partition in assignment2['C1'].assignment[0][1] for partition in assignment1['C1'].assignment[0][1]]) + assert all([partition in assignment2['C2'].assignment[0][1] for partition in assignment1['C2'].assignment[0][1]]) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + member_metadata = { + 'C2': StickyPartitionAssignor._metadata({'t'}, assignment2['C2'].partitions(), 2), + 'C3': StickyPartitionAssignor._metadata({'t'}, assignment1['C3'].partitions(), 1), + } + + assignment3 = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C2': {'t'}, 'C3': {'t'}}, assignment3) + assert len(assignment3['C2'].assignment[0][1]) == 3 + assert len(assignment3['C3'].assignment[0][1]) == 3 + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def test_assignment_with_multiple_generations2(mocker): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2, 3, 4, 5}) + + member_metadata = { + 'C1': StickyPartitionAssignor._metadata({'t'}, []), + 'C2': StickyPartitionAssignor._metadata({'t'}, []), + 'C3': StickyPartitionAssignor._metadata({'t'}, []), + } + + assignment1 = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C1': {'t'}, 'C2': {'t'}, 'C3': {'t'}}, assignment1) + assert len(assignment1['C1'].assignment[0][1]) == 2 + assert len(assignment1['C2'].assignment[0][1]) == 2 + assert len(assignment1['C3'].assignment[0][1]) == 2 + + member_metadata = { + 'C2': StickyPartitionAssignor._metadata({'t'}, assignment1['C2'].partitions(), 1), + } + + assignment2 = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C2': {'t'}}, assignment2) + assert len(assignment2['C2'].assignment[0][1]) == 6 + assert all([partition in assignment2['C2'].assignment[0][1] for partition in assignment1['C2'].assignment[0][1]]) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + member_metadata = { + 'C1': StickyPartitionAssignor._metadata({'t'}, assignment1['C1'].partitions(), 1), + 'C2': StickyPartitionAssignor._metadata({'t'}, assignment2['C2'].partitions(), 2), + 'C3': StickyPartitionAssignor._metadata({'t'}, assignment1['C3'].partitions(), 1), + } + + assignment3 = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C1': {'t'}, 'C2': {'t'}, 'C3': {'t'}}, assignment3) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + assert set(assignment3['C1'].assignment[0][1]) == set(assignment1['C1'].assignment[0][1]) + assert set(assignment3['C2'].assignment[0][1]) == set(assignment1['C2'].assignment[0][1]) + assert set(assignment3['C3'].assignment[0][1]) == set(assignment1['C3'].assignment[0][1]) + + +@pytest.mark.parametrize('execution_number', range(50)) +def test_assignment_with_conflicting_previous_generations(mocker, execution_number): + cluster = create_cluster(mocker, topics={'t'}, topics_partitions={0, 1, 2, 3, 4, 5}) + + member_assignments = { + 'C1': [TopicPartition('t', p) for p in {0, 1, 4}], + 'C2': [TopicPartition('t', p) for p in {0, 2, 3}], + 'C3': [TopicPartition('t', p) for p in {3, 4, 5}], + } + member_generations = { + 'C1': 1, + 'C2': 1, + 'C3': 2, + } + member_metadata = {} + for member in six.iterkeys(member_assignments): + member_metadata[member] = StickyPartitionAssignor._metadata({'t'}, member_assignments[member], member_generations[member]) + + assignment = StickyPartitionAssignor.assign(cluster, member_metadata) + verify_validity_and_balance({'C1': {'t'}, 'C2': {'t'}, 'C3': {'t'}}, assignment) + assert StickyPartitionAssignor._latest_partition_movements.are_sticky() + + +def make_member_metadata(subscriptions): + member_metadata = {} + for member, topics in six.iteritems(subscriptions): + member_metadata[member] = StickyPartitionAssignor._metadata(topics, []) + return member_metadata + + +def assert_assignment(result_assignment, expected_assignment): + assert result_assignment == expected_assignment + assert set(result_assignment) == set(expected_assignment) + for member in result_assignment: + assert result_assignment[member].encode() == expected_assignment[member].encode() + + +def verify_validity_and_balance(subscriptions, assignment): + """ + Verifies that the given assignment is valid with respect to the given subscriptions + Validity requirements: + - each consumer is subscribed to topics of all partitions assigned to it, and + - each partition is assigned to no more than one consumer + Balance requirements: + - the assignment is fully balanced (the numbers of topic partitions assigned to consumers differ by at most one), or + - there is no topic partition that can be moved from one consumer to another with 2+ fewer topic partitions + + :param subscriptions topic subscriptions of each consumer + :param assignment: given assignment for balance check + """ + assert six.viewkeys(subscriptions) == six.viewkeys(assignment) + + consumers = sorted(six.viewkeys(assignment)) + for i in range(len(consumers)): + consumer = consumers[i] + partitions = assignment[consumer].partitions() + for partition in partitions: + assert partition.topic in subscriptions[consumer], ( + 'Error: Partition {} is assigned to consumer {}, ' + 'but it is not subscribed to topic {}\n' + 'Subscriptions: {}\n' + 'Assignments: {}'.format(partition, consumers[i], partition.topic, subscriptions, assignment) + ) + if i == len(consumers) - 1: + continue + + for j in range(i + 1, len(consumers)): + other_consumer = consumers[j] + other_partitions = assignment[other_consumer].partitions() + partitions_intersection = set(partitions).intersection(set(other_partitions)) + assert partitions_intersection == set(), ( + 'Error: Consumers {} and {} have common partitions ' + 'assigned to them: {}\n' + 'Subscriptions: {}\n' + 'Assignments: {}'.format(consumer, other_consumer, partitions_intersection, subscriptions, assignment) + ) + + if abs(len(partitions) - len(other_partitions)) <= 1: + continue + + assignments_by_topic = group_partitions_by_topic(partitions) + other_assignments_by_topic = group_partitions_by_topic(other_partitions) + if len(partitions) > len(other_partitions): + for topic in six.iterkeys(assignments_by_topic): + assert topic not in other_assignments_by_topic, ( + 'Error: Some partitions can be moved from {} ({} partitions) ' + 'to {} ({} partitions) ' + 'to achieve a better balance\n' + 'Subscriptions: {}\n' + 'Assignments: {}'.format(consumer, len(partitions), other_consumer, len(other_partitions), subscriptions, assignment) + ) + if len(other_partitions) > len(partitions): + for topic in six.iterkeys(other_assignments_by_topic): + assert topic not in assignments_by_topic, ( + 'Error: Some partitions can be moved from {} ({} partitions) ' + 'to {} ({} partitions) ' + 'to achieve a better balance\n' + 'Subscriptions: {}\n' + 'Assignments: {}'.format(other_consumer, len(other_partitions), consumer, len(partitions), subscriptions, assignment) + ) + + +def group_partitions_by_topic(partitions): + result = defaultdict(set) + for p in partitions: + result[p.topic].add(p.partition) + return result diff --git a/testbed/dpkp__kafka-python/test/test_client_async.py b/testbed/dpkp__kafka-python/test/test_client_async.py new file mode 100644 index 0000000000000000000000000000000000000000..74da66a36e353a6929838319fa514148680b3a55 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_client_async.py @@ -0,0 +1,409 @@ +from __future__ import absolute_import, division + +# selectors in stdlib as of py3.4 +try: + import selectors # pylint: disable=import-error +except ImportError: + # vendored backport module + import kafka.vendor.selectors34 as selectors + +import socket +import time + +import pytest + +from kafka.client_async import KafkaClient, IdleConnectionManager +from kafka.cluster import ClusterMetadata +from kafka.conn import ConnectionStates +import kafka.errors as Errors +from kafka.future import Future +from kafka.protocol.metadata import MetadataRequest +from kafka.protocol.produce import ProduceRequest +from kafka.structs import BrokerMetadata + + +@pytest.fixture +def cli(mocker, conn): + client = KafkaClient(api_version=(0, 9)) + mocker.patch.object(client, '_selector') + client.poll(future=client.cluster.request_update()) + return client + + +def test_bootstrap(mocker, conn): + conn.state = ConnectionStates.CONNECTED + cli = KafkaClient(api_version=(0, 9)) + mocker.patch.object(cli, '_selector') + future = cli.cluster.request_update() + cli.poll(future=future) + + assert future.succeeded() + args, kwargs = conn.call_args + assert args == ('localhost', 9092, socket.AF_UNSPEC) + kwargs.pop('state_change_callback') + kwargs.pop('node_id') + assert kwargs == cli.config + conn.send.assert_called_once_with(MetadataRequest[0]([]), blocking=False) + assert cli._bootstrap_fails == 0 + assert cli.cluster.brokers() == set([BrokerMetadata(0, 'foo', 12, None), + BrokerMetadata(1, 'bar', 34, None)]) + + +def test_can_connect(cli, conn): + # Node is not in broker metadata - can't connect + assert not cli._can_connect(2) + + # Node is in broker metadata but not in _conns + assert 0 not in cli._conns + assert cli._can_connect(0) + + # Node is connected, can't reconnect + assert cli._maybe_connect(0) is True + assert not cli._can_connect(0) + + # Node is disconnected, can connect + cli._conns[0].state = ConnectionStates.DISCONNECTED + assert cli._can_connect(0) + + # Node is disconnected, but blacked out + conn.blacked_out.return_value = True + assert not cli._can_connect(0) + + +def test_maybe_connect(cli, conn): + try: + # Node not in metadata, raises AssertionError + cli._maybe_connect(2) + except AssertionError: + pass + else: + assert False, 'Exception not raised' + + # New node_id creates a conn object + assert 0 not in cli._conns + conn.state = ConnectionStates.DISCONNECTED + conn.connect.side_effect = lambda: conn._set_conn_state(ConnectionStates.CONNECTING) + assert cli._maybe_connect(0) is False + assert cli._conns[0] is conn + + +def test_conn_state_change(mocker, cli, conn): + sel = cli._selector + + node_id = 0 + cli._conns[node_id] = conn + conn.state = ConnectionStates.CONNECTING + sock = conn._sock + cli._conn_state_change(node_id, sock, conn) + assert node_id in cli._connecting + sel.register.assert_called_with(sock, selectors.EVENT_WRITE, conn) + + conn.state = ConnectionStates.CONNECTED + cli._conn_state_change(node_id, sock, conn) + assert node_id not in cli._connecting + sel.modify.assert_called_with(sock, selectors.EVENT_READ, conn) + + # Failure to connect should trigger metadata update + assert cli.cluster._need_update is False + conn.state = ConnectionStates.DISCONNECTED + cli._conn_state_change(node_id, sock, conn) + assert node_id not in cli._connecting + assert cli.cluster._need_update is True + sel.unregister.assert_called_with(sock) + + conn.state = ConnectionStates.CONNECTING + cli._conn_state_change(node_id, sock, conn) + assert node_id in cli._connecting + conn.state = ConnectionStates.DISCONNECTED + cli._conn_state_change(node_id, sock, conn) + assert node_id not in cli._connecting + + +def test_ready(mocker, cli, conn): + maybe_connect = mocker.patch.object(cli, 'maybe_connect') + node_id = 1 + cli.ready(node_id) + maybe_connect.assert_called_with(node_id) + + +def test_is_ready(mocker, cli, conn): + cli._maybe_connect(0) + cli._maybe_connect(1) + + # metadata refresh blocks ready nodes + assert cli.is_ready(0) + assert cli.is_ready(1) + cli._metadata_refresh_in_progress = True + assert not cli.is_ready(0) + assert not cli.is_ready(1) + + # requesting metadata update also blocks ready nodes + cli._metadata_refresh_in_progress = False + assert cli.is_ready(0) + assert cli.is_ready(1) + cli.cluster.request_update() + cli.cluster.config['retry_backoff_ms'] = 0 + assert not cli._metadata_refresh_in_progress + assert not cli.is_ready(0) + assert not cli.is_ready(1) + cli.cluster._need_update = False + + # if connection can't send more, not ready + assert cli.is_ready(0) + conn.can_send_more.return_value = False + assert not cli.is_ready(0) + conn.can_send_more.return_value = True + + # disconnected nodes, not ready + assert cli.is_ready(0) + conn.state = ConnectionStates.DISCONNECTED + assert not cli.is_ready(0) + + +def test_close(mocker, cli, conn): + mocker.patch.object(cli, '_selector') + + call_count = conn.close.call_count + + # Unknown node - silent + cli.close(2) + call_count += 0 + assert conn.close.call_count == call_count + + # Single node close + cli._maybe_connect(0) + assert conn.close.call_count == call_count + cli.close(0) + call_count += 1 + assert conn.close.call_count == call_count + + # All node close + cli._maybe_connect(1) + cli.close() + # +2 close: node 1, node bootstrap (node 0 already closed) + call_count += 2 + assert conn.close.call_count == call_count + + +def test_is_disconnected(cli, conn): + # False if not connected yet + conn.state = ConnectionStates.DISCONNECTED + assert not cli.is_disconnected(0) + + cli._maybe_connect(0) + assert cli.is_disconnected(0) + + conn.state = ConnectionStates.CONNECTING + assert not cli.is_disconnected(0) + + conn.state = ConnectionStates.CONNECTED + assert not cli.is_disconnected(0) + + +def test_send(cli, conn): + # Send to unknown node => raises AssertionError + try: + cli.send(2, None) + assert False, 'Exception not raised' + except AssertionError: + pass + + # Send to disconnected node => NodeNotReady + conn.state = ConnectionStates.DISCONNECTED + f = cli.send(0, None) + assert f.failed() + assert isinstance(f.exception, Errors.NodeNotReadyError) + + conn.state = ConnectionStates.CONNECTED + cli._maybe_connect(0) + # ProduceRequest w/ 0 required_acks -> no response + request = ProduceRequest[0](0, 0, []) + assert request.expect_response() is False + ret = cli.send(0, request) + assert conn.send.called_with(request) + assert isinstance(ret, Future) + + request = MetadataRequest[0]([]) + cli.send(0, request) + assert conn.send.called_with(request) + + +def test_poll(mocker): + metadata = mocker.patch.object(KafkaClient, '_maybe_refresh_metadata') + _poll = mocker.patch.object(KafkaClient, '_poll') + ifrs = mocker.patch.object(KafkaClient, 'in_flight_request_count') + ifrs.return_value = 1 + cli = KafkaClient(api_version=(0, 9)) + + # metadata timeout wins + metadata.return_value = 1000 + cli.poll() + _poll.assert_called_with(1.0) + + # user timeout wins + cli.poll(250) + _poll.assert_called_with(0.25) + + # default is request_timeout_ms + metadata.return_value = 1000000 + cli.poll() + _poll.assert_called_with(cli.config['request_timeout_ms'] / 1000.0) + + # If no in-flight-requests, drop timeout to retry_backoff_ms + ifrs.return_value = 0 + cli.poll() + _poll.assert_called_with(cli.config['retry_backoff_ms'] / 1000.0) + + +def test__poll(): + pass + + +def test_in_flight_request_count(): + pass + + +def test_least_loaded_node(): + pass + + +def test_set_topics(mocker): + request_update = mocker.patch.object(ClusterMetadata, 'request_update') + request_update.side_effect = lambda: Future() + cli = KafkaClient(api_version=(0, 10)) + + # replace 'empty' with 'non empty' + request_update.reset_mock() + fut = cli.set_topics(['t1', 't2']) + assert not fut.is_done + request_update.assert_called_with() + + # replace 'non empty' with 'same' + request_update.reset_mock() + fut = cli.set_topics(['t1', 't2']) + assert fut.is_done + assert fut.value == set(['t1', 't2']) + request_update.assert_not_called() + + # replace 'non empty' with 'empty' + request_update.reset_mock() + fut = cli.set_topics([]) + assert fut.is_done + assert fut.value == set() + request_update.assert_not_called() + + +@pytest.fixture +def client(mocker): + _poll = mocker.patch.object(KafkaClient, '_poll') + + cli = KafkaClient(request_timeout_ms=9999999, + reconnect_backoff_ms=2222, + connections_max_idle_ms=float('inf'), + api_version=(0, 9)) + + ttl = mocker.patch.object(cli.cluster, 'ttl') + ttl.return_value = 0 + return cli + + +def test_maybe_refresh_metadata_ttl(mocker, client): + client.cluster.ttl.return_value = 1234 + mocker.patch.object(KafkaClient, 'in_flight_request_count', return_value=1) + + client.poll(timeout_ms=12345678) + client._poll.assert_called_with(1.234) + + +def test_maybe_refresh_metadata_backoff(mocker, client): + mocker.patch.object(KafkaClient, 'in_flight_request_count', return_value=1) + now = time.time() + t = mocker.patch('time.time') + t.return_value = now + + client.poll(timeout_ms=12345678) + client._poll.assert_called_with(2.222) # reconnect backoff + + +def test_maybe_refresh_metadata_in_progress(mocker, client): + client._metadata_refresh_in_progress = True + mocker.patch.object(KafkaClient, 'in_flight_request_count', return_value=1) + + client.poll(timeout_ms=12345678) + client._poll.assert_called_with(9999.999) # request_timeout_ms + + +def test_maybe_refresh_metadata_update(mocker, client): + mocker.patch.object(client, 'least_loaded_node', return_value='foobar') + mocker.patch.object(client, '_can_send_request', return_value=True) + mocker.patch.object(KafkaClient, 'in_flight_request_count', return_value=1) + send = mocker.patch.object(client, 'send') + + client.poll(timeout_ms=12345678) + client._poll.assert_called_with(9999.999) # request_timeout_ms + assert client._metadata_refresh_in_progress + request = MetadataRequest[0]([]) + send.assert_called_once_with('foobar', request, wakeup=False) + + +def test_maybe_refresh_metadata_cant_send(mocker, client): + mocker.patch.object(client, 'least_loaded_node', return_value='foobar') + mocker.patch.object(client, '_can_connect', return_value=True) + mocker.patch.object(client, '_maybe_connect', return_value=True) + mocker.patch.object(client, 'maybe_connect', return_value=True) + mocker.patch.object(KafkaClient, 'in_flight_request_count', return_value=1) + + now = time.time() + t = mocker.patch('time.time') + t.return_value = now + + # first poll attempts connection + client.poll(timeout_ms=12345678) + client._poll.assert_called_with(2.222) # reconnect backoff + client.maybe_connect.assert_called_once_with('foobar', wakeup=False) + + # poll while connecting should not attempt a new connection + client._connecting.add('foobar') + client._can_connect.reset_mock() + client.poll(timeout_ms=12345678) + client._poll.assert_called_with(2.222) # connection timeout (reconnect timeout) + assert not client._can_connect.called + + assert not client._metadata_refresh_in_progress + + +def test_schedule(): + pass + + +def test_unschedule(): + pass + + +def test_idle_connection_manager(mocker): + t = mocker.patch.object(time, 'time') + t.return_value = 0 + + idle = IdleConnectionManager(100) + assert idle.next_check_ms() == float('inf') + + idle.update('foo') + assert not idle.is_expired('foo') + assert idle.poll_expired_connection() is None + assert idle.next_check_ms() == 100 + + t.return_value = 90 / 1000 + assert not idle.is_expired('foo') + assert idle.poll_expired_connection() is None + assert idle.next_check_ms() == 10 + + t.return_value = 100 / 1000 + assert idle.is_expired('foo') + assert idle.next_check_ms() == 0 + + conn_id, conn_ts = idle.poll_expired_connection() + assert conn_id == 'foo' + assert conn_ts == 0 + + idle.remove('foo') + assert idle.next_check_ms() == float('inf') diff --git a/testbed/dpkp__kafka-python/test/test_cluster.py b/testbed/dpkp__kafka-python/test/test_cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..f010c4f71441ee6216675974cea69279261778a9 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_cluster.py @@ -0,0 +1,22 @@ +# pylint: skip-file +from __future__ import absolute_import + +import pytest + +from kafka.cluster import ClusterMetadata +from kafka.protocol.metadata import MetadataResponse + + +def test_empty_broker_list(): + cluster = ClusterMetadata() + assert len(cluster.brokers()) == 0 + + cluster.update_metadata(MetadataResponse[0]( + [(0, 'foo', 12), (1, 'bar', 34)], [])) + assert len(cluster.brokers()) == 2 + + # empty broker list response should be ignored + cluster.update_metadata(MetadataResponse[0]( + [], # empty brokers + [(17, 'foo', []), (17, 'bar', [])])) # topics w/ error + assert len(cluster.brokers()) == 2 diff --git a/testbed/dpkp__kafka-python/test/test_codec.py b/testbed/dpkp__kafka-python/test/test_codec.py new file mode 100644 index 0000000000000000000000000000000000000000..e05707451a022e19a6092ba9dc69c65febee9f75 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_codec.py @@ -0,0 +1,124 @@ +from __future__ import absolute_import + +import platform +import struct + +import pytest +from kafka.vendor.six.moves import range + +from kafka.codec import ( + has_snappy, has_lz4, has_zstd, + gzip_encode, gzip_decode, + snappy_encode, snappy_decode, + lz4_encode, lz4_decode, + lz4_encode_old_kafka, lz4_decode_old_kafka, + zstd_encode, zstd_decode, +) + +from test.testutil import random_string + + +def test_gzip(): + for i in range(1000): + b1 = random_string(100).encode('utf-8') + b2 = gzip_decode(gzip_encode(b1)) + assert b1 == b2 + + +@pytest.mark.skipif(not has_snappy(), reason="Snappy not available") +def test_snappy(): + for i in range(1000): + b1 = random_string(100).encode('utf-8') + b2 = snappy_decode(snappy_encode(b1)) + assert b1 == b2 + + +@pytest.mark.skipif(not has_snappy(), reason="Snappy not available") +def test_snappy_detect_xerial(): + import kafka as kafka1 + _detect_xerial_stream = kafka1.codec._detect_xerial_stream + + header = b'\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01Some extra bytes' + false_header = b'\x01SNAPPY\x00\x00\x00\x01\x00\x00\x00\x01' + default_snappy = snappy_encode(b'foobar' * 50) + random_snappy = snappy_encode(b'SNAPPY' * 50, xerial_compatible=False) + short_data = b'\x01\x02\x03\x04' + + assert _detect_xerial_stream(header) is True + assert _detect_xerial_stream(b'') is False + assert _detect_xerial_stream(b'\x00') is False + assert _detect_xerial_stream(false_header) is False + assert _detect_xerial_stream(default_snappy) is True + assert _detect_xerial_stream(random_snappy) is False + assert _detect_xerial_stream(short_data) is False + + +@pytest.mark.skipif(not has_snappy(), reason="Snappy not available") +def test_snappy_decode_xerial(): + header = b'\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01' + random_snappy = snappy_encode(b'SNAPPY' * 50, xerial_compatible=False) + block_len = len(random_snappy) + random_snappy2 = snappy_encode(b'XERIAL' * 50, xerial_compatible=False) + block_len2 = len(random_snappy2) + + to_test = header \ + + struct.pack('!i', block_len) + random_snappy \ + + struct.pack('!i', block_len2) + random_snappy2 \ + + assert snappy_decode(to_test) == (b'SNAPPY' * 50) + (b'XERIAL' * 50) + + +@pytest.mark.skipif(not has_snappy(), reason="Snappy not available") +def test_snappy_encode_xerial(): + to_ensure = ( + b'\x82SNAPPY\x00\x00\x00\x00\x01\x00\x00\x00\x01' + b'\x00\x00\x00\x18' + b'\xac\x02\x14SNAPPY\xfe\x06\x00\xfe\x06\x00\xfe\x06\x00\xfe\x06\x00\x96\x06\x00' + b'\x00\x00\x00\x18' + b'\xac\x02\x14XERIAL\xfe\x06\x00\xfe\x06\x00\xfe\x06\x00\xfe\x06\x00\x96\x06\x00' + ) + + to_test = (b'SNAPPY' * 50) + (b'XERIAL' * 50) + + compressed = snappy_encode(to_test, xerial_compatible=True, xerial_blocksize=300) + assert compressed == to_ensure + + +@pytest.mark.skipif(not has_lz4() or platform.python_implementation() == 'PyPy', + reason="python-lz4 crashes on old versions of pypy") +def test_lz4(): + for i in range(1000): + b1 = random_string(100).encode('utf-8') + b2 = lz4_decode(lz4_encode(b1)) + assert len(b1) == len(b2) + assert b1 == b2 + + +@pytest.mark.skipif(not has_lz4() or platform.python_implementation() == 'PyPy', + reason="python-lz4 crashes on old versions of pypy") +def test_lz4_old(): + for i in range(1000): + b1 = random_string(100).encode('utf-8') + b2 = lz4_decode_old_kafka(lz4_encode_old_kafka(b1)) + assert len(b1) == len(b2) + assert b1 == b2 + + +@pytest.mark.skipif(not has_lz4() or platform.python_implementation() == 'PyPy', + reason="python-lz4 crashes on old versions of pypy") +def test_lz4_incremental(): + for i in range(1000): + # lz4 max single block size is 4MB + # make sure we test with multiple-blocks + b1 = random_string(100).encode('utf-8') * 50000 + b2 = lz4_decode(lz4_encode(b1)) + assert len(b1) == len(b2) + assert b1 == b2 + + +@pytest.mark.skipif(not has_zstd(), reason="Zstd not available") +def test_zstd(): + for _ in range(1000): + b1 = random_string(100).encode('utf-8') + b2 = zstd_decode(zstd_encode(b1)) + assert b1 == b2 diff --git a/testbed/dpkp__kafka-python/test/test_conn.py b/testbed/dpkp__kafka-python/test/test_conn.py new file mode 100644 index 0000000000000000000000000000000000000000..966f7b34d958402da6fe69aac366cda90d0fa5c9 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_conn.py @@ -0,0 +1,342 @@ +# pylint: skip-file +from __future__ import absolute_import + +from errno import EALREADY, EINPROGRESS, EISCONN, ECONNRESET +import socket + +import mock +import pytest + +from kafka.conn import BrokerConnection, ConnectionStates, collect_hosts +from kafka.protocol.api import RequestHeader +from kafka.protocol.metadata import MetadataRequest +from kafka.protocol.produce import ProduceRequest + +import kafka.errors as Errors + + +@pytest.fixture +def dns_lookup(mocker): + return mocker.patch('kafka.conn.dns_lookup', + return_value=[(socket.AF_INET, + None, None, None, + ('localhost', 9092))]) + +@pytest.fixture +def _socket(mocker): + socket = mocker.MagicMock() + socket.connect_ex.return_value = 0 + mocker.patch('socket.socket', return_value=socket) + return socket + + +@pytest.fixture +def conn(_socket, dns_lookup): + conn = BrokerConnection('localhost', 9092, socket.AF_INET) + return conn + + +@pytest.mark.parametrize("states", [ + (([EINPROGRESS, EALREADY], ConnectionStates.CONNECTING),), + (([EALREADY, EALREADY], ConnectionStates.CONNECTING),), + (([0], ConnectionStates.CONNECTED),), + (([EINPROGRESS, EALREADY], ConnectionStates.CONNECTING), + ([ECONNRESET], ConnectionStates.DISCONNECTED)), + (([EINPROGRESS, EALREADY], ConnectionStates.CONNECTING), + ([EALREADY], ConnectionStates.CONNECTING), + ([EISCONN], ConnectionStates.CONNECTED)), +]) +def test_connect(_socket, conn, states): + assert conn.state is ConnectionStates.DISCONNECTED + + for errno, state in states: + _socket.connect_ex.side_effect = errno + conn.connect() + assert conn.state is state + + +def test_connect_timeout(_socket, conn): + assert conn.state is ConnectionStates.DISCONNECTED + + # Initial connect returns EINPROGRESS + # immediate inline connect returns EALREADY + # second explicit connect returns EALREADY + # third explicit connect returns EALREADY and times out via last_attempt + _socket.connect_ex.side_effect = [EINPROGRESS, EALREADY, EALREADY, EALREADY] + conn.connect() + assert conn.state is ConnectionStates.CONNECTING + conn.connect() + assert conn.state is ConnectionStates.CONNECTING + conn.last_attempt = 0 + conn.connect() + assert conn.state is ConnectionStates.DISCONNECTED + + +def test_blacked_out(conn): + with mock.patch("time.time", return_value=1000): + conn.last_attempt = 0 + assert conn.blacked_out() is False + conn.last_attempt = 1000 + assert conn.blacked_out() is True + + +def test_connection_delay(conn): + with mock.patch("time.time", return_value=1000): + conn.last_attempt = 1000 + assert conn.connection_delay() == conn.config['reconnect_backoff_ms'] + conn.state = ConnectionStates.CONNECTING + assert conn.connection_delay() == float('inf') + conn.state = ConnectionStates.CONNECTED + assert conn.connection_delay() == float('inf') + + +def test_connected(conn): + assert conn.connected() is False + conn.state = ConnectionStates.CONNECTED + assert conn.connected() is True + + +def test_connecting(conn): + assert conn.connecting() is False + conn.state = ConnectionStates.CONNECTING + assert conn.connecting() is True + conn.state = ConnectionStates.CONNECTED + assert conn.connecting() is False + + +def test_send_disconnected(conn): + conn.state = ConnectionStates.DISCONNECTED + f = conn.send('foobar') + assert f.failed() is True + assert isinstance(f.exception, Errors.KafkaConnectionError) + + +def test_send_connecting(conn): + conn.state = ConnectionStates.CONNECTING + f = conn.send('foobar') + assert f.failed() is True + assert isinstance(f.exception, Errors.NodeNotReadyError) + + +def test_send_max_ifr(conn): + conn.state = ConnectionStates.CONNECTED + max_ifrs = conn.config['max_in_flight_requests_per_connection'] + for i in range(max_ifrs): + conn.in_flight_requests[i] = 'foo' + f = conn.send('foobar') + assert f.failed() is True + assert isinstance(f.exception, Errors.TooManyInFlightRequests) + + +def test_send_no_response(_socket, conn): + conn.connect() + assert conn.state is ConnectionStates.CONNECTED + req = ProduceRequest[0](required_acks=0, timeout=0, topics=()) + header = RequestHeader(req, client_id=conn.config['client_id']) + payload_bytes = len(header.encode()) + len(req.encode()) + third = payload_bytes // 3 + remainder = payload_bytes % 3 + _socket.send.side_effect = [4, third, third, third, remainder] + + assert len(conn.in_flight_requests) == 0 + f = conn.send(req) + assert f.succeeded() is True + assert f.value is None + assert len(conn.in_flight_requests) == 0 + + +def test_send_response(_socket, conn): + conn.connect() + assert conn.state is ConnectionStates.CONNECTED + req = MetadataRequest[0]([]) + header = RequestHeader(req, client_id=conn.config['client_id']) + payload_bytes = len(header.encode()) + len(req.encode()) + third = payload_bytes // 3 + remainder = payload_bytes % 3 + _socket.send.side_effect = [4, third, third, third, remainder] + + assert len(conn.in_flight_requests) == 0 + f = conn.send(req) + assert f.is_done is False + assert len(conn.in_flight_requests) == 1 + + +def test_send_error(_socket, conn): + conn.connect() + assert conn.state is ConnectionStates.CONNECTED + req = MetadataRequest[0]([]) + try: + _socket.send.side_effect = ConnectionError + except NameError: + _socket.send.side_effect = socket.error + f = conn.send(req) + assert f.failed() is True + assert isinstance(f.exception, Errors.KafkaConnectionError) + assert _socket.close.call_count == 1 + assert conn.state is ConnectionStates.DISCONNECTED + + +def test_can_send_more(conn): + assert conn.can_send_more() is True + max_ifrs = conn.config['max_in_flight_requests_per_connection'] + for i in range(max_ifrs): + assert conn.can_send_more() is True + conn.in_flight_requests[i] = 'foo' + assert conn.can_send_more() is False + + +def test_recv_disconnected(_socket, conn): + conn.connect() + assert conn.connected() + + req = MetadataRequest[0]([]) + header = RequestHeader(req, client_id=conn.config['client_id']) + payload_bytes = len(header.encode()) + len(req.encode()) + _socket.send.side_effect = [4, payload_bytes] + conn.send(req) + + # Empty data on recv means the socket is disconnected + _socket.recv.return_value = b'' + + # Attempt to receive should mark connection as disconnected + assert conn.connected() + conn.recv() + assert conn.disconnected() + + +def test_recv(_socket, conn): + pass # TODO + + +def test_close(conn): + pass # TODO + + +def test_collect_hosts__happy_path(): + hosts = "127.0.0.1:1234,127.0.0.1" + results = collect_hosts(hosts) + assert set(results) == set([ + ('127.0.0.1', 1234, socket.AF_INET), + ('127.0.0.1', 9092, socket.AF_INET), + ]) + + +def test_collect_hosts__ipv6(): + hosts = "[localhost]:1234,[2001:1000:2000::1],[2001:1000:2000::1]:1234" + results = collect_hosts(hosts) + assert set(results) == set([ + ('localhost', 1234, socket.AF_INET6), + ('2001:1000:2000::1', 9092, socket.AF_INET6), + ('2001:1000:2000::1', 1234, socket.AF_INET6), + ]) + + +def test_collect_hosts__string_list(): + hosts = [ + 'localhost:1234', + 'localhost', + '[localhost]', + '2001::1', + '[2001::1]', + '[2001::1]:1234', + ] + results = collect_hosts(hosts) + assert set(results) == set([ + ('localhost', 1234, socket.AF_UNSPEC), + ('localhost', 9092, socket.AF_UNSPEC), + ('localhost', 9092, socket.AF_INET6), + ('2001::1', 9092, socket.AF_INET6), + ('2001::1', 9092, socket.AF_INET6), + ('2001::1', 1234, socket.AF_INET6), + ]) + + +def test_collect_hosts__with_spaces(): + hosts = "localhost:1234, localhost" + results = collect_hosts(hosts) + assert set(results) == set([ + ('localhost', 1234, socket.AF_UNSPEC), + ('localhost', 9092, socket.AF_UNSPEC), + ]) + + +def test_lookup_on_connect(): + hostname = 'example.org' + port = 9092 + conn = BrokerConnection(hostname, port, socket.AF_UNSPEC) + assert conn.host == hostname + assert conn.port == port + assert conn.afi == socket.AF_UNSPEC + afi1 = socket.AF_INET + sockaddr1 = ('127.0.0.1', 9092) + mock_return1 = [ + (afi1, socket.SOCK_STREAM, 6, '', sockaddr1), + ] + with mock.patch("socket.getaddrinfo", return_value=mock_return1) as m: + conn.connect() + m.assert_called_once_with(hostname, port, 0, socket.SOCK_STREAM) + assert conn._sock_afi == afi1 + assert conn._sock_addr == sockaddr1 + conn.close() + + afi2 = socket.AF_INET6 + sockaddr2 = ('::1', 9092, 0, 0) + mock_return2 = [ + (afi2, socket.SOCK_STREAM, 6, '', sockaddr2), + ] + + with mock.patch("socket.getaddrinfo", return_value=mock_return2) as m: + conn.last_attempt = 0 + conn.connect() + m.assert_called_once_with(hostname, port, 0, socket.SOCK_STREAM) + assert conn._sock_afi == afi2 + assert conn._sock_addr == sockaddr2 + conn.close() + + +def test_relookup_on_failure(): + hostname = 'example.org' + port = 9092 + conn = BrokerConnection(hostname, port, socket.AF_UNSPEC) + assert conn.host == hostname + mock_return1 = [] + with mock.patch("socket.getaddrinfo", return_value=mock_return1) as m: + last_attempt = conn.last_attempt + conn.connect() + m.assert_called_once_with(hostname, port, 0, socket.SOCK_STREAM) + assert conn.disconnected() + assert conn.last_attempt > last_attempt + + afi2 = socket.AF_INET + sockaddr2 = ('127.0.0.2', 9092) + mock_return2 = [ + (afi2, socket.SOCK_STREAM, 6, '', sockaddr2), + ] + + with mock.patch("socket.getaddrinfo", return_value=mock_return2) as m: + conn.last_attempt = 0 + conn.connect() + m.assert_called_once_with(hostname, port, 0, socket.SOCK_STREAM) + assert conn._sock_afi == afi2 + assert conn._sock_addr == sockaddr2 + conn.close() + + +def test_requests_timed_out(conn): + with mock.patch("time.time", return_value=0): + # No in-flight requests, not timed out + assert not conn.requests_timed_out() + + # Single request, timestamp = now (0) + conn.in_flight_requests[0] = ('foo', 0) + assert not conn.requests_timed_out() + + # Add another request w/ timestamp > request_timeout ago + request_timeout = conn.config['request_timeout_ms'] + expired_timestamp = 0 - request_timeout - 1 + conn.in_flight_requests[1] = ('bar', expired_timestamp) + assert conn.requests_timed_out() + + # Drop the expired request and we should be good to go again + conn.in_flight_requests.pop(1) + assert not conn.requests_timed_out() diff --git a/testbed/dpkp__kafka-python/test/test_consumer.py b/testbed/dpkp__kafka-python/test/test_consumer.py new file mode 100644 index 0000000000000000000000000000000000000000..436fe55c02a0947a16385203ac1051575f931ab3 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_consumer.py @@ -0,0 +1,26 @@ +import pytest + +from kafka import KafkaConsumer +from kafka.errors import KafkaConfigurationError + + +class TestKafkaConsumer: + def test_session_timeout_larger_than_request_timeout_raises(self): + with pytest.raises(KafkaConfigurationError): + KafkaConsumer(bootstrap_servers='localhost:9092', api_version=(0, 9), group_id='foo', session_timeout_ms=50000, request_timeout_ms=40000) + + def test_fetch_max_wait_larger_than_request_timeout_raises(self): + with pytest.raises(KafkaConfigurationError): + KafkaConsumer(bootstrap_servers='localhost:9092', fetch_max_wait_ms=50000, request_timeout_ms=40000) + + def test_request_timeout_larger_than_connections_max_idle_ms_raises(self): + with pytest.raises(KafkaConfigurationError): + KafkaConsumer(bootstrap_servers='localhost:9092', api_version=(0, 9), request_timeout_ms=50000, connections_max_idle_ms=40000) + + def test_subscription_copy(self): + consumer = KafkaConsumer('foo', api_version=(0, 10)) + sub = consumer.subscription() + assert sub is not consumer.subscription() + assert sub == set(['foo']) + sub.add('fizz') + assert consumer.subscription() == set(['foo']) diff --git a/testbed/dpkp__kafka-python/test/test_consumer_group.py b/testbed/dpkp__kafka-python/test/test_consumer_group.py new file mode 100644 index 0000000000000000000000000000000000000000..58dc7ebf95114f53134afd6fd21ec70026d8fb1c --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_consumer_group.py @@ -0,0 +1,179 @@ +import collections +import logging +import threading +import time + +import pytest +from kafka.vendor import six + +from kafka.conn import ConnectionStates +from kafka.consumer.group import KafkaConsumer +from kafka.coordinator.base import MemberState +from kafka.structs import TopicPartition + +from test.testutil import env_kafka_version, random_string + + +def get_connect_str(kafka_broker): + return kafka_broker.host + ':' + str(kafka_broker.port) + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_consumer(kafka_broker, topic): + # The `topic` fixture is included because + # 0.8.2 brokers need a topic to function well + consumer = KafkaConsumer(bootstrap_servers=get_connect_str(kafka_broker)) + consumer.poll(500) + assert len(consumer._client._conns) > 0 + node_id = list(consumer._client._conns.keys())[0] + assert consumer._client._conns[node_id].state is ConnectionStates.CONNECTED + consumer.close() + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_consumer_topics(kafka_broker, topic): + consumer = KafkaConsumer(bootstrap_servers=get_connect_str(kafka_broker)) + # Necessary to drive the IO + consumer.poll(500) + assert topic in consumer.topics() + assert len(consumer.partitions_for_topic(topic)) > 0 + consumer.close() + + +@pytest.mark.skipif(env_kafka_version() < (0, 9), reason='Unsupported Kafka Version') +def test_group(kafka_broker, topic): + num_partitions = 4 + connect_str = get_connect_str(kafka_broker) + consumers = {} + stop = {} + threads = {} + messages = collections.defaultdict(list) + group_id = 'test-group-' + random_string(6) + def consumer_thread(i): + assert i not in consumers + assert i not in stop + stop[i] = threading.Event() + consumers[i] = KafkaConsumer(topic, + bootstrap_servers=connect_str, + group_id=group_id, + heartbeat_interval_ms=500) + while not stop[i].is_set(): + for tp, records in six.itervalues(consumers[i].poll(100)): + messages[i][tp].extend(records) + consumers[i].close() + consumers[i] = None + stop[i] = None + + num_consumers = 4 + for i in range(num_consumers): + t = threading.Thread(target=consumer_thread, args=(i,)) + t.start() + threads[i] = t + + try: + timeout = time.time() + 35 + while True: + for c in range(num_consumers): + + # Verify all consumers have been created + if c not in consumers: + break + + # Verify all consumers have an assignment + elif not consumers[c].assignment(): + break + + # If all consumers exist and have an assignment + else: + + logging.info('All consumers have assignment... checking for stable group') + # Verify all consumers are in the same generation + # then log state and break while loop + generations = set([consumer._coordinator._generation.generation_id + for consumer in list(consumers.values())]) + + # New generation assignment is not complete until + # coordinator.rejoining = False + rejoining = any([consumer._coordinator.rejoining + for consumer in list(consumers.values())]) + + if not rejoining and len(generations) == 1: + for c, consumer in list(consumers.items()): + logging.info("[%s] %s %s: %s", c, + consumer._coordinator._generation.generation_id, + consumer._coordinator._generation.member_id, + consumer.assignment()) + break + else: + logging.info('Rejoining: %s, generations: %s', rejoining, generations) + time.sleep(1) + assert time.time() < timeout, "timeout waiting for assignments" + + logging.info('Group stabilized; verifying assignment') + group_assignment = set() + for c in range(num_consumers): + assert len(consumers[c].assignment()) != 0 + assert set.isdisjoint(consumers[c].assignment(), group_assignment) + group_assignment.update(consumers[c].assignment()) + + assert group_assignment == set([ + TopicPartition(topic, partition) + for partition in range(num_partitions)]) + logging.info('Assignment looks good!') + + finally: + logging.info('Shutting down %s consumers', num_consumers) + for c in range(num_consumers): + logging.info('Stopping consumer %s', c) + stop[c].set() + threads[c].join() + threads[c] = None + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_paused(kafka_broker, topic): + consumer = KafkaConsumer(bootstrap_servers=get_connect_str(kafka_broker)) + topics = [TopicPartition(topic, 1)] + consumer.assign(topics) + assert set(topics) == consumer.assignment() + assert set() == consumer.paused() + + consumer.pause(topics[0]) + assert set([topics[0]]) == consumer.paused() + + consumer.resume(topics[0]) + assert set() == consumer.paused() + + consumer.unsubscribe() + assert set() == consumer.paused() + consumer.close() + + +@pytest.mark.skipif(env_kafka_version() < (0, 9), reason='Unsupported Kafka Version') +def test_heartbeat_thread(kafka_broker, topic): + group_id = 'test-group-' + random_string(6) + consumer = KafkaConsumer(topic, + bootstrap_servers=get_connect_str(kafka_broker), + group_id=group_id, + heartbeat_interval_ms=500) + + # poll until we have joined group / have assignment + while not consumer.assignment(): + consumer.poll(timeout_ms=100) + + assert consumer._coordinator.state is MemberState.STABLE + last_poll = consumer._coordinator.heartbeat.last_poll + last_beat = consumer._coordinator.heartbeat.last_send + + timeout = time.time() + 30 + while True: + if time.time() > timeout: + raise RuntimeError('timeout waiting for heartbeat') + if consumer._coordinator.heartbeat.last_send > last_beat: + break + time.sleep(0.5) + + assert consumer._coordinator.heartbeat.last_poll == last_poll + consumer.poll(timeout_ms=100) + assert consumer._coordinator.heartbeat.last_poll > last_poll + consumer.close() diff --git a/testbed/dpkp__kafka-python/test/test_consumer_integration.py b/testbed/dpkp__kafka-python/test/test_consumer_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..90b7ed203013f36b214c57516f8a9a167cd472af --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_consumer_integration.py @@ -0,0 +1,297 @@ +import logging +import time + +from mock import patch +import pytest +from kafka.vendor.six.moves import range + +import kafka.codec +from kafka.errors import UnsupportedCodecError, UnsupportedVersionError +from kafka.structs import TopicPartition, OffsetAndTimestamp + +from test.testutil import Timer, assert_message_count, env_kafka_version, random_string + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_kafka_version_infer(kafka_consumer_factory): + consumer = kafka_consumer_factory() + actual_ver_major_minor = env_kafka_version()[:2] + client = consumer._client + conn = list(client._conns.values())[0] + inferred_ver_major_minor = conn.check_version()[:2] + assert actual_ver_major_minor == inferred_ver_major_minor, \ + "Was expecting inferred broker version to be %s but was %s" % (actual_ver_major_minor, inferred_ver_major_minor) + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_kafka_consumer(kafka_consumer_factory, send_messages): + """Test KafkaConsumer""" + consumer = kafka_consumer_factory(auto_offset_reset='earliest') + send_messages(range(0, 100), partition=0) + send_messages(range(0, 100), partition=1) + cnt = 0 + messages = {0: [], 1: []} + for message in consumer: + logging.debug("Consumed message %s", repr(message)) + cnt += 1 + messages[message.partition].append(message) + if cnt >= 200: + break + + assert_message_count(messages[0], 100) + assert_message_count(messages[1], 100) + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_kafka_consumer_unsupported_encoding( + topic, kafka_producer_factory, kafka_consumer_factory): + # Send a compressed message + producer = kafka_producer_factory(compression_type="gzip") + fut = producer.send(topic, b"simple message" * 200) + fut.get(timeout=5) + producer.close() + + # Consume, but with the related compression codec not available + with patch.object(kafka.codec, "has_gzip") as mocked: + mocked.return_value = False + consumer = kafka_consumer_factory(auto_offset_reset='earliest') + error_msg = "Libraries for gzip compression codec not found" + with pytest.raises(UnsupportedCodecError, match=error_msg): + consumer.poll(timeout_ms=2000) + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +def test_kafka_consumer__blocking(kafka_consumer_factory, topic, send_messages): + TIMEOUT_MS = 500 + consumer = kafka_consumer_factory(auto_offset_reset='earliest', + enable_auto_commit=False, + consumer_timeout_ms=TIMEOUT_MS) + + # Manual assignment avoids overhead of consumer group mgmt + consumer.unsubscribe() + consumer.assign([TopicPartition(topic, 0)]) + + # Ask for 5 messages, nothing in queue, block 500ms + with Timer() as t: + with pytest.raises(StopIteration): + msg = next(consumer) + assert t.interval >= (TIMEOUT_MS / 1000.0) + + send_messages(range(0, 10)) + + # Ask for 5 messages, 10 in queue. Get 5 back, no blocking + messages = [] + with Timer() as t: + for i in range(5): + msg = next(consumer) + messages.append(msg) + assert_message_count(messages, 5) + assert t.interval < (TIMEOUT_MS / 1000.0) + + # Ask for 10 messages, get 5 back, block 500ms + messages = [] + with Timer() as t: + with pytest.raises(StopIteration): + for i in range(10): + msg = next(consumer) + messages.append(msg) + assert_message_count(messages, 5) + assert t.interval >= (TIMEOUT_MS / 1000.0) + + +@pytest.mark.skipif(env_kafka_version() < (0, 8, 1), reason="Requires KAFKA_VERSION >= 0.8.1") +def test_kafka_consumer__offset_commit_resume(kafka_consumer_factory, send_messages): + GROUP_ID = random_string(10) + + send_messages(range(0, 100), partition=0) + send_messages(range(100, 200), partition=1) + + # Start a consumer and grab the first 180 messages + consumer1 = kafka_consumer_factory( + group_id=GROUP_ID, + enable_auto_commit=True, + auto_commit_interval_ms=100, + auto_offset_reset='earliest', + ) + output_msgs1 = [] + for _ in range(180): + m = next(consumer1) + output_msgs1.append(m) + assert_message_count(output_msgs1, 180) + + # Normally we let the pytest fixture `kafka_consumer_factory` handle + # closing as part of its teardown. Here we manually call close() to force + # auto-commit to occur before the second consumer starts. That way the + # second consumer only consumes previously unconsumed messages. + consumer1.close() + + # Start a second consumer to grab 181-200 + consumer2 = kafka_consumer_factory( + group_id=GROUP_ID, + enable_auto_commit=True, + auto_commit_interval_ms=100, + auto_offset_reset='earliest', + ) + output_msgs2 = [] + for _ in range(20): + m = next(consumer2) + output_msgs2.append(m) + assert_message_count(output_msgs2, 20) + + # Verify the second consumer wasn't reconsuming messages that the first + # consumer already saw + assert_message_count(output_msgs1 + output_msgs2, 200) + + +@pytest.mark.skipif(env_kafka_version() < (0, 10, 1), reason="Requires KAFKA_VERSION >= 0.10.1") +def test_kafka_consumer_max_bytes_simple(kafka_consumer_factory, topic, send_messages): + send_messages(range(100, 200), partition=0) + send_messages(range(200, 300), partition=1) + + # Start a consumer + consumer = kafka_consumer_factory( + auto_offset_reset='earliest', fetch_max_bytes=300) + seen_partitions = set() + for i in range(90): + poll_res = consumer.poll(timeout_ms=100) + for partition, msgs in poll_res.items(): + for msg in msgs: + seen_partitions.add(partition) + + # Check that we fetched at least 1 message from both partitions + assert seen_partitions == {TopicPartition(topic, 0), TopicPartition(topic, 1)} + + +@pytest.mark.skipif(env_kafka_version() < (0, 10, 1), reason="Requires KAFKA_VERSION >= 0.10.1") +def test_kafka_consumer_max_bytes_one_msg(kafka_consumer_factory, send_messages): + # We send to only 1 partition so we don't have parallel requests to 2 + # nodes for data. + send_messages(range(100, 200)) + + # Start a consumer. FetchResponse_v3 should always include at least 1 + # full msg, so by setting fetch_max_bytes=1 we should get 1 msg at a time + # But 0.11.0.0 returns 1 MessageSet at a time when the messages are + # stored in the new v2 format by the broker. + # + # DP Note: This is a strange test. The consumer shouldn't care + # how many messages are included in a FetchResponse, as long as it is + # non-zero. I would not mind if we deleted this test. It caused + # a minor headache when testing 0.11.0.0. + group = 'test-kafka-consumer-max-bytes-one-msg-' + random_string(5) + consumer = kafka_consumer_factory( + group_id=group, + auto_offset_reset='earliest', + consumer_timeout_ms=5000, + fetch_max_bytes=1) + + fetched_msgs = [next(consumer) for i in range(10)] + assert_message_count(fetched_msgs, 10) + + +@pytest.mark.skipif(env_kafka_version() < (0, 10, 1), reason="Requires KAFKA_VERSION >= 0.10.1") +def test_kafka_consumer_offsets_for_time(topic, kafka_consumer, kafka_producer): + late_time = int(time.time()) * 1000 + middle_time = late_time - 1000 + early_time = late_time - 2000 + tp = TopicPartition(topic, 0) + + timeout = 10 + early_msg = kafka_producer.send( + topic, partition=0, value=b"first", + timestamp_ms=early_time).get(timeout) + late_msg = kafka_producer.send( + topic, partition=0, value=b"last", + timestamp_ms=late_time).get(timeout) + + consumer = kafka_consumer + offsets = consumer.offsets_for_times({tp: early_time}) + assert len(offsets) == 1 + assert offsets[tp].offset == early_msg.offset + assert offsets[tp].timestamp == early_time + + offsets = consumer.offsets_for_times({tp: middle_time}) + assert offsets[tp].offset == late_msg.offset + assert offsets[tp].timestamp == late_time + + offsets = consumer.offsets_for_times({tp: late_time}) + assert offsets[tp].offset == late_msg.offset + assert offsets[tp].timestamp == late_time + + offsets = consumer.offsets_for_times({}) + assert offsets == {} + + # Out of bound timestamps check + + offsets = consumer.offsets_for_times({tp: 0}) + assert offsets[tp].offset == early_msg.offset + assert offsets[tp].timestamp == early_time + + offsets = consumer.offsets_for_times({tp: 9999999999999}) + assert offsets[tp] is None + + # Beginning/End offsets + + offsets = consumer.beginning_offsets([tp]) + assert offsets == {tp: early_msg.offset} + offsets = consumer.end_offsets([tp]) + assert offsets == {tp: late_msg.offset + 1} + + +@pytest.mark.skipif(env_kafka_version() < (0, 10, 1), reason="Requires KAFKA_VERSION >= 0.10.1") +def test_kafka_consumer_offsets_search_many_partitions(kafka_consumer, kafka_producer, topic): + tp0 = TopicPartition(topic, 0) + tp1 = TopicPartition(topic, 1) + + send_time = int(time.time() * 1000) + timeout = 10 + p0msg = kafka_producer.send( + topic, partition=0, value=b"XXX", + timestamp_ms=send_time).get(timeout) + p1msg = kafka_producer.send( + topic, partition=1, value=b"XXX", + timestamp_ms=send_time).get(timeout) + + consumer = kafka_consumer + offsets = consumer.offsets_for_times({ + tp0: send_time, + tp1: send_time + }) + + assert offsets == { + tp0: OffsetAndTimestamp(p0msg.offset, send_time), + tp1: OffsetAndTimestamp(p1msg.offset, send_time) + } + + offsets = consumer.beginning_offsets([tp0, tp1]) + assert offsets == { + tp0: p0msg.offset, + tp1: p1msg.offset + } + + offsets = consumer.end_offsets([tp0, tp1]) + assert offsets == { + tp0: p0msg.offset + 1, + tp1: p1msg.offset + 1 + } + + +@pytest.mark.skipif(env_kafka_version() >= (0, 10, 1), reason="Requires KAFKA_VERSION < 0.10.1") +def test_kafka_consumer_offsets_for_time_old(kafka_consumer, topic): + consumer = kafka_consumer + tp = TopicPartition(topic, 0) + + with pytest.raises(UnsupportedVersionError): + consumer.offsets_for_times({tp: int(time.time())}) + + +@pytest.mark.skipif(env_kafka_version() < (0, 10, 1), reason="Requires KAFKA_VERSION >= 0.10.1") +def test_kafka_consumer_offsets_for_times_errors(kafka_consumer_factory, topic): + consumer = kafka_consumer_factory(fetch_max_wait_ms=200, + request_timeout_ms=500) + tp = TopicPartition(topic, 0) + bad_tp = TopicPartition(topic, 100) + + with pytest.raises(ValueError): + consumer.offsets_for_times({tp: -1}) + + assert consumer.offsets_for_times({bad_tp: 0}) == {bad_tp: None} diff --git a/testbed/dpkp__kafka-python/test/test_coordinator.py b/testbed/dpkp__kafka-python/test/test_coordinator.py new file mode 100644 index 0000000000000000000000000000000000000000..a35cdd1a0c16d4b0c5f2b0c8396891232d097e5a --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_coordinator.py @@ -0,0 +1,638 @@ +# pylint: skip-file +from __future__ import absolute_import +import time + +import pytest + +from kafka.client_async import KafkaClient +from kafka.consumer.subscription_state import ( + SubscriptionState, ConsumerRebalanceListener) +from kafka.coordinator.assignors.range import RangePartitionAssignor +from kafka.coordinator.assignors.roundrobin import RoundRobinPartitionAssignor +from kafka.coordinator.assignors.sticky.sticky_assignor import StickyPartitionAssignor +from kafka.coordinator.base import Generation, MemberState, HeartbeatThread +from kafka.coordinator.consumer import ConsumerCoordinator +from kafka.coordinator.protocol import ( + ConsumerProtocolMemberMetadata, ConsumerProtocolMemberAssignment) +import kafka.errors as Errors +from kafka.future import Future +from kafka.metrics import Metrics +from kafka.protocol.commit import ( + OffsetCommitRequest, OffsetCommitResponse, + OffsetFetchRequest, OffsetFetchResponse) +from kafka.protocol.metadata import MetadataResponse +from kafka.structs import OffsetAndMetadata, TopicPartition +from kafka.util import WeakMethod + + +@pytest.fixture +def client(conn): + return KafkaClient(api_version=(0, 9)) + +@pytest.fixture +def coordinator(client): + return ConsumerCoordinator(client, SubscriptionState(), Metrics()) + + +def test_init(client, coordinator): + # metadata update on init + assert client.cluster._need_update is True + assert WeakMethod(coordinator._handle_metadata_update) in client.cluster._listeners + + +@pytest.mark.parametrize("api_version", [(0, 8, 0), (0, 8, 1), (0, 8, 2), (0, 9)]) +def test_autocommit_enable_api_version(client, api_version): + coordinator = ConsumerCoordinator(client, SubscriptionState(), + Metrics(), + enable_auto_commit=True, + session_timeout_ms=30000, # session_timeout_ms and max_poll_interval_ms + max_poll_interval_ms=30000, # should be the same to avoid KafkaConfigurationError + group_id='foobar', + api_version=api_version) + if api_version < (0, 8, 1): + assert coordinator.config['enable_auto_commit'] is False + else: + assert coordinator.config['enable_auto_commit'] is True + + +def test_protocol_type(coordinator): + assert coordinator.protocol_type() == 'consumer' + + +def test_group_protocols(coordinator): + # Requires a subscription + try: + coordinator.group_protocols() + except Errors.IllegalStateError: + pass + else: + assert False, 'Exception not raised when expected' + + coordinator._subscription.subscribe(topics=['foobar']) + assert coordinator.group_protocols() == [ + ('range', ConsumerProtocolMemberMetadata( + RangePartitionAssignor.version, + ['foobar'], + b'')), + ('roundrobin', ConsumerProtocolMemberMetadata( + RoundRobinPartitionAssignor.version, + ['foobar'], + b'')), + ('sticky', ConsumerProtocolMemberMetadata( + StickyPartitionAssignor.version, + ['foobar'], + b'')), + ] + + +@pytest.mark.parametrize('api_version', [(0, 8, 0), (0, 8, 1), (0, 8, 2), (0, 9)]) +def test_pattern_subscription(coordinator, api_version): + coordinator.config['api_version'] = api_version + coordinator._subscription.subscribe(pattern='foo') + assert coordinator._subscription.subscription == set([]) + assert coordinator._metadata_snapshot == coordinator._build_metadata_snapshot(coordinator._subscription, {}) + + cluster = coordinator._client.cluster + cluster.update_metadata(MetadataResponse[0]( + # brokers + [(0, 'foo', 12), (1, 'bar', 34)], + # topics + [(0, 'fizz', []), + (0, 'foo1', [(0, 0, 0, [], [])]), + (0, 'foo2', [(0, 0, 1, [], [])])])) + assert coordinator._subscription.subscription == {'foo1', 'foo2'} + + # 0.9 consumers should trigger dynamic partition assignment + if api_version >= (0, 9): + assert coordinator._subscription.assignment == {} + + # earlier consumers get all partitions assigned locally + else: + assert set(coordinator._subscription.assignment.keys()) == {TopicPartition('foo1', 0), + TopicPartition('foo2', 0)} + + +def test_lookup_assignor(coordinator): + assert coordinator._lookup_assignor('roundrobin') is RoundRobinPartitionAssignor + assert coordinator._lookup_assignor('range') is RangePartitionAssignor + assert coordinator._lookup_assignor('sticky') is StickyPartitionAssignor + assert coordinator._lookup_assignor('foobar') is None + + +def test_join_complete(mocker, coordinator): + coordinator._subscription.subscribe(topics=['foobar']) + assignor = RoundRobinPartitionAssignor() + coordinator.config['assignors'] = (assignor,) + mocker.spy(assignor, 'on_assignment') + assert assignor.on_assignment.call_count == 0 + assignment = ConsumerProtocolMemberAssignment(0, [('foobar', [0, 1])], b'') + coordinator._on_join_complete(0, 'member-foo', 'roundrobin', assignment.encode()) + assert assignor.on_assignment.call_count == 1 + assignor.on_assignment.assert_called_with(assignment) + + +def test_join_complete_with_sticky_assignor(mocker, coordinator): + coordinator._subscription.subscribe(topics=['foobar']) + assignor = StickyPartitionAssignor() + coordinator.config['assignors'] = (assignor,) + mocker.spy(assignor, 'on_assignment') + mocker.spy(assignor, 'on_generation_assignment') + assert assignor.on_assignment.call_count == 0 + assert assignor.on_generation_assignment.call_count == 0 + assignment = ConsumerProtocolMemberAssignment(0, [('foobar', [0, 1])], b'') + coordinator._on_join_complete(0, 'member-foo', 'sticky', assignment.encode()) + assert assignor.on_assignment.call_count == 1 + assert assignor.on_generation_assignment.call_count == 1 + assignor.on_assignment.assert_called_with(assignment) + assignor.on_generation_assignment.assert_called_with(0) + + +def test_subscription_listener(mocker, coordinator): + listener = mocker.MagicMock(spec=ConsumerRebalanceListener) + coordinator._subscription.subscribe( + topics=['foobar'], + listener=listener) + + coordinator._on_join_prepare(0, 'member-foo') + assert listener.on_partitions_revoked.call_count == 1 + listener.on_partitions_revoked.assert_called_with(set([])) + + assignment = ConsumerProtocolMemberAssignment(0, [('foobar', [0, 1])], b'') + coordinator._on_join_complete( + 0, 'member-foo', 'roundrobin', assignment.encode()) + assert listener.on_partitions_assigned.call_count == 1 + listener.on_partitions_assigned.assert_called_with({TopicPartition('foobar', 0), TopicPartition('foobar', 1)}) + + +def test_subscription_listener_failure(mocker, coordinator): + listener = mocker.MagicMock(spec=ConsumerRebalanceListener) + coordinator._subscription.subscribe( + topics=['foobar'], + listener=listener) + + # exception raised in listener should not be re-raised by coordinator + listener.on_partitions_revoked.side_effect = Exception('crash') + coordinator._on_join_prepare(0, 'member-foo') + assert listener.on_partitions_revoked.call_count == 1 + + assignment = ConsumerProtocolMemberAssignment(0, [('foobar', [0, 1])], b'') + coordinator._on_join_complete( + 0, 'member-foo', 'roundrobin', assignment.encode()) + assert listener.on_partitions_assigned.call_count == 1 + + +def test_perform_assignment(mocker, coordinator): + member_metadata = { + 'member-foo': ConsumerProtocolMemberMetadata(0, ['foo1'], b''), + 'member-bar': ConsumerProtocolMemberMetadata(0, ['foo1'], b'') + } + assignments = { + 'member-foo': ConsumerProtocolMemberAssignment( + 0, [('foo1', [0])], b''), + 'member-bar': ConsumerProtocolMemberAssignment( + 0, [('foo1', [1])], b'') + } + + mocker.patch.object(RoundRobinPartitionAssignor, 'assign') + RoundRobinPartitionAssignor.assign.return_value = assignments + + ret = coordinator._perform_assignment( + 'member-foo', 'roundrobin', + [(member, metadata.encode()) + for member, metadata in member_metadata.items()]) + + assert RoundRobinPartitionAssignor.assign.call_count == 1 + RoundRobinPartitionAssignor.assign.assert_called_with( + coordinator._client.cluster, member_metadata) + assert ret == assignments + + +def test_on_join_prepare(coordinator): + coordinator._subscription.subscribe(topics=['foobar']) + coordinator._on_join_prepare(0, 'member-foo') + + +def test_need_rejoin(coordinator): + # No subscription - no rejoin + assert coordinator.need_rejoin() is False + + coordinator._subscription.subscribe(topics=['foobar']) + assert coordinator.need_rejoin() is True + + +def test_refresh_committed_offsets_if_needed(mocker, coordinator): + mocker.patch.object(ConsumerCoordinator, 'fetch_committed_offsets', + return_value = { + TopicPartition('foobar', 0): OffsetAndMetadata(123, b''), + TopicPartition('foobar', 1): OffsetAndMetadata(234, b'')}) + coordinator._subscription.assign_from_user([TopicPartition('foobar', 0)]) + assert coordinator._subscription.needs_fetch_committed_offsets is True + coordinator.refresh_committed_offsets_if_needed() + assignment = coordinator._subscription.assignment + assert assignment[TopicPartition('foobar', 0)].committed == OffsetAndMetadata(123, b'') + assert TopicPartition('foobar', 1) not in assignment + assert coordinator._subscription.needs_fetch_committed_offsets is False + + +def test_fetch_committed_offsets(mocker, coordinator): + + # No partitions, no IO polling + mocker.patch.object(coordinator._client, 'poll') + assert coordinator.fetch_committed_offsets([]) == {} + assert coordinator._client.poll.call_count == 0 + + # general case -- send offset fetch request, get successful future + mocker.patch.object(coordinator, 'ensure_coordinator_ready') + mocker.patch.object(coordinator, '_send_offset_fetch_request', + return_value=Future().success('foobar')) + partitions = [TopicPartition('foobar', 0)] + ret = coordinator.fetch_committed_offsets(partitions) + assert ret == 'foobar' + coordinator._send_offset_fetch_request.assert_called_with(partitions) + assert coordinator._client.poll.call_count == 1 + + # Failed future is raised if not retriable + coordinator._send_offset_fetch_request.return_value = Future().failure(AssertionError) + coordinator._client.poll.reset_mock() + try: + coordinator.fetch_committed_offsets(partitions) + except AssertionError: + pass + else: + assert False, 'Exception not raised when expected' + assert coordinator._client.poll.call_count == 1 + + coordinator._client.poll.reset_mock() + coordinator._send_offset_fetch_request.side_effect = [ + Future().failure(Errors.RequestTimedOutError), + Future().success('fizzbuzz')] + + ret = coordinator.fetch_committed_offsets(partitions) + assert ret == 'fizzbuzz' + assert coordinator._client.poll.call_count == 2 # call + retry + + +def test_close(mocker, coordinator): + mocker.patch.object(coordinator, '_maybe_auto_commit_offsets_sync') + mocker.patch.object(coordinator, '_handle_leave_group_response') + mocker.patch.object(coordinator, 'coordinator_unknown', return_value=False) + coordinator.coordinator_id = 0 + coordinator._generation = Generation(1, 'foobar', b'') + coordinator.state = MemberState.STABLE + cli = coordinator._client + mocker.patch.object(cli, 'send', return_value=Future().success('foobar')) + mocker.patch.object(cli, 'poll') + + coordinator.close() + assert coordinator._maybe_auto_commit_offsets_sync.call_count == 1 + coordinator._handle_leave_group_response.assert_called_with('foobar') + + assert coordinator.generation() is None + assert coordinator._generation is Generation.NO_GENERATION + assert coordinator.state is MemberState.UNJOINED + assert coordinator.rejoin_needed is True + + +@pytest.fixture +def offsets(): + return { + TopicPartition('foobar', 0): OffsetAndMetadata(123, b''), + TopicPartition('foobar', 1): OffsetAndMetadata(234, b''), + } + + +def test_commit_offsets_async(mocker, coordinator, offsets): + mocker.patch.object(coordinator._client, 'poll') + mocker.patch.object(coordinator, 'coordinator_unknown', return_value=False) + mocker.patch.object(coordinator, 'ensure_coordinator_ready') + mocker.patch.object(coordinator, '_send_offset_commit_request', + return_value=Future().success('fizzbuzz')) + coordinator.commit_offsets_async(offsets) + assert coordinator._send_offset_commit_request.call_count == 1 + + +def test_commit_offsets_sync(mocker, coordinator, offsets): + mocker.patch.object(coordinator, 'ensure_coordinator_ready') + mocker.patch.object(coordinator, '_send_offset_commit_request', + return_value=Future().success('fizzbuzz')) + cli = coordinator._client + mocker.patch.object(cli, 'poll') + + # No offsets, no calls + assert coordinator.commit_offsets_sync({}) is None + assert coordinator._send_offset_commit_request.call_count == 0 + assert cli.poll.call_count == 0 + + ret = coordinator.commit_offsets_sync(offsets) + assert coordinator._send_offset_commit_request.call_count == 1 + assert cli.poll.call_count == 1 + assert ret == 'fizzbuzz' + + # Failed future is raised if not retriable + coordinator._send_offset_commit_request.return_value = Future().failure(AssertionError) + coordinator._client.poll.reset_mock() + try: + coordinator.commit_offsets_sync(offsets) + except AssertionError: + pass + else: + assert False, 'Exception not raised when expected' + assert coordinator._client.poll.call_count == 1 + + coordinator._client.poll.reset_mock() + coordinator._send_offset_commit_request.side_effect = [ + Future().failure(Errors.RequestTimedOutError), + Future().success('fizzbuzz')] + + ret = coordinator.commit_offsets_sync(offsets) + assert ret == 'fizzbuzz' + assert coordinator._client.poll.call_count == 2 # call + retry + + +@pytest.mark.parametrize( + 'api_version,group_id,enable,error,has_auto_commit,commit_offsets,warn,exc', [ + ((0, 8, 0), 'foobar', True, None, False, False, True, False), + ((0, 8, 1), 'foobar', True, None, True, True, False, False), + ((0, 8, 2), 'foobar', True, None, True, True, False, False), + ((0, 9), 'foobar', False, None, False, False, False, False), + ((0, 9), 'foobar', True, Errors.UnknownMemberIdError(), True, True, True, False), + ((0, 9), 'foobar', True, Errors.IllegalGenerationError(), True, True, True, False), + ((0, 9), 'foobar', True, Errors.RebalanceInProgressError(), True, True, True, False), + ((0, 9), 'foobar', True, Exception(), True, True, False, True), + ((0, 9), 'foobar', True, None, True, True, False, False), + ((0, 9), None, True, None, False, False, True, False), + ]) +def test_maybe_auto_commit_offsets_sync(mocker, api_version, group_id, enable, + error, has_auto_commit, commit_offsets, + warn, exc): + mock_warn = mocker.patch('kafka.coordinator.consumer.log.warning') + mock_exc = mocker.patch('kafka.coordinator.consumer.log.exception') + client = KafkaClient(api_version=api_version) + coordinator = ConsumerCoordinator(client, SubscriptionState(), + Metrics(), + api_version=api_version, + session_timeout_ms=30000, + max_poll_interval_ms=30000, + enable_auto_commit=enable, + group_id=group_id) + commit_sync = mocker.patch.object(coordinator, 'commit_offsets_sync', + side_effect=error) + if has_auto_commit: + assert coordinator.next_auto_commit_deadline is not None + else: + assert coordinator.next_auto_commit_deadline is None + + assert coordinator._maybe_auto_commit_offsets_sync() is None + + if has_auto_commit: + assert coordinator.next_auto_commit_deadline is not None + + assert commit_sync.call_count == (1 if commit_offsets else 0) + assert mock_warn.call_count == (1 if warn else 0) + assert mock_exc.call_count == (1 if exc else 0) + + +@pytest.fixture +def patched_coord(mocker, coordinator): + coordinator._subscription.subscribe(topics=['foobar']) + mocker.patch.object(coordinator, 'coordinator_unknown', return_value=False) + coordinator.coordinator_id = 0 + mocker.patch.object(coordinator, 'coordinator', return_value=0) + coordinator._generation = Generation(0, 'foobar', b'') + coordinator.state = MemberState.STABLE + coordinator.rejoin_needed = False + mocker.patch.object(coordinator, 'need_rejoin', return_value=False) + mocker.patch.object(coordinator._client, 'least_loaded_node', + return_value=1) + mocker.patch.object(coordinator._client, 'ready', return_value=True) + mocker.patch.object(coordinator._client, 'send') + mocker.patch.object(coordinator, '_heartbeat_thread') + mocker.spy(coordinator, '_failed_request') + mocker.spy(coordinator, '_handle_offset_commit_response') + mocker.spy(coordinator, '_handle_offset_fetch_response') + return coordinator + + +def test_send_offset_commit_request_fail(mocker, patched_coord, offsets): + patched_coord.coordinator_unknown.return_value = True + patched_coord.coordinator_id = None + patched_coord.coordinator.return_value = None + + # No offsets + ret = patched_coord._send_offset_commit_request({}) + assert isinstance(ret, Future) + assert ret.succeeded() + + # No coordinator + ret = patched_coord._send_offset_commit_request(offsets) + assert ret.failed() + assert isinstance(ret.exception, Errors.GroupCoordinatorNotAvailableError) + + +@pytest.mark.parametrize('api_version,req_type', [ + ((0, 8, 1), OffsetCommitRequest[0]), + ((0, 8, 2), OffsetCommitRequest[1]), + ((0, 9), OffsetCommitRequest[2])]) +def test_send_offset_commit_request_versions(patched_coord, offsets, + api_version, req_type): + expect_node = 0 + patched_coord.config['api_version'] = api_version + + patched_coord._send_offset_commit_request(offsets) + (node, request), _ = patched_coord._client.send.call_args + assert node == expect_node, 'Unexpected coordinator node' + assert isinstance(request, req_type) + + +def test_send_offset_commit_request_failure(patched_coord, offsets): + _f = Future() + patched_coord._client.send.return_value = _f + future = patched_coord._send_offset_commit_request(offsets) + (node, request), _ = patched_coord._client.send.call_args + error = Exception() + _f.failure(error) + patched_coord._failed_request.assert_called_with(0, request, future, error) + assert future.failed() + assert future.exception is error + + +def test_send_offset_commit_request_success(mocker, patched_coord, offsets): + _f = Future() + patched_coord._client.send.return_value = _f + future = patched_coord._send_offset_commit_request(offsets) + (node, request), _ = patched_coord._client.send.call_args + response = OffsetCommitResponse[0]([('foobar', [(0, 0), (1, 0)])]) + _f.success(response) + patched_coord._handle_offset_commit_response.assert_called_with( + offsets, future, mocker.ANY, response) + + +@pytest.mark.parametrize('response,error,dead', [ + (OffsetCommitResponse[0]([('foobar', [(0, 30), (1, 30)])]), + Errors.GroupAuthorizationFailedError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 12), (1, 12)])]), + Errors.OffsetMetadataTooLargeError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 28), (1, 28)])]), + Errors.InvalidCommitOffsetSizeError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 14), (1, 14)])]), + Errors.GroupLoadInProgressError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 15), (1, 15)])]), + Errors.GroupCoordinatorNotAvailableError, True), + (OffsetCommitResponse[0]([('foobar', [(0, 16), (1, 16)])]), + Errors.NotCoordinatorForGroupError, True), + (OffsetCommitResponse[0]([('foobar', [(0, 7), (1, 7)])]), + Errors.RequestTimedOutError, True), + (OffsetCommitResponse[0]([('foobar', [(0, 25), (1, 25)])]), + Errors.CommitFailedError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 22), (1, 22)])]), + Errors.CommitFailedError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 27), (1, 27)])]), + Errors.CommitFailedError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 17), (1, 17)])]), + Errors.InvalidTopicError, False), + (OffsetCommitResponse[0]([('foobar', [(0, 29), (1, 29)])]), + Errors.TopicAuthorizationFailedError, False), +]) +def test_handle_offset_commit_response(mocker, patched_coord, offsets, + response, error, dead): + future = Future() + patched_coord._handle_offset_commit_response(offsets, future, time.time(), + response) + assert isinstance(future.exception, error) + assert patched_coord.coordinator_id is (None if dead else 0) + + +@pytest.fixture +def partitions(): + return [TopicPartition('foobar', 0), TopicPartition('foobar', 1)] + + +def test_send_offset_fetch_request_fail(mocker, patched_coord, partitions): + patched_coord.coordinator_unknown.return_value = True + patched_coord.coordinator_id = None + patched_coord.coordinator.return_value = None + + # No partitions + ret = patched_coord._send_offset_fetch_request([]) + assert isinstance(ret, Future) + assert ret.succeeded() + assert ret.value == {} + + # No coordinator + ret = patched_coord._send_offset_fetch_request(partitions) + assert ret.failed() + assert isinstance(ret.exception, Errors.GroupCoordinatorNotAvailableError) + + +@pytest.mark.parametrize('api_version,req_type', [ + ((0, 8, 1), OffsetFetchRequest[0]), + ((0, 8, 2), OffsetFetchRequest[1]), + ((0, 9), OffsetFetchRequest[1])]) +def test_send_offset_fetch_request_versions(patched_coord, partitions, + api_version, req_type): + # assuming fixture sets coordinator=0, least_loaded_node=1 + expect_node = 0 + patched_coord.config['api_version'] = api_version + + patched_coord._send_offset_fetch_request(partitions) + (node, request), _ = patched_coord._client.send.call_args + assert node == expect_node, 'Unexpected coordinator node' + assert isinstance(request, req_type) + + +def test_send_offset_fetch_request_failure(patched_coord, partitions): + _f = Future() + patched_coord._client.send.return_value = _f + future = patched_coord._send_offset_fetch_request(partitions) + (node, request), _ = patched_coord._client.send.call_args + error = Exception() + _f.failure(error) + patched_coord._failed_request.assert_called_with(0, request, future, error) + assert future.failed() + assert future.exception is error + + +def test_send_offset_fetch_request_success(patched_coord, partitions): + _f = Future() + patched_coord._client.send.return_value = _f + future = patched_coord._send_offset_fetch_request(partitions) + (node, request), _ = patched_coord._client.send.call_args + response = OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 0), (1, 234, b'', 0)])]) + _f.success(response) + patched_coord._handle_offset_fetch_response.assert_called_with( + future, response) + + +@pytest.mark.parametrize('response,error,dead', [ + (OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 14), (1, 234, b'', 14)])]), + Errors.GroupLoadInProgressError, False), + (OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 16), (1, 234, b'', 16)])]), + Errors.NotCoordinatorForGroupError, True), + (OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 25), (1, 234, b'', 25)])]), + Errors.UnknownMemberIdError, False), + (OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 22), (1, 234, b'', 22)])]), + Errors.IllegalGenerationError, False), + (OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 29), (1, 234, b'', 29)])]), + Errors.TopicAuthorizationFailedError, False), + (OffsetFetchResponse[0]([('foobar', [(0, 123, b'', 0), (1, 234, b'', 0)])]), + None, False), +]) +def test_handle_offset_fetch_response(patched_coord, offsets, + response, error, dead): + future = Future() + patched_coord._handle_offset_fetch_response(future, response) + if error is not None: + assert isinstance(future.exception, error) + else: + assert future.succeeded() + assert future.value == offsets + assert patched_coord.coordinator_id is (None if dead else 0) + + +def test_heartbeat(mocker, patched_coord): + heartbeat = HeartbeatThread(patched_coord) + + assert not heartbeat.enabled and not heartbeat.closed + + heartbeat.enable() + assert heartbeat.enabled + + heartbeat.disable() + assert not heartbeat.enabled + + # heartbeat disables when un-joined + heartbeat.enable() + patched_coord.state = MemberState.UNJOINED + heartbeat._run_once() + assert not heartbeat.enabled + + heartbeat.enable() + patched_coord.state = MemberState.STABLE + mocker.spy(patched_coord, '_send_heartbeat_request') + mocker.patch.object(patched_coord.heartbeat, 'should_heartbeat', return_value=True) + heartbeat._run_once() + assert patched_coord._send_heartbeat_request.call_count == 1 + + heartbeat.close() + assert heartbeat.closed + + +def test_lookup_coordinator_failure(mocker, coordinator): + + mocker.patch.object(coordinator, '_send_group_coordinator_request', + return_value=Future().failure(Exception('foobar'))) + future = coordinator.lookup_coordinator() + assert future.failed() + + +def test_ensure_active_group(mocker, coordinator): + coordinator._subscription.subscribe(topics=['foobar']) + mocker.patch.object(coordinator, 'coordinator_unknown', return_value=False) + mocker.patch.object(coordinator, '_send_join_group_request', return_value=Future().success(True)) + mocker.patch.object(coordinator, 'need_rejoin', side_effect=[True, False]) + mocker.patch.object(coordinator, '_on_join_complete') + mocker.patch.object(coordinator, '_heartbeat_thread') + + coordinator.ensure_active_group() + + coordinator._send_join_group_request.assert_called_once_with() diff --git a/testbed/dpkp__kafka-python/test/test_fetcher.py b/testbed/dpkp__kafka-python/test/test_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..697f8be1f6e32cea126593c60d79dd6c1ad4f80b --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_fetcher.py @@ -0,0 +1,553 @@ +# pylint: skip-file +from __future__ import absolute_import + +import pytest + +from collections import OrderedDict +import itertools +import time + +from kafka.client_async import KafkaClient +from kafka.consumer.fetcher import ( + CompletedFetch, ConsumerRecord, Fetcher, NoOffsetForPartitionError +) +from kafka.consumer.subscription_state import SubscriptionState +from kafka.future import Future +from kafka.metrics import Metrics +from kafka.protocol.fetch import FetchRequest, FetchResponse +from kafka.protocol.offset import OffsetResponse +from kafka.errors import ( + StaleMetadata, LeaderNotAvailableError, NotLeaderForPartitionError, + UnknownTopicOrPartitionError, OffsetOutOfRangeError +) +from kafka.record.memory_records import MemoryRecordsBuilder, MemoryRecords +from kafka.structs import OffsetAndMetadata, TopicPartition + + +@pytest.fixture +def client(mocker): + return mocker.Mock(spec=KafkaClient(bootstrap_servers=(), api_version=(0, 9))) + + +@pytest.fixture +def subscription_state(): + return SubscriptionState() + + +@pytest.fixture +def topic(): + return 'foobar' + + +@pytest.fixture +def fetcher(client, subscription_state, topic): + subscription_state.subscribe(topics=[topic]) + assignment = [TopicPartition(topic, i) for i in range(3)] + subscription_state.assign_from_subscribed(assignment) + for tp in assignment: + subscription_state.seek(tp, 0) + return Fetcher(client, subscription_state, Metrics()) + + +def _build_record_batch(msgs, compression=0): + builder = MemoryRecordsBuilder( + magic=1, compression_type=0, batch_size=9999999) + for msg in msgs: + key, value, timestamp = msg + builder.append(key=key, value=value, timestamp=timestamp, headers=[]) + builder.close() + return builder.buffer() + + +def test_send_fetches(fetcher, topic, mocker): + fetch_requests = [ + FetchRequest[0]( + -1, fetcher.config['fetch_max_wait_ms'], + fetcher.config['fetch_min_bytes'], + [(topic, [ + (0, 0, fetcher.config['max_partition_fetch_bytes']), + (1, 0, fetcher.config['max_partition_fetch_bytes']), + ])]), + FetchRequest[0]( + -1, fetcher.config['fetch_max_wait_ms'], + fetcher.config['fetch_min_bytes'], + [(topic, [ + (2, 0, fetcher.config['max_partition_fetch_bytes']), + ])]) + ] + + mocker.patch.object(fetcher, '_create_fetch_requests', + return_value=dict(enumerate(fetch_requests))) + + ret = fetcher.send_fetches() + for node, request in enumerate(fetch_requests): + fetcher._client.send.assert_any_call(node, request, wakeup=False) + assert len(ret) == len(fetch_requests) + + +@pytest.mark.parametrize(("api_version", "fetch_version"), [ + ((0, 10, 1), 3), + ((0, 10, 0), 2), + ((0, 9), 1), + ((0, 8), 0) +]) +def test_create_fetch_requests(fetcher, mocker, api_version, fetch_version): + fetcher._client.in_flight_request_count.return_value = 0 + fetcher.config['api_version'] = api_version + by_node = fetcher._create_fetch_requests() + requests = by_node.values() + assert all([isinstance(r, FetchRequest[fetch_version]) for r in requests]) + + +def test_update_fetch_positions(fetcher, topic, mocker): + mocker.patch.object(fetcher, '_reset_offset') + partition = TopicPartition(topic, 0) + + # unassigned partition + fetcher.update_fetch_positions([TopicPartition('fizzbuzz', 0)]) + assert fetcher._reset_offset.call_count == 0 + + # fetchable partition (has offset, not paused) + fetcher.update_fetch_positions([partition]) + assert fetcher._reset_offset.call_count == 0 + + # partition needs reset, no committed offset + fetcher._subscriptions.need_offset_reset(partition) + fetcher._subscriptions.assignment[partition].awaiting_reset = False + fetcher.update_fetch_positions([partition]) + fetcher._reset_offset.assert_called_with(partition) + assert fetcher._subscriptions.assignment[partition].awaiting_reset is True + fetcher.update_fetch_positions([partition]) + fetcher._reset_offset.assert_called_with(partition) + + # partition needs reset, has committed offset + fetcher._reset_offset.reset_mock() + fetcher._subscriptions.need_offset_reset(partition) + fetcher._subscriptions.assignment[partition].awaiting_reset = False + fetcher._subscriptions.assignment[partition].committed = OffsetAndMetadata(123, b'') + mocker.patch.object(fetcher._subscriptions, 'seek') + fetcher.update_fetch_positions([partition]) + assert fetcher._reset_offset.call_count == 0 + fetcher._subscriptions.seek.assert_called_with(partition, 123) + + +def test__reset_offset(fetcher, mocker): + tp = TopicPartition("topic", 0) + fetcher._subscriptions.subscribe(topics="topic") + fetcher._subscriptions.assign_from_subscribed([tp]) + fetcher._subscriptions.need_offset_reset(tp) + mocked = mocker.patch.object(fetcher, '_retrieve_offsets') + + mocked.return_value = {tp: (1001, None)} + fetcher._reset_offset(tp) + assert not fetcher._subscriptions.assignment[tp].awaiting_reset + assert fetcher._subscriptions.assignment[tp].position == 1001 + + +def test__send_offset_requests(fetcher, mocker): + tp = TopicPartition("topic_send_offset", 1) + mocked_send = mocker.patch.object(fetcher, "_send_offset_request") + send_futures = [] + + def send_side_effect(*args, **kw): + f = Future() + send_futures.append(f) + return f + mocked_send.side_effect = send_side_effect + + mocked_leader = mocker.patch.object( + fetcher._client.cluster, "leader_for_partition") + # First we report unavailable leader 2 times different ways and later + # always as available + mocked_leader.side_effect = itertools.chain( + [None, -1], itertools.cycle([0])) + + # Leader == None + fut = fetcher._send_offset_requests({tp: 0}) + assert fut.failed() + assert isinstance(fut.exception, StaleMetadata) + assert not mocked_send.called + + # Leader == -1 + fut = fetcher._send_offset_requests({tp: 0}) + assert fut.failed() + assert isinstance(fut.exception, LeaderNotAvailableError) + assert not mocked_send.called + + # Leader == 0, send failed + fut = fetcher._send_offset_requests({tp: 0}) + assert not fut.is_done + assert mocked_send.called + # Check that we bound the futures correctly to chain failure + send_futures.pop().failure(NotLeaderForPartitionError(tp)) + assert fut.failed() + assert isinstance(fut.exception, NotLeaderForPartitionError) + + # Leader == 0, send success + fut = fetcher._send_offset_requests({tp: 0}) + assert not fut.is_done + assert mocked_send.called + # Check that we bound the futures correctly to chain success + send_futures.pop().success({tp: (10, 10000)}) + assert fut.succeeded() + assert fut.value == {tp: (10, 10000)} + + +def test__send_offset_requests_multiple_nodes(fetcher, mocker): + tp1 = TopicPartition("topic_send_offset", 1) + tp2 = TopicPartition("topic_send_offset", 2) + tp3 = TopicPartition("topic_send_offset", 3) + tp4 = TopicPartition("topic_send_offset", 4) + mocked_send = mocker.patch.object(fetcher, "_send_offset_request") + send_futures = [] + + def send_side_effect(node_id, timestamps): + f = Future() + send_futures.append((node_id, timestamps, f)) + return f + mocked_send.side_effect = send_side_effect + + mocked_leader = mocker.patch.object( + fetcher._client.cluster, "leader_for_partition") + mocked_leader.side_effect = itertools.cycle([0, 1]) + + # -- All node succeeded case + tss = OrderedDict([(tp1, 0), (tp2, 0), (tp3, 0), (tp4, 0)]) + fut = fetcher._send_offset_requests(tss) + assert not fut.is_done + assert mocked_send.call_count == 2 + + req_by_node = {} + second_future = None + for node, timestamps, f in send_futures: + req_by_node[node] = timestamps + if node == 0: + # Say tp3 does not have any messages so it's missing + f.success({tp1: (11, 1001)}) + else: + second_future = f + assert req_by_node == { + 0: {tp1: 0, tp3: 0}, + 1: {tp2: 0, tp4: 0} + } + + # We only resolved 1 future so far, so result future is not yet ready + assert not fut.is_done + second_future.success({tp2: (12, 1002), tp4: (14, 1004)}) + assert fut.succeeded() + assert fut.value == {tp1: (11, 1001), tp2: (12, 1002), tp4: (14, 1004)} + + # -- First succeeded second not + del send_futures[:] + fut = fetcher._send_offset_requests(tss) + assert len(send_futures) == 2 + send_futures[0][2].success({tp1: (11, 1001)}) + send_futures[1][2].failure(UnknownTopicOrPartitionError(tp1)) + assert fut.failed() + assert isinstance(fut.exception, UnknownTopicOrPartitionError) + + # -- First fails second succeeded + del send_futures[:] + fut = fetcher._send_offset_requests(tss) + assert len(send_futures) == 2 + send_futures[0][2].failure(UnknownTopicOrPartitionError(tp1)) + send_futures[1][2].success({tp1: (11, 1001)}) + assert fut.failed() + assert isinstance(fut.exception, UnknownTopicOrPartitionError) + + +def test__handle_offset_response(fetcher, mocker): + # Broker returns UnsupportedForMessageFormatError, will omit partition + fut = Future() + res = OffsetResponse[1]([ + ("topic", [(0, 43, -1, -1)]), + ("topic", [(1, 0, 1000, 9999)]) + ]) + fetcher._handle_offset_response(fut, res) + assert fut.succeeded() + assert fut.value == {TopicPartition("topic", 1): (9999, 1000)} + + # Broker returns NotLeaderForPartitionError + fut = Future() + res = OffsetResponse[1]([ + ("topic", [(0, 6, -1, -1)]), + ]) + fetcher._handle_offset_response(fut, res) + assert fut.failed() + assert isinstance(fut.exception, NotLeaderForPartitionError) + + # Broker returns UnknownTopicOrPartitionError + fut = Future() + res = OffsetResponse[1]([ + ("topic", [(0, 3, -1, -1)]), + ]) + fetcher._handle_offset_response(fut, res) + assert fut.failed() + assert isinstance(fut.exception, UnknownTopicOrPartitionError) + + # Broker returns many errors and 1 result + # Will fail on 1st error and return + fut = Future() + res = OffsetResponse[1]([ + ("topic", [(0, 43, -1, -1)]), + ("topic", [(1, 6, -1, -1)]), + ("topic", [(2, 3, -1, -1)]), + ("topic", [(3, 0, 1000, 9999)]) + ]) + fetcher._handle_offset_response(fut, res) + assert fut.failed() + assert isinstance(fut.exception, NotLeaderForPartitionError) + + +def test_fetched_records(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + + msgs = [] + for i in range(10): + msgs.append((None, b"foo", None)) + completed_fetch = CompletedFetch( + tp, 0, 0, [0, 100, _build_record_batch(msgs)], + mocker.MagicMock() + ) + fetcher._completed_fetches.append(completed_fetch) + records, partial = fetcher.fetched_records() + assert tp in records + assert len(records[tp]) == len(msgs) + assert all(map(lambda x: isinstance(x, ConsumerRecord), records[tp])) + assert partial is False + + +@pytest.mark.parametrize(("fetch_request", "fetch_response", "num_partitions"), [ + ( + FetchRequest[0]( + -1, 100, 100, + [('foo', [(0, 0, 1000),])]), + FetchResponse[0]( + [("foo", [(0, 0, 1000, [(0, b'xxx'),])]),]), + 1, + ), + ( + FetchRequest[1]( + -1, 100, 100, + [('foo', [(0, 0, 1000), (1, 0, 1000),])]), + FetchResponse[1]( + 0, + [("foo", [ + (0, 0, 1000, [(0, b'xxx'),]), + (1, 0, 1000, [(0, b'xxx'),]), + ]),]), + 2, + ), + ( + FetchRequest[2]( + -1, 100, 100, + [('foo', [(0, 0, 1000),])]), + FetchResponse[2]( + 0, [("foo", [(0, 0, 1000, [(0, b'xxx'),])]),]), + 1, + ), + ( + FetchRequest[3]( + -1, 100, 100, 10000, + [('foo', [(0, 0, 1000),])]), + FetchResponse[3]( + 0, [("foo", [(0, 0, 1000, [(0, b'xxx'),])]),]), + 1, + ), + ( + FetchRequest[4]( + -1, 100, 100, 10000, 0, + [('foo', [(0, 0, 1000),])]), + FetchResponse[4]( + 0, [("foo", [(0, 0, 1000, 0, [], [(0, b'xxx'),])]),]), + 1, + ), + ( + # This may only be used in broker-broker api calls + FetchRequest[5]( + -1, 100, 100, 10000, 0, + [('foo', [(0, 0, 1000),])]), + FetchResponse[5]( + 0, [("foo", [(0, 0, 1000, 0, 0, [], [(0, b'xxx'),])]),]), + 1, + ), +]) +def test__handle_fetch_response(fetcher, fetch_request, fetch_response, num_partitions): + fetcher._handle_fetch_response(fetch_request, time.time(), fetch_response) + assert len(fetcher._completed_fetches) == num_partitions + + +def test__unpack_message_set(fetcher): + fetcher.config['check_crcs'] = False + tp = TopicPartition('foo', 0) + messages = [ + (None, b"a", None), + (None, b"b", None), + (None, b"c", None), + ] + memory_records = MemoryRecords(_build_record_batch(messages)) + records = list(fetcher._unpack_message_set(tp, memory_records)) + assert len(records) == 3 + assert all(map(lambda x: isinstance(x, ConsumerRecord), records)) + assert records[0].value == b'a' + assert records[1].value == b'b' + assert records[2].value == b'c' + assert records[0].offset == 0 + assert records[1].offset == 1 + assert records[2].offset == 2 + + +def test__message_generator(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + msgs = [] + for i in range(10): + msgs.append((None, b"foo", None)) + completed_fetch = CompletedFetch( + tp, 0, 0, [0, 100, _build_record_batch(msgs)], + mocker.MagicMock() + ) + fetcher._completed_fetches.append(completed_fetch) + for i in range(10): + msg = next(fetcher) + assert isinstance(msg, ConsumerRecord) + assert msg.offset == i + assert msg.value == b'foo' + + +def test__parse_fetched_data(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + msgs = [] + for i in range(10): + msgs.append((None, b"foo", None)) + completed_fetch = CompletedFetch( + tp, 0, 0, [0, 100, _build_record_batch(msgs)], + mocker.MagicMock() + ) + partition_record = fetcher._parse_fetched_data(completed_fetch) + assert isinstance(partition_record, fetcher.PartitionRecords) + assert len(partition_record) == 10 + + +def test__parse_fetched_data__paused(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + msgs = [] + for i in range(10): + msgs.append((None, b"foo", None)) + completed_fetch = CompletedFetch( + tp, 0, 0, [0, 100, _build_record_batch(msgs)], + mocker.MagicMock() + ) + fetcher._subscriptions.pause(tp) + partition_record = fetcher._parse_fetched_data(completed_fetch) + assert partition_record is None + + +def test__parse_fetched_data__stale_offset(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + msgs = [] + for i in range(10): + msgs.append((None, b"foo", None)) + completed_fetch = CompletedFetch( + tp, 10, 0, [0, 100, _build_record_batch(msgs)], + mocker.MagicMock() + ) + partition_record = fetcher._parse_fetched_data(completed_fetch) + assert partition_record is None + + +def test__parse_fetched_data__not_leader(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + completed_fetch = CompletedFetch( + tp, 0, 0, [NotLeaderForPartitionError.errno, -1, None], + mocker.MagicMock() + ) + partition_record = fetcher._parse_fetched_data(completed_fetch) + assert partition_record is None + fetcher._client.cluster.request_update.assert_called_with() + + +def test__parse_fetched_data__unknown_tp(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + completed_fetch = CompletedFetch( + tp, 0, 0, [UnknownTopicOrPartitionError.errno, -1, None], + mocker.MagicMock() + ) + partition_record = fetcher._parse_fetched_data(completed_fetch) + assert partition_record is None + fetcher._client.cluster.request_update.assert_called_with() + + +def test__parse_fetched_data__out_of_range(fetcher, topic, mocker): + fetcher.config['check_crcs'] = False + tp = TopicPartition(topic, 0) + completed_fetch = CompletedFetch( + tp, 0, 0, [OffsetOutOfRangeError.errno, -1, None], + mocker.MagicMock() + ) + partition_record = fetcher._parse_fetched_data(completed_fetch) + assert partition_record is None + assert fetcher._subscriptions.assignment[tp].awaiting_reset is True + + +def test_partition_records_offset(): + """Test that compressed messagesets are handle correctly + when fetch offset is in the middle of the message list + """ + batch_start = 120 + batch_end = 130 + fetch_offset = 123 + tp = TopicPartition('foo', 0) + messages = [ConsumerRecord(tp.topic, tp.partition, i, + None, None, 'key', 'value', [], 'checksum', 0, 0, -1) + for i in range(batch_start, batch_end)] + records = Fetcher.PartitionRecords(fetch_offset, None, messages) + assert len(records) > 0 + msgs = records.take(1) + assert msgs[0].offset == fetch_offset + assert records.fetch_offset == fetch_offset + 1 + msgs = records.take(2) + assert len(msgs) == 2 + assert len(records) > 0 + records.discard() + assert len(records) == 0 + + +def test_partition_records_empty(): + records = Fetcher.PartitionRecords(0, None, []) + assert len(records) == 0 + + +def test_partition_records_no_fetch_offset(): + batch_start = 0 + batch_end = 100 + fetch_offset = 123 + tp = TopicPartition('foo', 0) + messages = [ConsumerRecord(tp.topic, tp.partition, i, + None, None, 'key', 'value', None, 'checksum', 0, 0, -1) + for i in range(batch_start, batch_end)] + records = Fetcher.PartitionRecords(fetch_offset, None, messages) + assert len(records) == 0 + + +def test_partition_records_compacted_offset(): + """Test that messagesets are handle correctly + when the fetch offset points to a message that has been compacted + """ + batch_start = 0 + batch_end = 100 + fetch_offset = 42 + tp = TopicPartition('foo', 0) + messages = [ConsumerRecord(tp.topic, tp.partition, i, + None, None, 'key', 'value', None, 'checksum', 0, 0, -1) + for i in range(batch_start, batch_end) if i != fetch_offset] + records = Fetcher.PartitionRecords(fetch_offset, None, messages) + assert len(records) == batch_end - fetch_offset - 1 + msgs = records.take(1) + assert msgs[0].offset == fetch_offset + 1 diff --git a/testbed/dpkp__kafka-python/test/test_metrics.py b/testbed/dpkp__kafka-python/test/test_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..308ea58315190a25b26392634de208d3a26c75b3 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_metrics.py @@ -0,0 +1,499 @@ +import sys +import time + +import pytest + +from kafka.errors import QuotaViolationError +from kafka.metrics import DictReporter, MetricConfig, MetricName, Metrics, Quota +from kafka.metrics.measurable import AbstractMeasurable +from kafka.metrics.stats import (Avg, Count, Max, Min, Percentile, Percentiles, + Rate, Total) +from kafka.metrics.stats.percentiles import BucketSizing +from kafka.metrics.stats.rate import TimeUnit + +EPS = 0.000001 + + +@pytest.fixture +def time_keeper(): + return TimeKeeper() + + +@pytest.fixture +def config(): + return MetricConfig() + + +@pytest.fixture +def reporter(): + return DictReporter() + + +@pytest.fixture +def metrics(request, config, reporter): + metrics = Metrics(config, [reporter], enable_expiration=True) + yield metrics + metrics.close() + + +def test_MetricName(): + # The Java test only cover the differences between the deprecated + # constructors, so I'm skipping them but doing some other basic testing. + + # In short, metrics should be equal IFF their name, group, and tags are + # the same. Descriptions do not matter. + name1 = MetricName('name', 'group', 'A metric.', {'a': 1, 'b': 2}) + name2 = MetricName('name', 'group', 'A description.', {'a': 1, 'b': 2}) + assert name1 == name2 + + name1 = MetricName('name', 'group', tags={'a': 1, 'b': 2}) + name2 = MetricName('name', 'group', tags={'a': 1, 'b': 2}) + assert name1 == name2 + + name1 = MetricName('foo', 'group') + name2 = MetricName('name', 'group') + assert name1 != name2 + + name1 = MetricName('name', 'foo') + name2 = MetricName('name', 'group') + assert name1 != name2 + + # name and group must be non-empty. Everything else is optional. + with pytest.raises(Exception): + MetricName('', 'group') + with pytest.raises(Exception): + MetricName('name', None) + # tags must be a dict if supplied + with pytest.raises(Exception): + MetricName('name', 'group', tags=set()) + + # Because of the implementation of __eq__ and __hash__, the values of + # a MetricName cannot be mutable. + tags = {'a': 1} + name = MetricName('name', 'group', 'description', tags=tags) + with pytest.raises(AttributeError): + name.name = 'new name' + with pytest.raises(AttributeError): + name.group = 'new name' + with pytest.raises(AttributeError): + name.tags = {} + # tags is a copy, so the instance isn't altered + name.tags['b'] = 2 + assert name.tags == tags + + +def test_simple_stats(mocker, time_keeper, config, metrics): + mocker.patch('time.time', side_effect=time_keeper.time) + + measurable = ConstantMeasurable() + + metrics.add_metric(metrics.metric_name('direct.measurable', 'grp1', + 'The fraction of time an appender waits for space allocation.'), + measurable) + sensor = metrics.sensor('test.sensor') + sensor.add(metrics.metric_name('test.avg', 'grp1'), Avg()) + sensor.add(metrics.metric_name('test.max', 'grp1'), Max()) + sensor.add(metrics.metric_name('test.min', 'grp1'), Min()) + sensor.add(metrics.metric_name('test.rate', 'grp1'), Rate(TimeUnit.SECONDS)) + sensor.add(metrics.metric_name('test.occurences', 'grp1'),Rate(TimeUnit.SECONDS, Count())) + sensor.add(metrics.metric_name('test.count', 'grp1'), Count()) + percentiles = [Percentile(metrics.metric_name('test.median', 'grp1'), 50.0), + Percentile(metrics.metric_name('test.perc99_9', 'grp1'), 99.9)] + sensor.add_compound(Percentiles(100, BucketSizing.CONSTANT, 100, -100, + percentiles=percentiles)) + + sensor2 = metrics.sensor('test.sensor2') + sensor2.add(metrics.metric_name('s2.total', 'grp1'), Total()) + sensor2.record(5.0) + + sum_val = 0 + count = 10 + for i in range(count): + sensor.record(i) + sum_val += i + + # prior to any time passing + elapsed_secs = (config.time_window_ms * (config.samples - 1)) / 1000.0 + assert abs(count / elapsed_secs - + metrics.metrics.get(metrics.metric_name('test.occurences', 'grp1')).value()) \ + < EPS, 'Occurrences(0...%d) = %f' % (count, count / elapsed_secs) + + # pretend 2 seconds passed... + sleep_time_seconds = 2.0 + time_keeper.sleep(sleep_time_seconds) + elapsed_secs += sleep_time_seconds + + assert abs(5.0 - metrics.metrics.get(metrics.metric_name('s2.total', 'grp1')).value()) \ + < EPS, 's2 reflects the constant value' + assert abs(4.5 - metrics.metrics.get(metrics.metric_name('test.avg', 'grp1')).value()) \ + < EPS, 'Avg(0...9) = 4.5' + assert abs((count - 1) - metrics.metrics.get(metrics.metric_name('test.max', 'grp1')).value()) \ + < EPS, 'Max(0...9) = 9' + assert abs(0.0 - metrics.metrics.get(metrics.metric_name('test.min', 'grp1')).value()) \ + < EPS, 'Min(0...9) = 0' + assert abs((sum_val / elapsed_secs) - metrics.metrics.get(metrics.metric_name('test.rate', 'grp1')).value()) \ + < EPS, 'Rate(0...9) = 1.40625' + assert abs((count / elapsed_secs) - metrics.metrics.get(metrics.metric_name('test.occurences', 'grp1')).value()) \ + < EPS, 'Occurrences(0...%d) = %f' % (count, count / elapsed_secs) + assert abs(count - metrics.metrics.get(metrics.metric_name('test.count', 'grp1')).value()) \ + < EPS, 'Count(0...9) = 10' + + +def test_hierarchical_sensors(metrics): + parent1 = metrics.sensor('test.parent1') + parent1.add(metrics.metric_name('test.parent1.count', 'grp1'), Count()) + parent2 = metrics.sensor('test.parent2') + parent2.add(metrics.metric_name('test.parent2.count', 'grp1'), Count()) + child1 = metrics.sensor('test.child1', parents=[parent1, parent2]) + child1.add(metrics.metric_name('test.child1.count', 'grp1'), Count()) + child2 = metrics.sensor('test.child2', parents=[parent1]) + child2.add(metrics.metric_name('test.child2.count', 'grp1'), Count()) + grandchild = metrics.sensor('test.grandchild', parents=[child1]) + grandchild.add(metrics.metric_name('test.grandchild.count', 'grp1'), Count()) + + # increment each sensor one time + parent1.record() + parent2.record() + child1.record() + child2.record() + grandchild.record() + + p1 = parent1.metrics[0].value() + p2 = parent2.metrics[0].value() + c1 = child1.metrics[0].value() + c2 = child2.metrics[0].value() + gc = grandchild.metrics[0].value() + + # each metric should have a count equal to one + its children's count + assert 1.0 == gc + assert 1.0 + gc == c1 + assert 1.0 == c2 + assert 1.0 + c1 == p2 + assert 1.0 + c1 + c2 == p1 + assert [child1, child2] == metrics._children_sensors.get(parent1) + assert [child1] == metrics._children_sensors.get(parent2) + assert metrics._children_sensors.get(grandchild) is None + + +def test_bad_sensor_hierarchy(metrics): + parent = metrics.sensor('parent') + child1 = metrics.sensor('child1', parents=[parent]) + child2 = metrics.sensor('child2', parents=[parent]) + + with pytest.raises(ValueError): + metrics.sensor('gc', parents=[child1, child2]) + + +def test_remove_sensor(metrics): + size = len(metrics.metrics) + parent1 = metrics.sensor('test.parent1') + parent1.add(metrics.metric_name('test.parent1.count', 'grp1'), Count()) + parent2 = metrics.sensor('test.parent2') + parent2.add(metrics.metric_name('test.parent2.count', 'grp1'), Count()) + child1 = metrics.sensor('test.child1', parents=[parent1, parent2]) + child1.add(metrics.metric_name('test.child1.count', 'grp1'), Count()) + child2 = metrics.sensor('test.child2', parents=[parent2]) + child2.add(metrics.metric_name('test.child2.count', 'grp1'), Count()) + grandchild1 = metrics.sensor('test.gchild2', parents=[child2]) + grandchild1.add(metrics.metric_name('test.gchild2.count', 'grp1'), Count()) + + sensor = metrics.get_sensor('test.parent1') + assert sensor is not None + metrics.remove_sensor('test.parent1') + assert metrics.get_sensor('test.parent1') is None + assert metrics.metrics.get(metrics.metric_name('test.parent1.count', 'grp1')) is None + assert metrics.get_sensor('test.child1') is None + assert metrics._children_sensors.get(sensor) is None + assert metrics.metrics.get(metrics.metric_name('test.child1.count', 'grp1')) is None + + sensor = metrics.get_sensor('test.gchild2') + assert sensor is not None + metrics.remove_sensor('test.gchild2') + assert metrics.get_sensor('test.gchild2') is None + assert metrics._children_sensors.get(sensor) is None + assert metrics.metrics.get(metrics.metric_name('test.gchild2.count', 'grp1')) is None + + sensor = metrics.get_sensor('test.child2') + assert sensor is not None + metrics.remove_sensor('test.child2') + assert metrics.get_sensor('test.child2') is None + assert metrics._children_sensors.get(sensor) is None + assert metrics.metrics.get(metrics.metric_name('test.child2.count', 'grp1')) is None + + sensor = metrics.get_sensor('test.parent2') + assert sensor is not None + metrics.remove_sensor('test.parent2') + assert metrics.get_sensor('test.parent2') is None + assert metrics._children_sensors.get(sensor) is None + assert metrics.metrics.get(metrics.metric_name('test.parent2.count', 'grp1')) is None + + assert size == len(metrics.metrics) + + +def test_remove_inactive_metrics(mocker, time_keeper, metrics): + mocker.patch('time.time', side_effect=time_keeper.time) + + s1 = metrics.sensor('test.s1', None, 1) + s1.add(metrics.metric_name('test.s1.count', 'grp1'), Count()) + + s2 = metrics.sensor('test.s2', None, 3) + s2.add(metrics.metric_name('test.s2.count', 'grp1'), Count()) + + purger = Metrics.ExpireSensorTask + purger.run(metrics) + assert metrics.get_sensor('test.s1') is not None, \ + 'Sensor test.s1 must be present' + assert metrics.metrics.get(metrics.metric_name('test.s1.count', 'grp1')) is not None, \ + 'MetricName test.s1.count must be present' + assert metrics.get_sensor('test.s2') is not None, \ + 'Sensor test.s2 must be present' + assert metrics.metrics.get(metrics.metric_name('test.s2.count', 'grp1')) is not None, \ + 'MetricName test.s2.count must be present' + + time_keeper.sleep(1.001) + purger.run(metrics) + assert metrics.get_sensor('test.s1') is None, \ + 'Sensor test.s1 should have been purged' + assert metrics.metrics.get(metrics.metric_name('test.s1.count', 'grp1')) is None, \ + 'MetricName test.s1.count should have been purged' + assert metrics.get_sensor('test.s2') is not None, \ + 'Sensor test.s2 must be present' + assert metrics.metrics.get(metrics.metric_name('test.s2.count', 'grp1')) is not None, \ + 'MetricName test.s2.count must be present' + + # record a value in sensor s2. This should reset the clock for that sensor. + # It should not get purged at the 3 second mark after creation + s2.record() + + time_keeper.sleep(2) + purger.run(metrics) + assert metrics.get_sensor('test.s2') is not None, \ + 'Sensor test.s2 must be present' + assert metrics.metrics.get(metrics.metric_name('test.s2.count', 'grp1')) is not None, \ + 'MetricName test.s2.count must be present' + + # After another 1 second sleep, the metric should be purged + time_keeper.sleep(1) + purger.run(metrics) + assert metrics.get_sensor('test.s1') is None, \ + 'Sensor test.s2 should have been purged' + assert metrics.metrics.get(metrics.metric_name('test.s1.count', 'grp1')) is None, \ + 'MetricName test.s2.count should have been purged' + + # After purging, it should be possible to recreate a metric + s1 = metrics.sensor('test.s1', None, 1) + s1.add(metrics.metric_name('test.s1.count', 'grp1'), Count()) + assert metrics.get_sensor('test.s1') is not None, \ + 'Sensor test.s1 must be present' + assert metrics.metrics.get(metrics.metric_name('test.s1.count', 'grp1')) is not None, \ + 'MetricName test.s1.count must be present' + + +def test_remove_metric(metrics): + size = len(metrics.metrics) + metrics.add_metric(metrics.metric_name('test1', 'grp1'), Count()) + metrics.add_metric(metrics.metric_name('test2', 'grp1'), Count()) + + assert metrics.remove_metric(metrics.metric_name('test1', 'grp1')) is not None + assert metrics.metrics.get(metrics.metric_name('test1', 'grp1')) is None + assert metrics.metrics.get(metrics.metric_name('test2', 'grp1')) is not None + + assert metrics.remove_metric(metrics.metric_name('test2', 'grp1')) is not None + assert metrics.metrics.get(metrics.metric_name('test2', 'grp1')) is None + + assert size == len(metrics.metrics) + + +def test_event_windowing(mocker, time_keeper): + mocker.patch('time.time', side_effect=time_keeper.time) + + count = Count() + config = MetricConfig(event_window=1, samples=2) + count.record(config, 1.0, time_keeper.ms()) + count.record(config, 1.0, time_keeper.ms()) + assert 2.0 == count.measure(config, time_keeper.ms()) + count.record(config, 1.0, time_keeper.ms()) # first event times out + assert 2.0 == count.measure(config, time_keeper.ms()) + + +def test_time_windowing(mocker, time_keeper): + mocker.patch('time.time', side_effect=time_keeper.time) + + count = Count() + config = MetricConfig(time_window_ms=1, samples=2) + count.record(config, 1.0, time_keeper.ms()) + time_keeper.sleep(.001) + count.record(config, 1.0, time_keeper.ms()) + assert 2.0 == count.measure(config, time_keeper.ms()) + time_keeper.sleep(.001) + count.record(config, 1.0, time_keeper.ms()) # oldest event times out + assert 2.0 == count.measure(config, time_keeper.ms()) + + +def test_old_data_has_no_effect(mocker, time_keeper): + mocker.patch('time.time', side_effect=time_keeper.time) + + max_stat = Max() + min_stat = Min() + avg_stat = Avg() + count_stat = Count() + window_ms = 100 + samples = 2 + config = MetricConfig(time_window_ms=window_ms, samples=samples) + max_stat.record(config, 50, time_keeper.ms()) + min_stat.record(config, 50, time_keeper.ms()) + avg_stat.record(config, 50, time_keeper.ms()) + count_stat.record(config, 50, time_keeper.ms()) + + time_keeper.sleep(samples * window_ms / 1000.0) + assert float('-inf') == max_stat.measure(config, time_keeper.ms()) + assert float(sys.maxsize) == min_stat.measure(config, time_keeper.ms()) + assert 0.0 == avg_stat.measure(config, time_keeper.ms()) + assert 0 == count_stat.measure(config, time_keeper.ms()) + + +def test_duplicate_MetricName(metrics): + metrics.sensor('test').add(metrics.metric_name('test', 'grp1'), Avg()) + with pytest.raises(ValueError): + metrics.sensor('test2').add(metrics.metric_name('test', 'grp1'), Total()) + + +def test_Quotas(metrics): + sensor = metrics.sensor('test') + sensor.add(metrics.metric_name('test1.total', 'grp1'), Total(), + MetricConfig(quota=Quota.upper_bound(5.0))) + sensor.add(metrics.metric_name('test2.total', 'grp1'), Total(), + MetricConfig(quota=Quota.lower_bound(0.0))) + sensor.record(5.0) + with pytest.raises(QuotaViolationError): + sensor.record(1.0) + + assert abs(6.0 - metrics.metrics.get(metrics.metric_name('test1.total', 'grp1')).value()) \ + < EPS + + sensor.record(-6.0) + with pytest.raises(QuotaViolationError): + sensor.record(-1.0) + + +def test_Quotas_equality(): + quota1 = Quota.upper_bound(10.5) + quota2 = Quota.lower_bound(10.5) + assert quota1 != quota2, 'Quota with different upper values should not be equal' + + quota3 = Quota.lower_bound(10.5) + assert quota2 == quota3, 'Quota with same upper and bound values should be equal' + + +def test_Percentiles(metrics): + buckets = 100 + _percentiles = [ + Percentile(metrics.metric_name('test.p25', 'grp1'), 25), + Percentile(metrics.metric_name('test.p50', 'grp1'), 50), + Percentile(metrics.metric_name('test.p75', 'grp1'), 75), + ] + percs = Percentiles(4 * buckets, BucketSizing.CONSTANT, 100.0, 0.0, + percentiles=_percentiles) + config = MetricConfig(event_window=50, samples=2) + sensor = metrics.sensor('test', config) + sensor.add_compound(percs) + p25 = metrics.metrics.get(metrics.metric_name('test.p25', 'grp1')) + p50 = metrics.metrics.get(metrics.metric_name('test.p50', 'grp1')) + p75 = metrics.metrics.get(metrics.metric_name('test.p75', 'grp1')) + + # record two windows worth of sequential values + for i in range(buckets): + sensor.record(i) + + assert abs(p25.value() - 25) < 1.0 + assert abs(p50.value() - 50) < 1.0 + assert abs(p75.value() - 75) < 1.0 + + for i in range(buckets): + sensor.record(0.0) + + assert p25.value() < 1.0 + assert p50.value() < 1.0 + assert p75.value() < 1.0 + +def test_rate_windowing(mocker, time_keeper, metrics): + mocker.patch('time.time', side_effect=time_keeper.time) + + # Use the default time window. Set 3 samples + config = MetricConfig(samples=3) + sensor = metrics.sensor('test.sensor', config) + sensor.add(metrics.metric_name('test.rate', 'grp1'), Rate(TimeUnit.SECONDS)) + + sum_val = 0 + count = config.samples - 1 + # Advance 1 window after every record + for i in range(count): + sensor.record(100) + sum_val += 100 + time_keeper.sleep(config.time_window_ms / 1000.0) + + # Sleep for half the window. + time_keeper.sleep(config.time_window_ms / 2.0 / 1000.0) + + # prior to any time passing + elapsed_secs = (config.time_window_ms * (config.samples - 1) + config.time_window_ms / 2.0) / 1000.0 + + kafka_metric = metrics.metrics.get(metrics.metric_name('test.rate', 'grp1')) + assert abs((sum_val / elapsed_secs) - kafka_metric.value()) < EPS, \ + 'Rate(0...2) = 2.666' + assert abs(elapsed_secs - (kafka_metric.measurable.window_size(config, time.time() * 1000) / 1000.0)) \ + < EPS, 'Elapsed Time = 75 seconds' + + +def test_reporter(metrics): + reporter = DictReporter() + foo_reporter = DictReporter(prefix='foo') + metrics.add_reporter(reporter) + metrics.add_reporter(foo_reporter) + sensor = metrics.sensor('kafka.requests') + sensor.add(metrics.metric_name('pack.bean1.avg', 'grp1'), Avg()) + sensor.add(metrics.metric_name('pack.bean2.total', 'grp2'), Total()) + sensor2 = metrics.sensor('kafka.blah') + sensor2.add(metrics.metric_name('pack.bean1.some', 'grp1'), Total()) + sensor2.add(metrics.metric_name('pack.bean2.some', 'grp1', + tags={'a': 42, 'b': 'bar'}), Total()) + + # kafka-metrics-count > count is the total number of metrics and automatic + expected = { + 'kafka-metrics-count': {'count': 5.0}, + 'grp2': {'pack.bean2.total': 0.0}, + 'grp1': {'pack.bean1.avg': 0.0, 'pack.bean1.some': 0.0}, + 'grp1.a=42,b=bar': {'pack.bean2.some': 0.0}, + } + assert expected == reporter.snapshot() + + for key in list(expected.keys()): + metrics = expected.pop(key) + expected['foo.%s' % (key,)] = metrics + assert expected == foo_reporter.snapshot() + + +class ConstantMeasurable(AbstractMeasurable): + _value = 0.0 + + def measure(self, config, now): + return self._value + + +class TimeKeeper(object): + """ + A clock that you can manually advance by calling sleep + """ + def __init__(self, auto_tick_ms=0): + self._millis = time.time() * 1000 + self._auto_tick_ms = auto_tick_ms + + def time(self): + return self.ms() / 1000.0 + + def ms(self): + self.sleep(self._auto_tick_ms) + return self._millis + + def sleep(self, seconds): + self._millis += (seconds * 1000) diff --git a/testbed/dpkp__kafka-python/test/test_object_conversion.py b/testbed/dpkp__kafka-python/test/test_object_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..9b1ff2131f819e59ded7ce4e9a838e88e031e654 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_object_conversion.py @@ -0,0 +1,236 @@ +from kafka.protocol.admin import Request +from kafka.protocol.admin import Response +from kafka.protocol.types import Schema +from kafka.protocol.types import Array +from kafka.protocol.types import Int16 +from kafka.protocol.types import String + +import pytest + +@pytest.mark.parametrize('superclass', (Request, Response)) +class TestObjectConversion: + def test_get_item(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myobject', Int16)) + + tc = TestClass(myobject=0) + assert tc.get_item('myobject') == 0 + with pytest.raises(KeyError): + tc.get_item('does-not-exist') + + def test_with_empty_schema(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema() + + tc = TestClass() + tc.encode() + assert tc.to_object() == {} + + def test_with_basic_schema(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myobject', Int16)) + + tc = TestClass(myobject=0) + tc.encode() + assert tc.to_object() == {'myobject': 0} + + def test_with_basic_array_schema(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myarray', Array(Int16))) + + tc = TestClass(myarray=[1,2,3]) + tc.encode() + assert tc.to_object()['myarray'] == [1, 2, 3] + + def test_with_complex_array_schema(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myarray', Array( + ('subobject', Int16), + ('othersubobject', String('utf-8'))))) + + tc = TestClass( + myarray=[[10, 'hello']] + ) + tc.encode() + obj = tc.to_object() + assert len(obj['myarray']) == 1 + assert obj['myarray'][0]['subobject'] == 10 + assert obj['myarray'][0]['othersubobject'] == 'hello' + + def test_with_array_and_other(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myarray', Array( + ('subobject', Int16), + ('othersubobject', String('utf-8')))), + ('notarray', Int16)) + + tc = TestClass( + myarray=[[10, 'hello']], + notarray=42 + ) + + obj = tc.to_object() + assert len(obj['myarray']) == 1 + assert obj['myarray'][0]['subobject'] == 10 + assert obj['myarray'][0]['othersubobject'] == 'hello' + assert obj['notarray'] == 42 + + def test_with_nested_array(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myarray', Array( + ('subarray', Array(Int16)), + ('otherobject', Int16)))) + + tc = TestClass( + myarray=[ + [[1, 2], 2], + [[2, 3], 4], + ] + ) + print(tc.encode()) + + + obj = tc.to_object() + assert len(obj['myarray']) == 2 + assert obj['myarray'][0]['subarray'] == [1, 2] + assert obj['myarray'][0]['otherobject'] == 2 + assert obj['myarray'][1]['subarray'] == [2, 3] + assert obj['myarray'][1]['otherobject'] == 4 + + def test_with_complex_nested_array(self, superclass): + class TestClass(superclass): + API_KEY = 0 + API_VERSION = 0 + RESPONSE_TYPE = None # To satisfy the Request ABC + SCHEMA = Schema( + ('myarray', Array( + ('subarray', Array( + ('innertest', String('utf-8')), + ('otherinnertest', String('utf-8')))), + ('othersubarray', Array(Int16)))), + ('notarray', String('utf-8'))) + + tc = TestClass( + myarray=[ + [[['hello', 'hello'], ['hello again', 'hello again']], [0]], + [[['hello', 'hello again']], [1]], + ], + notarray='notarray' + ) + tc.encode() + + obj = tc.to_object() + + assert obj['notarray'] == 'notarray' + myarray = obj['myarray'] + assert len(myarray) == 2 + + assert myarray[0]['othersubarray'] == [0] + assert len(myarray[0]['subarray']) == 2 + assert myarray[0]['subarray'][0]['innertest'] == 'hello' + assert myarray[0]['subarray'][0]['otherinnertest'] == 'hello' + assert myarray[0]['subarray'][1]['innertest'] == 'hello again' + assert myarray[0]['subarray'][1]['otherinnertest'] == 'hello again' + + assert myarray[1]['othersubarray'] == [1] + assert len(myarray[1]['subarray']) == 1 + assert myarray[1]['subarray'][0]['innertest'] == 'hello' + assert myarray[1]['subarray'][0]['otherinnertest'] == 'hello again' + +def test_with_metadata_response(): + from kafka.protocol.metadata import MetadataResponse_v5 + tc = MetadataResponse_v5( + throttle_time_ms=0, + brokers=[ + [0, 'testhost0', 9092, 'testrack0'], + [1, 'testhost1', 9092, 'testrack1'], + ], + cluster_id='abcd', + controller_id=0, + topics=[ + [0, 'testtopic1', False, [ + [0, 0, 0, [0, 1], [0, 1], []], + [0, 1, 1, [1, 0], [1, 0], []], + ], + ], [0, 'other-test-topic', True, [ + [0, 0, 0, [0, 1], [0, 1], []], + ] + ]] + ) + tc.encode() # Make sure this object encodes successfully + + + obj = tc.to_object() + + assert obj['throttle_time_ms'] == 0 + + assert len(obj['brokers']) == 2 + assert obj['brokers'][0]['node_id'] == 0 + assert obj['brokers'][0]['host'] == 'testhost0' + assert obj['brokers'][0]['port'] == 9092 + assert obj['brokers'][0]['rack'] == 'testrack0' + assert obj['brokers'][1]['node_id'] == 1 + assert obj['brokers'][1]['host'] == 'testhost1' + assert obj['brokers'][1]['port'] == 9092 + assert obj['brokers'][1]['rack'] == 'testrack1' + + assert obj['cluster_id'] == 'abcd' + assert obj['controller_id'] == 0 + + assert len(obj['topics']) == 2 + assert obj['topics'][0]['error_code'] == 0 + assert obj['topics'][0]['topic'] == 'testtopic1' + assert obj['topics'][0]['is_internal'] == False + assert len(obj['topics'][0]['partitions']) == 2 + assert obj['topics'][0]['partitions'][0]['error_code'] == 0 + assert obj['topics'][0]['partitions'][0]['partition'] == 0 + assert obj['topics'][0]['partitions'][0]['leader'] == 0 + assert obj['topics'][0]['partitions'][0]['replicas'] == [0, 1] + assert obj['topics'][0]['partitions'][0]['isr'] == [0, 1] + assert obj['topics'][0]['partitions'][0]['offline_replicas'] == [] + assert obj['topics'][0]['partitions'][1]['error_code'] == 0 + assert obj['topics'][0]['partitions'][1]['partition'] == 1 + assert obj['topics'][0]['partitions'][1]['leader'] == 1 + assert obj['topics'][0]['partitions'][1]['replicas'] == [1, 0] + assert obj['topics'][0]['partitions'][1]['isr'] == [1, 0] + assert obj['topics'][0]['partitions'][1]['offline_replicas'] == [] + + assert obj['topics'][1]['error_code'] == 0 + assert obj['topics'][1]['topic'] == 'other-test-topic' + assert obj['topics'][1]['is_internal'] == True + assert len(obj['topics'][1]['partitions']) == 1 + assert obj['topics'][1]['partitions'][0]['error_code'] == 0 + assert obj['topics'][1]['partitions'][0]['partition'] == 0 + assert obj['topics'][1]['partitions'][0]['leader'] == 0 + assert obj['topics'][1]['partitions'][0]['replicas'] == [0, 1] + assert obj['topics'][1]['partitions'][0]['isr'] == [0, 1] + assert obj['topics'][1]['partitions'][0]['offline_replicas'] == [] + + tc.encode() diff --git a/testbed/dpkp__kafka-python/test/test_package.py b/testbed/dpkp__kafka-python/test/test_package.py new file mode 100644 index 0000000000000000000000000000000000000000..aa42c9cecfcdc7d2d98c6a03b5a43a2cf5ed1996 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_package.py @@ -0,0 +1,25 @@ +class TestPackage: + def test_top_level_namespace(self): + import kafka as kafka1 + assert kafka1.KafkaConsumer.__name__ == "KafkaConsumer" + assert kafka1.consumer.__name__ == "kafka.consumer" + assert kafka1.codec.__name__ == "kafka.codec" + + def test_submodule_namespace(self): + import kafka.client_async as client1 + assert client1.__name__ == "kafka.client_async" + + from kafka import client_async as client2 + assert client2.__name__ == "kafka.client_async" + + from kafka.client_async import KafkaClient as KafkaClient1 + assert KafkaClient1.__name__ == "KafkaClient" + + from kafka import KafkaClient as KafkaClient2 + assert KafkaClient2.__name__ == "KafkaClient" + + from kafka.codec import gzip_encode as gzip_encode1 + assert gzip_encode1.__name__ == "gzip_encode" + + from kafka.codec import snappy_encode + assert snappy_encode.__name__ == "snappy_encode" diff --git a/testbed/dpkp__kafka-python/test/test_partition_movements.py b/testbed/dpkp__kafka-python/test/test_partition_movements.py new file mode 100644 index 0000000000000000000000000000000000000000..bc990bf3d648e9da1d5fb5d1d8dd1e625057295a --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_partition_movements.py @@ -0,0 +1,23 @@ +from kafka.structs import TopicPartition + +from kafka.coordinator.assignors.sticky.partition_movements import PartitionMovements + + +def test_empty_movements_are_sticky(): + partition_movements = PartitionMovements() + assert partition_movements.are_sticky() + + +def test_sticky_movements(): + partition_movements = PartitionMovements() + partition_movements.move_partition(TopicPartition('t', 1), 'C1', 'C2') + partition_movements.move_partition(TopicPartition('t', 1), 'C2', 'C3') + partition_movements.move_partition(TopicPartition('t', 1), 'C3', 'C1') + assert partition_movements.are_sticky() + + +def test_should_detect_non_sticky_assignment(): + partition_movements = PartitionMovements() + partition_movements.move_partition(TopicPartition('t', 1), 'C1', 'C2') + partition_movements.move_partition(TopicPartition('t', 2), 'C2', 'C1') + assert not partition_movements.are_sticky() diff --git a/testbed/dpkp__kafka-python/test/test_partitioner.py b/testbed/dpkp__kafka-python/test/test_partitioner.py new file mode 100644 index 0000000000000000000000000000000000000000..853fbf69eae8f5567dfd00061ab873598316e96f --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_partitioner.py @@ -0,0 +1,38 @@ +from __future__ import absolute_import + +import pytest + +from kafka.partitioner import DefaultPartitioner, murmur2 + + +def test_default_partitioner(): + partitioner = DefaultPartitioner() + all_partitions = available = list(range(100)) + # partitioner should return the same partition for the same key + p1 = partitioner(b'foo', all_partitions, available) + p2 = partitioner(b'foo', all_partitions, available) + assert p1 == p2 + assert p1 in all_partitions + + # when key is None, choose one of available partitions + assert partitioner(None, all_partitions, [123]) == 123 + + # with fallback to all_partitions + assert partitioner(None, all_partitions, []) in all_partitions + + +@pytest.mark.parametrize("bytes_payload,partition_number", [ + (b'', 681), (b'a', 524), (b'ab', 434), (b'abc', 107), (b'123456789', 566), + (b'\x00 ', 742) +]) +def test_murmur2_java_compatibility(bytes_payload, partition_number): + partitioner = DefaultPartitioner() + all_partitions = available = list(range(1000)) + # compare with output from Kafka's org.apache.kafka.clients.producer.Partitioner + assert partitioner(bytes_payload, all_partitions, available) == partition_number + + +def test_murmur2_not_ascii(): + # Verify no regression of murmur2() bug encoding py2 bytes that don't ascii encode + murmur2(b'\xa4') + murmur2(b'\x81' * 1000) diff --git a/testbed/dpkp__kafka-python/test/test_producer.py b/testbed/dpkp__kafka-python/test/test_producer.py new file mode 100644 index 0000000000000000000000000000000000000000..7263130d110cf93d525f7a49d8f7ee3b9b84eaf8 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_producer.py @@ -0,0 +1,137 @@ +import gc +import platform +import time +import threading + +import pytest + +from kafka import KafkaConsumer, KafkaProducer, TopicPartition +from kafka.producer.buffer import SimpleBufferPool +from test.testutil import env_kafka_version, random_string + + +def test_buffer_pool(): + pool = SimpleBufferPool(1000, 1000) + + buf1 = pool.allocate(1000, 1000) + message = ''.join(map(str, range(100))) + buf1.write(message.encode('utf-8')) + pool.deallocate(buf1) + + buf2 = pool.allocate(1000, 1000) + assert buf2.read() == b'' + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +@pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4', 'zstd']) +def test_end_to_end(kafka_broker, compression): + if compression == 'lz4': + if env_kafka_version() < (0, 8, 2): + pytest.skip('LZ4 requires 0.8.2') + elif platform.python_implementation() == 'PyPy': + pytest.skip('python-lz4 crashes on older versions of pypy') + + if compression == 'zstd' and env_kafka_version() < (2, 1, 0): + pytest.skip('zstd requires kafka 2.1.0 or newer') + + connect_str = ':'.join([kafka_broker.host, str(kafka_broker.port)]) + producer = KafkaProducer(bootstrap_servers=connect_str, + retries=5, + max_block_ms=30000, + compression_type=compression, + value_serializer=str.encode) + consumer = KafkaConsumer(bootstrap_servers=connect_str, + group_id=None, + consumer_timeout_ms=30000, + auto_offset_reset='earliest', + value_deserializer=bytes.decode) + + topic = random_string(5) + + messages = 100 + futures = [] + for i in range(messages): + futures.append(producer.send(topic, 'msg %d' % i)) + ret = [f.get(timeout=30) for f in futures] + assert len(ret) == messages + producer.close() + + consumer.subscribe([topic]) + msgs = set() + for i in range(messages): + try: + msgs.add(next(consumer).value) + except StopIteration: + break + + assert msgs == set(['msg %d' % (i,) for i in range(messages)]) + consumer.close() + + +@pytest.mark.skipif(platform.python_implementation() != 'CPython', + reason='Test relies on CPython-specific gc policies') +def test_kafka_producer_gc_cleanup(): + gc.collect() + threads = threading.active_count() + producer = KafkaProducer(api_version='0.9') # set api_version explicitly to avoid auto-detection + assert threading.active_count() == threads + 1 + del(producer) + gc.collect() + assert threading.active_count() == threads + + +@pytest.mark.skipif(not env_kafka_version(), reason="No KAFKA_VERSION set") +@pytest.mark.parametrize("compression", [None, 'gzip', 'snappy', 'lz4', 'zstd']) +def test_kafka_producer_proper_record_metadata(kafka_broker, compression): + if compression == 'zstd' and env_kafka_version() < (2, 1, 0): + pytest.skip('zstd requires 2.1.0 or more') + connect_str = ':'.join([kafka_broker.host, str(kafka_broker.port)]) + producer = KafkaProducer(bootstrap_servers=connect_str, + retries=5, + max_block_ms=30000, + compression_type=compression) + magic = producer._max_usable_produce_magic() + + # record headers are supported in 0.11.0 + if env_kafka_version() < (0, 11, 0): + headers = None + else: + headers = [("Header Key", b"Header Value")] + + topic = random_string(5) + future = producer.send( + topic, + value=b"Simple value", key=b"Simple key", headers=headers, timestamp_ms=9999999, + partition=0) + record = future.get(timeout=5) + assert record is not None + assert record.topic == topic + assert record.partition == 0 + assert record.topic_partition == TopicPartition(topic, 0) + assert record.offset == 0 + if magic >= 1: + assert record.timestamp == 9999999 + else: + assert record.timestamp == -1 # NO_TIMESTAMP + + if magic >= 2: + assert record.checksum is None + elif magic == 1: + assert record.checksum == 1370034956 + else: + assert record.checksum == 3296137851 + + assert record.serialized_key_size == 10 + assert record.serialized_value_size == 12 + if headers: + assert record.serialized_header_size == 22 + + if magic == 0: + pytest.skip('generated timestamp case is skipped for broker 0.9 and below') + send_time = time.time() * 1000 + future = producer.send( + topic, + value=b"Simple value", key=b"Simple key", timestamp_ms=None, + partition=0) + record = future.get(timeout=5) + assert abs(record.timestamp - send_time) <= 1000 # Allow 1s deviation diff --git a/testbed/dpkp__kafka-python/test/test_protocol.py b/testbed/dpkp__kafka-python/test/test_protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..e295174d4bc58c6fcb9b9a6ced2cd4c3fa5deeff --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_protocol.py @@ -0,0 +1,284 @@ +#pylint: skip-file +import io +import struct + +import pytest + +from kafka.protocol.api import RequestHeader +from kafka.protocol.commit import GroupCoordinatorRequest +from kafka.protocol.fetch import FetchRequest, FetchResponse +from kafka.protocol.message import Message, MessageSet, PartialMessage +from kafka.protocol.metadata import MetadataRequest +from kafka.protocol.types import Int16, Int32, Int64, String + + +def test_create_message(): + payload = b'test' + key = b'key' + msg = Message(payload, key=key) + assert msg.magic == 0 + assert msg.attributes == 0 + assert msg.key == key + assert msg.value == payload + + +def test_encode_message_v0(): + message = Message(b'test', key=b'key') + encoded = message.encode() + expect = b''.join([ + struct.pack('>i', -1427009701), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 3), # Length of key + b'key', # key + struct.pack('>i', 4), # Length of value + b'test', # value + ]) + assert encoded == expect + + +def test_encode_message_v1(): + message = Message(b'test', key=b'key', magic=1, timestamp=1234) + encoded = message.encode() + expect = b''.join([ + struct.pack('>i', 1331087195), # CRC + struct.pack('>bb', 1, 0), # Magic, flags + struct.pack('>q', 1234), # Timestamp + struct.pack('>i', 3), # Length of key + b'key', # key + struct.pack('>i', 4), # Length of value + b'test', # value + ]) + assert encoded == expect + + +def test_decode_message(): + encoded = b''.join([ + struct.pack('>i', -1427009701), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 3), # Length of key + b'key', # key + struct.pack('>i', 4), # Length of value + b'test', # value + ]) + decoded_message = Message.decode(encoded) + msg = Message(b'test', key=b'key') + msg.encode() # crc is recalculated during encoding + assert decoded_message == msg + + +def test_decode_message_validate_crc(): + encoded = b''.join([ + struct.pack('>i', -1427009701), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 3), # Length of key + b'key', # key + struct.pack('>i', 4), # Length of value + b'test', # value + ]) + decoded_message = Message.decode(encoded) + assert decoded_message.validate_crc() is True + + encoded = b''.join([ + struct.pack('>i', 1234), # Incorrect CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 3), # Length of key + b'key', # key + struct.pack('>i', 4), # Length of value + b'test', # value + ]) + decoded_message = Message.decode(encoded) + assert decoded_message.validate_crc() is False + + +def test_encode_message_set(): + messages = [ + Message(b'v1', key=b'k1'), + Message(b'v2', key=b'k2') + ] + encoded = MessageSet.encode([(0, msg.encode()) + for msg in messages]) + expect = b''.join([ + struct.pack('>q', 0), # MsgSet Offset + struct.pack('>i', 18), # Msg Size + struct.pack('>i', 1474775406), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k1', # Key + struct.pack('>i', 2), # Length of value + b'v1', # Value + + struct.pack('>q', 0), # MsgSet Offset + struct.pack('>i', 18), # Msg Size + struct.pack('>i', -16383415), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k2', # Key + struct.pack('>i', 2), # Length of value + b'v2', # Value + ]) + expect = struct.pack('>i', len(expect)) + expect + assert encoded == expect + + +def test_decode_message_set(): + encoded = b''.join([ + struct.pack('>q', 0), # MsgSet Offset + struct.pack('>i', 18), # Msg Size + struct.pack('>i', 1474775406), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k1', # Key + struct.pack('>i', 2), # Length of value + b'v1', # Value + + struct.pack('>q', 1), # MsgSet Offset + struct.pack('>i', 18), # Msg Size + struct.pack('>i', -16383415), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k2', # Key + struct.pack('>i', 2), # Length of value + b'v2', # Value + ]) + + msgs = MessageSet.decode(encoded, bytes_to_read=len(encoded)) + assert len(msgs) == 2 + msg1, msg2 = msgs + + returned_offset1, message1_size, decoded_message1 = msg1 + returned_offset2, message2_size, decoded_message2 = msg2 + + assert returned_offset1 == 0 + message1 = Message(b'v1', key=b'k1') + message1.encode() + assert decoded_message1 == message1 + + assert returned_offset2 == 1 + message2 = Message(b'v2', key=b'k2') + message2.encode() + assert decoded_message2 == message2 + + +def test_encode_message_header(): + expect = b''.join([ + struct.pack('>h', 10), # API Key + struct.pack('>h', 0), # API Version + struct.pack('>i', 4), # Correlation Id + struct.pack('>h', len('client3')), # Length of clientId + b'client3', # ClientId + ]) + + req = GroupCoordinatorRequest[0]('foo') + header = RequestHeader(req, correlation_id=4, client_id='client3') + assert header.encode() == expect + + +def test_decode_message_set_partial(): + encoded = b''.join([ + struct.pack('>q', 0), # Msg Offset + struct.pack('>i', 18), # Msg Size + struct.pack('>i', 1474775406), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k1', # Key + struct.pack('>i', 2), # Length of value + b'v1', # Value + + struct.pack('>q', 1), # Msg Offset + struct.pack('>i', 24), # Msg Size (larger than remaining MsgSet size) + struct.pack('>i', -16383415), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k2', # Key + struct.pack('>i', 8), # Length of value + b'ar', # Value (truncated) + ]) + + msgs = MessageSet.decode(encoded, bytes_to_read=len(encoded)) + assert len(msgs) == 2 + msg1, msg2 = msgs + + returned_offset1, message1_size, decoded_message1 = msg1 + returned_offset2, message2_size, decoded_message2 = msg2 + + assert returned_offset1 == 0 + message1 = Message(b'v1', key=b'k1') + message1.encode() + assert decoded_message1 == message1 + + assert returned_offset2 is None + assert message2_size is None + assert decoded_message2 == PartialMessage() + + +def test_decode_fetch_response_partial(): + encoded = b''.join([ + Int32.encode(1), # Num Topics (Array) + String('utf-8').encode('foobar'), + Int32.encode(2), # Num Partitions (Array) + Int32.encode(0), # Partition id + Int16.encode(0), # Error Code + Int64.encode(1234), # Highwater offset + Int32.encode(52), # MessageSet size + Int64.encode(0), # Msg Offset + Int32.encode(18), # Msg Size + struct.pack('>i', 1474775406), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k1', # Key + struct.pack('>i', 2), # Length of value + b'v1', # Value + + Int64.encode(1), # Msg Offset + struct.pack('>i', 24), # Msg Size (larger than remaining MsgSet size) + struct.pack('>i', -16383415), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k2', # Key + struct.pack('>i', 8), # Length of value + b'ar', # Value (truncated) + Int32.encode(1), + Int16.encode(0), + Int64.encode(2345), + Int32.encode(52), # MessageSet size + Int64.encode(0), # Msg Offset + Int32.encode(18), # Msg Size + struct.pack('>i', 1474775406), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k1', # Key + struct.pack('>i', 2), # Length of value + b'v1', # Value + + Int64.encode(1), # Msg Offset + struct.pack('>i', 24), # Msg Size (larger than remaining MsgSet size) + struct.pack('>i', -16383415), # CRC + struct.pack('>bb', 0, 0), # Magic, flags + struct.pack('>i', 2), # Length of key + b'k2', # Key + struct.pack('>i', 8), # Length of value + b'ar', # Value (truncated) + ]) + resp = FetchResponse[0].decode(io.BytesIO(encoded)) + assert len(resp.topics) == 1 + topic, partitions = resp.topics[0] + assert topic == 'foobar' + assert len(partitions) == 2 + + m1 = MessageSet.decode( + partitions[0][3], bytes_to_read=len(partitions[0][3])) + assert len(m1) == 2 + assert m1[1] == (None, None, PartialMessage()) + + +def test_struct_unrecognized_kwargs(): + try: + mr = MetadataRequest[0](topicz='foo') + assert False, 'Structs should not allow unrecognized kwargs' + except ValueError: + pass + + +def test_struct_missing_kwargs(): + fr = FetchRequest[0](max_wait_time=100) + assert fr.min_bytes is None diff --git a/testbed/dpkp__kafka-python/test/test_sasl_integration.py b/testbed/dpkp__kafka-python/test/test_sasl_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a4813aec33d53f4807eec4435b9d6a2d9da8e9 --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_sasl_integration.py @@ -0,0 +1,80 @@ +import logging +import uuid + +import pytest + +from kafka.admin import NewTopic +from kafka.protocol.metadata import MetadataRequest_v1 +from test.testutil import assert_message_count, env_kafka_version, random_string, special_to_underscore + + +@pytest.fixture( + params=[ + pytest.param( + "PLAIN", marks=pytest.mark.skipif(env_kafka_version() < (0, 10), reason="Requires KAFKA_VERSION >= 0.10") + ), + pytest.param( + "SCRAM-SHA-256", + marks=pytest.mark.skipif(env_kafka_version() < (0, 10, 2), reason="Requires KAFKA_VERSION >= 0.10.2"), + ), + pytest.param( + "SCRAM-SHA-512", + marks=pytest.mark.skipif(env_kafka_version() < (0, 10, 2), reason="Requires KAFKA_VERSION >= 0.10.2"), + ), + ] +) +def sasl_kafka(request, kafka_broker_factory): + sasl_kafka = kafka_broker_factory(transport="SASL_PLAINTEXT", sasl_mechanism=request.param)[0] + yield sasl_kafka + sasl_kafka.child.dump_logs() + + +def test_admin(request, sasl_kafka): + topic_name = special_to_underscore(request.node.name + random_string(4)) + admin, = sasl_kafka.get_admin_clients(1) + admin.create_topics([NewTopic(topic_name, 1, 1)]) + assert topic_name in sasl_kafka.get_topic_names() + + +def test_produce_and_consume(request, sasl_kafka): + topic_name = special_to_underscore(request.node.name + random_string(4)) + sasl_kafka.create_topics([topic_name], num_partitions=2) + producer, = sasl_kafka.get_producers(1) + + messages_and_futures = [] # [(message, produce_future),] + for i in range(100): + encoded_msg = "{}-{}-{}".format(i, request.node.name, uuid.uuid4()).encode("utf-8") + future = producer.send(topic_name, value=encoded_msg, partition=i % 2) + messages_and_futures.append((encoded_msg, future)) + producer.flush() + + for (msg, f) in messages_and_futures: + assert f.succeeded() + + consumer, = sasl_kafka.get_consumers(1, [topic_name]) + messages = {0: [], 1: []} + for i, message in enumerate(consumer, 1): + logging.debug("Consumed message %s", repr(message)) + messages[message.partition].append(message) + if i >= 100: + break + + assert_message_count(messages[0], 50) + assert_message_count(messages[1], 50) + + +def test_client(request, sasl_kafka): + topic_name = special_to_underscore(request.node.name + random_string(4)) + sasl_kafka.create_topics([topic_name], num_partitions=1) + + client, = sasl_kafka.get_clients(1) + request = MetadataRequest_v1(None) + client.send(0, request) + for _ in range(10): + result = client.poll(timeout_ms=10000) + if len(result) > 0: + break + else: + raise RuntimeError("Couldn't fetch topic response from Broker.") + result = result[0] + assert topic_name in [t[1] for t in result.topics] diff --git a/testbed/dpkp__kafka-python/test/test_sender.py b/testbed/dpkp__kafka-python/test/test_sender.py new file mode 100644 index 0000000000000000000000000000000000000000..2a68defcfad634878029c17a7fa1a4f1fa48e9fa --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_sender.py @@ -0,0 +1,53 @@ +# pylint: skip-file +from __future__ import absolute_import + +import pytest +import io + +from kafka.client_async import KafkaClient +from kafka.cluster import ClusterMetadata +from kafka.metrics import Metrics +from kafka.protocol.produce import ProduceRequest +from kafka.producer.record_accumulator import RecordAccumulator, ProducerBatch +from kafka.producer.sender import Sender +from kafka.record.memory_records import MemoryRecordsBuilder +from kafka.structs import TopicPartition + + +@pytest.fixture +def client(mocker): + _cli = mocker.Mock(spec=KafkaClient(bootstrap_servers=(), api_version=(0, 9))) + _cli.cluster = mocker.Mock(spec=ClusterMetadata()) + return _cli + + +@pytest.fixture +def accumulator(): + return RecordAccumulator() + + +@pytest.fixture +def metrics(): + return Metrics() + + +@pytest.fixture +def sender(client, accumulator, metrics): + return Sender(client, client.cluster, accumulator, metrics) + + +@pytest.mark.parametrize(("api_version", "produce_version"), [ + ((0, 10), 2), + ((0, 9), 1), + ((0, 8), 0) +]) +def test_produce_request(sender, mocker, api_version, produce_version): + sender.config['api_version'] = api_version + tp = TopicPartition('foo', 0) + buffer = io.BytesIO() + records = MemoryRecordsBuilder( + magic=1, compression_type=0, batch_size=100000) + batch = ProducerBatch(tp, records, buffer) + records.close() + produce_request = sender._produce_request(0, 0, 0, [batch]) + assert isinstance(produce_request, ProduceRequest[produce_version]) diff --git a/testbed/dpkp__kafka-python/test/test_subscription_state.py b/testbed/dpkp__kafka-python/test/test_subscription_state.py new file mode 100644 index 0000000000000000000000000000000000000000..9718f6af4614894c8237024b9a0eb4060899d61b --- /dev/null +++ b/testbed/dpkp__kafka-python/test/test_subscription_state.py @@ -0,0 +1,25 @@ +# pylint: skip-file +from __future__ import absolute_import + +import pytest + +from kafka.consumer.subscription_state import SubscriptionState + +@pytest.mark.parametrize(('topic_name', 'expectation'), [ + (0, pytest.raises(TypeError)), + (None, pytest.raises(TypeError)), + ('', pytest.raises(ValueError)), + ('.', pytest.raises(ValueError)), + ('..', pytest.raises(ValueError)), + ('a' * 250, pytest.raises(ValueError)), + ('abc/123', pytest.raises(ValueError)), + ('/abc/123', pytest.raises(ValueError)), + ('/abc123', pytest.raises(ValueError)), + ('name with space', pytest.raises(ValueError)), + ('name*with*stars', pytest.raises(ValueError)), + ('name+with+plus', pytest.raises(ValueError)), +]) +def test_topic_name_validation(topic_name, expectation): + state = SubscriptionState() + with expectation: + state._ensure_valid_topic_name(topic_name) diff --git a/testbed/dpkp__kafka-python/test/testutil.py b/testbed/dpkp__kafka-python/test/testutil.py new file mode 100644 index 0000000000000000000000000000000000000000..ec4d70bf67f958242493ce0697235d4d4cd899ee --- /dev/null +++ b/testbed/dpkp__kafka-python/test/testutil.py @@ -0,0 +1,46 @@ +from __future__ import absolute_import + +import os +import random +import re +import string +import time + + +def special_to_underscore(string, _matcher=re.compile(r'[^a-zA-Z0-9_]+')): + return _matcher.sub('_', string) + + +def random_string(length): + return "".join(random.choice(string.ascii_letters) for i in range(length)) + + +def env_kafka_version(): + """Return the Kafka version set in the OS environment as a tuple. + + Example: '0.8.1.1' --> (0, 8, 1, 1) + """ + if 'KAFKA_VERSION' not in os.environ: + return () + return tuple(map(int, os.environ['KAFKA_VERSION'].split('.'))) + + +def assert_message_count(messages, num_messages): + """Check that we received the expected number of messages with no duplicates.""" + # Make sure we got them all + assert len(messages) == num_messages + # Make sure there are no duplicates + # Note: Currently duplicates are identified only using key/value. Other attributes like topic, partition, headers, + # timestamp, etc are ignored... this could be changed if necessary, but will be more tolerant of dupes. + unique_messages = {(m.key, m.value) for m in messages} + assert len(unique_messages) == num_messages + + +class Timer(object): + def __enter__(self): + self.start = time.time() + return self + + def __exit__(self, *args): + self.end = time.time() + self.interval = self.end - self.start diff --git a/testbed/dpkp__kafka-python/tox.ini b/testbed/dpkp__kafka-python/tox.ini new file mode 100644 index 0000000000000000000000000000000000000000..10e9911dc93f57220986714df92ed280cdff4adc --- /dev/null +++ b/testbed/dpkp__kafka-python/tox.ini @@ -0,0 +1,44 @@ +[tox] +envlist = py{26,27,34,35,36,37,38,py}, docs + +[pytest] +testpaths = kafka test +addopts = --durations=10 +log_format = %(created)f %(filename)-23s %(threadName)s %(message)s + +[testenv] +deps = + pytest + pytest-cov + py{27,34,35,36,37,38,py}: pylint + py{27,34,35,36,37,38,py}: pytest-pylint + pytest-mock + mock + python-snappy + zstandard + lz4 + xxhash + crc32c +commands = + py.test {posargs:--pylint --pylint-rcfile=pylint.rc --pylint-error-types=EF --cov=kafka --cov-config=.covrc} +setenv = + CRC32C_SW_MODE = auto + PROJECT_ROOT = {toxinidir} +passenv = KAFKA_VERSION + +[testenv:py26] +# pylint doesn't support python2.6 +commands = py.test {posargs:--cov=kafka --cov-config=.covrc} + +[testenv:pypy] +# pylint is super slow on pypy... +commands = py.test {posargs:--cov=kafka --cov-config=.covrc} + +[testenv:docs] +deps = + sphinx_rtd_theme + sphinx + +commands = + sphinx-apidoc -o docs/apidoc/ kafka/ + sphinx-build -b html docs/ docs/_build diff --git a/testbed/dpkp__kafka-python/travis_java_install.sh b/testbed/dpkp__kafka-python/travis_java_install.sh new file mode 100644 index 0000000000000000000000000000000000000000..f662ce27441e765a37ba94e035dcd92d953c169a --- /dev/null +++ b/testbed/dpkp__kafka-python/travis_java_install.sh @@ -0,0 +1,25 @@ +#!/bin/bash + +# borrowed from: https://github.com/mansenfranzen/pywrangler/blob/master/tests/travis_java_install.sh + +# Kafka requires Java 8 in order to work properly. However, TravisCI's Ubuntu +# 16.04 ships with Java 11 and Java can't be set with `jdk` when python is +# selected as language. Ubuntu 14.04 does not work due to missing python 3.7 +# support on TravisCI which does have Java 8 as default. + +# show current JAVA_HOME and java version +echo "Current JAVA_HOME: $JAVA_HOME" +echo "Current java -version:" +which java +java -version + +echo "Updating JAVA_HOME" +# change JAVA_HOME to Java 8 +export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-amd64 + +echo "Updating PATH" +export PATH=${PATH/\/usr\/local\/lib\/jvm\/openjdk11\/bin/$JAVA_HOME\/bin} + +echo "New java -version" +which java +java -version diff --git a/testbed/embeddings-benchmark__mteb/.github/pull_request_template.md b/testbed/embeddings-benchmark__mteb/.github/pull_request_template.md new file mode 100644 index 0000000000000000000000000000000000000000..6f593414dd3f514ae204e401efafc142e90b2e2f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.github/pull_request_template.md @@ -0,0 +1,26 @@ + + + + + + +## Checklist for adding MMTEB dataset + + +Reason for dataset addition: + + + +- [ ] I have tested that the dataset runs with the `mteb` package. +- [ ] I have run the following models on the task (adding the results to the pr). These can be run using the `mteb -m {model_name} -t {task_name}` command. + - [ ] `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` + - [ ] `intfloat/multilingual-e5-small` +- [ ] I have checked that the performance is neither trivial (both models gain close to perfect scores) nor random (both models gain close to random scores). +- [ ] If the dataset is too big (e.g. >2048 examples), considering using `self.stratified_subsampling() under dataset_transform()` +- [ ] I have filled out the metadata object in the dataset file (find documentation on it [here](https://github.com/embeddings-benchmark/mteb/blob/main/docs/adding_a_dataset.md#2-creating-the-metadata-object)). +- [ ] Run tests locally to make sure nothing is broken using `make test`. +- [ ] Run the formatter to format the code using `make lint`. +- [ ] I have added points for my submission to the [points folder](https://github.com/embeddings-benchmark/mteb/blob/main/docs/mmteb/points.md) using the PR number as the filename (e.g. `438.jsonl`). diff --git a/testbed/embeddings-benchmark__mteb/.github/workflows/docs.yml b/testbed/embeddings-benchmark__mteb/.github/workflows/docs.yml new file mode 100644 index 0000000000000000000000000000000000000000..52e1deba664bc8a1f141442891a1414a5631f67c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.github/workflows/docs.yml @@ -0,0 +1,42 @@ +# GitHub action for the task table generation. + +name: documentation + +on: + push: + branches: [main] + +jobs: + create-table: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + token: ${{ secrets.RELEASE }} + + - uses: actions/setup-python@v4 + with: + python-version: "3.10" + cache: "pip" + + - name: Install dependencies + run: | + make install + + - name: Create table + run: python docs/create_tasks_table.py + + - name: Push table + if: github.event_name == 'push' + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + # Check if changes exist + if git diff --quiet; then + echo "No changes detected" + else + git add docs/tasks.md + git commit -m "Update tasks table" + git push + fi + \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/.github/workflows/lint.yml b/testbed/embeddings-benchmark__mteb/.github/workflows/lint.yml new file mode 100644 index 0000000000000000000000000000000000000000..861c2e6ba619e442162083f25011a4a117e23240 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.github/workflows/lint.yml @@ -0,0 +1,28 @@ +# GitHub action to run linting + +name: run-linting + +on: + push: + branches: [main] + pull_request: + +jobs: + lint: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-python@v4 + with: + python-version: "3.8" + cache: "pip" + + - name: Install dependencies + run: make install + + - name: Lint + id: lint + run: | + make lint-check + diff --git a/testbed/embeddings-benchmark__mteb/.github/workflows/mmteb.yml b/testbed/embeddings-benchmark__mteb/.github/workflows/mmteb.yml new file mode 100644 index 0000000000000000000000000000000000000000..6ae21152f21b31544f690e8ca4c09e94975b97b9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.github/workflows/mmteb.yml @@ -0,0 +1,63 @@ +# GitHub action for the mmteb contributions +# this way the CI related to the mmteb contributions will be separated from the linting CI + +name: mmteb + +on: + push: + branches: [main] + pull_request: + +jobs: + check-points: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - uses: actions/setup-python@v4 + with: + python-version: "3.8" + cache: "pip" + + - name: Install dependencies + run: | + pip install jsonlines pydantic + + - name: Validate jsonl points files + run: python docs/mmteb/validate_points.py + + create-table: + # only run on push to main + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + runs-on: ubuntu-latest + needs: check-points + steps: + - uses: actions/checkout@v3 + with: + token: ${{ secrets.RELEASE }} + + - uses: actions/setup-python@v4 + with: + python-version: "3.8" + cache: "pip" + + - name: Install dependencies + run: | + pip install pandas tabulate # for the table creation + + - name: Create table + run: python docs/mmteb/create_points_table.py + + - name: Push table + run: | + git config --global user.email "github-actions[bot]@users.noreply.github.com" + git config --global user.name "github-actions[bot]" + # Check if changes exist in points_table.md + if git diff --quiet; then + echo "No changes detected" + else + git add docs/mmteb/points_table.md + git commit -m "Update points table" + git push + fi + \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/.github/workflows/release.yml b/testbed/embeddings-benchmark__mteb/.github/workflows/release.yml new file mode 100644 index 0000000000000000000000000000000000000000..510e02bbc06f23b864931e83f69465efcfc730f6 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.github/workflows/release.yml @@ -0,0 +1,51 @@ +# This workflow will +# - Find the latest version tag based on the commit history +# - Create a git tag for the new version +# - Update the version number in pyproject.toml based on the commit history +# - Upload the package to PyPI +# - Create a release on GitHub + +# This workflow required the following secrets to be set: +# - a GitHub personal access token with the `repo` scope called `RELEASE` +# - and that you setup trusted publishing using PyPI as described here: https://blog.pypi.org/posts/2023-04-20-introducing-trusted-publishers/ + +name: Release +on: + workflow_run: + workflows: ["test"] + types: + - completed +jobs: + release: + runs-on: ubuntu-latest + concurrency: release + permissions: + id-token: write # IMPORTANT: this permission is mandatory for trusted publishing using PyPI + + + if: ${{ github.ref == 'refs/heads/main' && github.event.workflow_run.conclusion == 'success'}} + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 0 + token: ${{ secrets.RELEASE }} + + - name: Python Semantic Release + id: release + uses: python-semantic-release/python-semantic-release@v8.0.4 + with: + github_token: ${{ secrets.RELEASE }} + changelog: "false" + + - name: Publish package distributions to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + if: steps.release.outputs.released == 'true' + # This action supports PyPI's trusted publishing implementation, which allows authentication to PyPI without a manually + # configured API token or username/password combination. To perform trusted publishing with this action, your project's + # publisher must already be configured on PyPI. + + - name: Publish package distributions to GitHub Releases + uses: python-semantic-release/upload-to-gh-release@main + if: steps.release.outputs.released == 'true' + with: + github_token: ${{ secrets.RELEASE }} diff --git a/testbed/embeddings-benchmark__mteb/.github/workflows/test.yml b/testbed/embeddings-benchmark__mteb/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..e56a85ce996bea1c3b2ccef2f3e6bb0b6a5f0ea5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.github/workflows/test.yml @@ -0,0 +1,56 @@ +# This workflow will: +# 1) install Python dependencies +# 2) run make test + + +name: Test +on: + push: + branches: [main] + pull_request: + +jobs: + test: + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest] #, macos-latest, windows-latest] + python-version: ["3.8", "3.9", "3.10"] + include: + # Add Windows with Python 3.8 only to avoid tests taking too long + - os: windows-latest + python-version: "3.8" + + steps: + - uses: actions/checkout@v3 + + - name: Setup Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + cache: "pip" + + - name: Install dependencies + shell: bash + run: | + make install-for-tests + + - name: Run tests + if: runner.os != 'Windows' + shell: bash + run: | + make test + + - name: Run tests on Windows + # Run tests on Windows + # this step will run the workflow twice since we have experienced + # failures when running on windows when loading the datasets + if: runner.os == 'Windows' + shell: bash + run: | + # run the test once and if it fails, run it again + # if it fails again, the workflow will fail. + # If it passes the first time the test will not run again + make test || make test + diff --git a/testbed/embeddings-benchmark__mteb/.vscode/extensions.json b/testbed/embeddings-benchmark__mteb/.vscode/extensions.json new file mode 100644 index 0000000000000000000000000000000000000000..424b18fcec7461c627d4d81e54136cc3334905d2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.vscode/extensions.json @@ -0,0 +1,5 @@ +{ + "recommendations": [ + "charliermarsh.ruff" + ] +} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/.vscode/settings.json b/testbed/embeddings-benchmark__mteb/.vscode/settings.json new file mode 100644 index 0000000000000000000000000000000000000000..b52f600915968a4f812d4fbb0145aeed6600c92c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/.vscode/settings.json @@ -0,0 +1,8 @@ +{ + "python.testing.pytestArgs": [ + "tests" + ], + "python.testing.unittestEnabled": false, + "python.testing.pytestEnabled": true, + "editor.defaultFormatter": "charliermarsh.ruff", +} diff --git a/testbed/embeddings-benchmark__mteb/docs/adding_a_dataset.md b/testbed/embeddings-benchmark__mteb/docs/adding_a_dataset.md new file mode 100644 index 0000000000000000000000000000000000000000..8ba11386808050c0dd310a1f8f50cac893d0af12 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/adding_a_dataset.md @@ -0,0 +1,266 @@ + +# Adding a Dataset + +To add a new dataset to MTEB, you need to do three things: + +1) Implement a task with the desired dataset, by subclassing an abstract task +2) Add metadata to the task +3) Submit the edits to the [MTEB](https://github.com/embeddings-benchmark/mteb) repository + +If you have any questions regarding this process feel free to open a discussion [thread](https://github.com/embeddings-benchmark/mteb/discussions). + +> Note: When we mention adding a dataset we refer to a subclass of one of the abstasks. + +## 1) Creating a new subclass + +### A Simple Example + +To add a new task, you need to implement a new class that inherits from the `AbsTask` associated with the task type (e.g. `AbsTaskReranking` for reranking tasks). You can find the supported task types in [here](https://github.com/embeddings-benchmark/mteb-draft/tree/main/mteb/abstasks). + +```python +from mteb import MTEB +from mteb.abstasks.AbsTaskReranking import AbsTaskReranking +from sentence_transformers import SentenceTransformer +from mteb.abstasks.TaskMetadata import TaskMetadata + +class SciDocsReranking(AbsTaskReranking): + metadata = TaskMetadata( + name="SciDocsRR", + description="Ranking of related scientific papers based on their title.", + reference="https://allenai.org/data/scidocs", + type="Reranking", + category="s2s", + eval_splits=["test"], + eval_langs=["eng-Latn"], + main_score="map", + dataset={ + "path": "mteb/scidocs-reranking", + "revision": "d3c5e1fc0b855ab6097bf1cda04dd73947d7caab", + } + date=("2000-01-01", "2020-12-31"), # best guess + form="written", + domains=["Academic", "Non-fiction"], + task_subtypes=["Scientific Reranking"], + license="cc-by-4.0", + socioeconomic_status="high", + annotations_creators="derived", + dialect=[], + text_creation="found", + n_samples={"test": 19599}, + avg_character_length={"test": 69.0}, + bibtex_citation=""" +@inproceedings{cohan-etal-2020-specter, + title = "{SPECTER}: Document-level Representation Learning using Citation-informed Transformers", + author = "Cohan, Arman and + Feldman, Sergey and + Beltagy, Iz and + Downey, Doug and + Weld, Daniel", + editor = "Jurafsky, Dan and + Chai, Joyce and + Schluter, Natalie and + Tetreault, Joel", + booktitle = "Proceedings of the 58th Annual Meeting of the Association for Computational Linguistics", + month = jul, + year = "2020", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2020.acl-main.207", + doi = "10.18653/v1/2020.acl-main.207", + pages = "2270--2282", + abstract = "Representation learning is a critical ingredient for natural language processing systems. Recent Transformer language models like BERT learn powerful textual representations, but these models are targeted towards token- and sentence-level training objectives and do not leverage information on inter-document relatedness, which limits their document-level representation power. For applications on scientific documents, such as classification and recommendation, accurate embeddings of documents are a necessity. We propose SPECTER, a new method to generate document-level embedding of scientific papers based on pretraining a Transformer language model on a powerful signal of document-level relatedness: the citation graph. Unlike existing pretrained language models, Specter can be easily applied to downstream applications without task-specific fine-tuning. Additionally, to encourage further research on document-level models, we introduce SciDocs, a new evaluation benchmark consisting of seven document-level tasks ranging from citation prediction, to document classification and recommendation. We show that Specter outperforms a variety of competitive baselines on the benchmark.", +} +""", +) + +# testing the task with a model: +model = SentenceTransformer("average_word_embeddings_komninos") +evaluation = MTEB(tasks=[MindSmallReranking()]) +evaluation.run(model) +``` + +> **Note:** for multilingual tasks, make sure your class also inherits from the `MultilingualTask` class like in [this](https://github.com/embeddings-benchmark/mteb-draft/blob/main/mteb/tasks/Classification/MTOPIntentClassification.py) example. +> For cross-lingual tasks, make sure your class also inherits from the `CrosslingualTask` class like in [this](https://github.com/embeddings-benchmark/mteb/blob/main/mteb/tasks/BitextMining/TatoebaBitextMining.py). + + + +### A Detailed Example +Often the dataset from HuggingFace is not in the format expected by MTEB. To resolve this you can either change the format on Hugging Face or add a `dataset_transform` method to your dataset to transform it into the right format on the fly. Here is an example along with some design considerations: + +```python +class VGClustering(AbsTaskClustering): + metadata = TaskMetadata( + name="VGClustering", + description="Articles and their classes (e.g. sports) from VG news articles extracted from Norsk Aviskorpus.", + reference="https://huggingface.co/datasets/navjordj/VG_summarization", + type="Clustering", + category="p2p", + eval_splits=["test"], + eval_langs=["nob-Latn"], + main_score="v_measure", + dataset={ + "path": "navjordj/VG_summarization", + "revision": "d4c5a8ba10ae71224752c727094ac4c46947fa29", + }, + date=("2012-01-01", "2020-01-01"), + form="written", + domains=["Academic", "Non-fiction"], + task_subtypes=["Scientific Reranking"], + license="cc-by-nc", + socioeconomic_status="high", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation= ... # removed for brevity +) + + def dataset_transform(self): + splits = self.description["eval_splits"] + + documents: list = [] + labels: list = [] + label_col = "classes" + + ds = {} + for split in splits: + ds_split = self.dataset[split] + + _label = self.normalize_labels(ds_split[label_col]) + documents.extend(ds_split["title"]) + labels.extend(_label) + + documents.extend(ds_split["ingress"]) + labels.extend(_label) + + documents.extend(ds_split["article"]) + labels.extend(_label) + + assert len(documents) == len(labels) + + rng = random.Random(1111) # local only seed + pairs = list(zip(documents, labels)) + rng.shuffle(pairs) + documents, labels = [list(collection) for collection in zip(*pairs)] + + # To get a more robust estimate we create batches of size 512, this decision can vary depending on dataset + documents_batched = list(batched(documents, 512)) + labels_batched = list(batched(labels, 512)) + + # reduce the size of the dataset as we see that we obtain a consistent scores (if we change the seed) even + # with only 512x4 samples. + documents_batched = documents_batched[:4] + labels_batched = labels_batched[:4] + + + ds[split] = datasets.Dataset.from_dict( + { + "sentences": documents_batched, + "labels": labels_batched, + } + ) + + self.dataset = datasets.DatasetDict(ds) +``` + + + + +## 2) Creating the metadata object +Along with the task MTEB requires metadata regarding the task. If the metadata isn't available please provide your best guess or leave the field as `None`. + +To get an overview of the fields in the metadata object, you can look at the [TaskMetadata](https://github.com/embeddings-benchmark/mteb/blob/main/mteb/abstasks/TaskMetadata.py) class. + + +Note that these fields can be left blank if the information is not available and can be extended if necessary. We do not include any machine-translated (without verification) datasets in the benchmark. + +
+Domains +
+ +The domains follow the categories used in the [Universal Dependencies project](https://universaldependencies.org), though we updated them where deemed appropriate. These do not have to be mutually exclusive. + +| **Domain** | **Description** | +| ------------- | ---------------------------------------------------------------- | +| Academic | Academic writing | +| Religious | Religious text e.g. bibles | +| Blog | [Blogpost, weblog etc.](https://en.wikipedia.org/wiki/Blog) | +| Fiction | Works of [fiction](https://en.wikipedia.org/wiki/Fiction) | +| Government | Governmental communication, websites or similar | +| Legal | Legal documents, laws etc. | +| Medical | doctors notes, medical procedures or similar | +| News | News articles, tabloids etc. | +| Reviews | Reviews e.g. user reviews of products | +| Non-fiction | [non-fiction](https://en.wikipedia.org/wiki/Non-fiction) writing | +| Poetry | Poems, Epics etc. | +| Social | social media content | +| Spoken | Spoken dialogues | +| Encyclopaedic | E.g. Wikipedias | +| Web | Web content | + + +
+ + +
+
+Task Subtypes +
+ +These domains subtypes were introduced in the [Scandinavian Embedding Benchmark](https://openreview.net/pdf/f5f1953a9c798ec61bb050e62bc7a94037fd4fab.pdf) and are intended to be extended as needed. + + + +| Formalization | Task | Description | +| ----------------------- | ------------------------ | --------------------------------------------------------------------------------------------------------------- | +| **Retrieval** | | Retrieval focuses on locating and providing relevant information or documents based on a query. | +| | Question answering | Finding answers to queries in a dataset, focusing on exact answers or relevant passages. | +| | Article retrieval | Identifying and retrieving full articles that are relevant to a given query. | +| **Bitext Mining** | | Bitext mining involves identifying parallel texts across languages or dialects for translation or analysis. | +| | Dialect pairing | Identifying pairs of text that are translations of each other across different dialects. | +| **Classification** | | Classification is the process of categorizing text into predefined groups or classes based on their content. | +| | Political | Categorizing text according to political orientation or content. | +| | Language Identification | Determining the language in which a given piece of text is written. | +| | Linguistic Acceptability | Assessing whether a sentence is grammatically correct according to linguistic norms. | +| | Sentiment/Hate Speech | Detecting the sentiment of text or identifying hate speech within the content. | +| | Dialog Systems | Creating or evaluating systems capable of conversing with humans in a natural manner. | +| **Clustering** | | Clustering involves grouping sets of texts together based on their similarity without pre-defined labels. | +| | Thematic Clustering | Grouping texts based on their thematic similarity without prior labeling. | +| **Reranking** | | Reranking adjusts the order of items in a list to improve relevance or accuracy according to specific criteria. | +| **Pair Classification** | | Pair classification assesses relationships between pairs of items, such as texts, to classify their connection. | +| **STS** | | Semantic Textual Similarity measures the degree of semantic equivalence between two pieces of text. | + + +
+ + + +## Submit a PR + +Once you are finished create a PR to the [MTEB](https://github.com/embeddings-benchmark/mteb) repository. If you haven't created a PR before please refer to the [GitHub documentation](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/) + +The PR will be reviewed by one of the organizers or contributors who might ask you to change things. Once the PR is approved the dataset will be added into the main repository. + + +Before you commit here is a checklist you should consider completing before submitting: + +- [ ] I have tested that the dataset runs with the `mteb` package. + +An easy way to test it is using: +```python +from mteb import MTEB +from sentence_transformers import SentenceTransformer + +# Define the sentence-transformers model name +model_name = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2" + +model = SentenceTransformer(model_name) +evaluation = MTEB(tasks=[YourNewTask()]) +``` + +- [ ] I have run the following models on the task (adding the results to the pr). These can be run using the `mteb -m {model_name} -t {task_name}` command. + - [ ] `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` + - [ ] `intfloat/multilingual-e5-small` +- [ ] I have checked that the performance is neither trivial (both models gain close to perfect scores) nor random (both models gain close to random scores). +- [ ] I have considered the size of the dataset and reduced it if it is too big (2048 examples is typically large enough for most tasks) +- [ ] Run tests locally to make sure nothing is broken using `make test`. +- [ ] Run the formatter to format the code using `make lint`. diff --git a/testbed/embeddings-benchmark__mteb/docs/adding_a_leaderboard_tab.md b/testbed/embeddings-benchmark__mteb/docs/adding_a_leaderboard_tab.md new file mode 100644 index 0000000000000000000000000000000000000000..260293ed5cc9ab5df8071831cabffc8f0364987d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/adding_a_leaderboard_tab.md @@ -0,0 +1,15 @@ +## Adding a new Leaderboard tab + +The MTEB Leaderboard is available [here](https://huggingface.co/spaces/mteb/leaderboard) and we love new leaderboard tabs. To add a new leaderboard tab: + +1. Open a PR in https://hf.co/datasets/mteb/results with: +- All results added in existing model folders or new folders +- Updated paths.json (see snippet results.py) +- If adding any new models, their names added to results.py +- If you have access to all models you are adding, you can also [add results via the metadata](https://github.com/embeddings-benchmark/mteb/blob/main/docs/adding_a_model.md) for all of them / some of them +2. Open a PR at https://huggingface.co/spaces/mteb/leaderboard modifying app.py to add your tab: +- Add any new models & their specs to the global lists +- Add your tab, credits etc to where the other tabs are defined +- If you're adding new results to existing models, remove those models from `EXTERNAL_MODEL_RESULTS.json` such that they can be reloaded with the new results and are not cached. +- You may also have to uncomment `, download_mode='force_redownload', verification_mode="no_checks")` where the datasets are loaded to experiment locally without caching of results +- Test that it runs & works locally as you desire with python app.py, **please add screenshots to the PR** diff --git a/testbed/embeddings-benchmark__mteb/docs/adding_a_model.md b/testbed/embeddings-benchmark__mteb/docs/adding_a_model.md new file mode 100644 index 0000000000000000000000000000000000000000..0cbbd2af45d4c03c8f129f5554f71a2637e36825 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/adding_a_model.md @@ -0,0 +1,11 @@ +## Adding a Model to the MTEB Leaderboard + +The MTEB Leaderboard is available [here](https://huggingface.co/spaces/mteb/leaderboard). To submit: + +1. Run on MTEB: You can reference [scripts/run_mteb_english.py](https://github.com/embeddings-benchmark/mteb/blob/main/scripts/run_mteb_english.py) for all MTEB English datasets used in the main ranking, or [scripts/run_mteb_chinese.py](https://github.com/embeddings-benchmark/mteb/blob/main/scripts/run_mteb_chinese.py) for the Chinese ones. +Advanced scripts with different models are available in the [mteb/mtebscripts repo](https://github.com/embeddings-benchmark/mtebscripts). +2. Format the json files into metadata using the script at `scripts/mteb_meta.py`. For example +`python scripts/mteb_meta.py path_to_results_folder`, which will create a `mteb_metadata.md` file. If you ran CQADupstack retrieval, make sure to merge the results first with `python scripts/merge_cqadupstack.py path_to_results_folder`. +3. Copy the content of the `mteb_metadata.md` file to the top of a `README.md` file of your model on the Hub. See [here](https://huggingface.co/Muennighoff/SGPT-5.8B-weightedmean-msmarco-specb-bitfit/blob/main/README.md) for an example. +4. Hit the Refresh button at the bottom of the leaderboard and you should see your scores 🥇 +5. To have the scores appear without refreshing, you can open an issue on the [Community Tab of the LB](https://huggingface.co/spaces/mteb/leaderboard/discussions) and someone will restart the space to cache your average scores. The cache is updated anyways ~1x/week. \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/create_tasks_table.py b/testbed/embeddings-benchmark__mteb/docs/create_tasks_table.py new file mode 100644 index 0000000000000000000000000000000000000000..b1f59754894317046aeca82e80904aa285ee4f71 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/create_tasks_table.py @@ -0,0 +1,136 @@ +from __future__ import annotations + +import re +from pathlib import Path +from typing import get_args + +import polars as pl + +import mteb +from mteb.abstasks.TaskMetadata import PROGRAMMING_LANGS, TASK_TYPE + + +def author_from_bibtex(bibtex: str | None) -> str: + """Create (Authors, Year) from bibtex entry (author = {Authors}, year = {Year})""" + if bibtex is None: + return "" + # get authors from bibtex (author = {Authors} or author={Authors}) + authors = re.search(r"author\s*=\s*{([^}]*)}", bibtex) + if authors is None: + return "" + authors = authors.group(1) + authors = [a.split(", ") for a in authors.split(" and ")] + author_str_w_et_al = ( + authors[0][0] + " et al." if len(authors[0]) > 1 else authors[0][0] + ) + # replace any newline characters + author_str_w_et_al = author_str_w_et_al.replace("\n", " ") + year = re.search(r"year\s*=\s*{([^}]*)}", bibtex) + if year is None: + return "" + year_str = year.group(1) + return f" ({author_str_w_et_al}, {year_str})" + + +def task_to_markdown_row(task: mteb.AbsTask) -> str: + name = task.metadata.name + name_w_reference = ( + f"[{name}]({task.metadata.reference})" if task.metadata.reference else name + ) + domains = ( + "[" + ", ".join(task.metadata.domains) + "]" if task.metadata.domains else "" + ) + n_samples = task.metadata.n_samples if task.metadata.n_samples else "" + avg_character_length = ( + task.metadata.avg_character_length if task.metadata.avg_character_length else "" + ) + + name_w_reference += author_from_bibtex(task.metadata.bibtex_citation) + + return f"| {name_w_reference} | {task.metadata.languages} | {task.metadata.type} | {task.metadata.category} | {domains} | {n_samples} | {avg_character_length} |" + + +def create_tasks_table(tasks: list[mteb.AbsTask]) -> str: + table = """ +| Name | Languages | Type | Category | Domains | # Samples | Avg. Length (Char.) | +|------|-----------|------|----------|---------|-----------|---------------------| +""" + for task in tasks: + table += task_to_markdown_row(task) + "\n" + return table + + +def create_task_lang_table(tasks: list[mteb.AbsTask]) -> str: + table_dict = {} + ## Group by language. If it is a multilingual dataset, 1 is added to all languages present. + for task in tasks: + for lang in task.metadata.languages: + if lang in PROGRAMMING_LANGS: + lang = "code" + if table_dict.get(lang) is None: + table_dict[lang] = {k: 0 for k in sorted(get_args(TASK_TYPE))} + table_dict[lang][task.metadata.type] += 1 + + ## Wrangle for polars + pl_table_dict = [] + for lang, d in table_dict.items(): + d.update({"lang": lang}) + pl_table_dict.append(d) + + df = pl.DataFrame(pl_table_dict).sort(by="lang") + total = df.sum(axis=0) + + task_names_md = " | ".join(sorted(get_args(TASK_TYPE))) + horizontal_line_md = "---|---" * len(sorted(get_args(TASK_TYPE))) + table = """ +| Language | {} | +|{}| +""".format(task_names_md, horizontal_line_md) + + for row in df.iter_rows(): + table += f"| {row[-1]} " + for num in row[:-1]: + table += f"| {num} " + table += "|\n" + + for row in total.iter_rows(): + table += "| Total " + for num in row[:-1]: + table += f"| {num} " + table += "|\n" + + return table + + +def insert_tables( + file_path: str, tables: list[str], tags: list[str] = ["TASKS TABLE"] +) -> None: + """Insert tables within and or similar tags.""" + md = Path(file_path).read_text() + + for table, tag in zip(tables, tags): + start = f"" + end = f"" + md = md.replace(md[md.index(start) + len(start) : md.index(end)], table) + + Path(file_path).write_text(md) + + +def main(): + tasks = mteb.get_tasks() + tasks = sorted(tasks, key=lambda x: x.metadata.name) + + tasks_table = create_tasks_table(tasks) + task_lang_table = create_task_lang_table(tasks) + + file_path = Path(__file__).parent / "tasks.md" + + insert_tables( + file_path, + tables=[tasks_table, task_lang_table], + tags=["TASKS TABLE", "TASK LANG TABLE"], + ) + + +if __name__ == "__main__": + main() diff --git a/testbed/embeddings-benchmark__mteb/docs/images/mteb_logo/mteb_logo_tight_hfhub.drawio b/testbed/embeddings-benchmark__mteb/docs/images/mteb_logo/mteb_logo_tight_hfhub.drawio new file mode 100644 index 0000000000000000000000000000000000000000..a632ac9b564683e0ffc1790d1f99f27b04804b8a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/images/mteb_logo/mteb_logo_tight_hfhub.drawio @@ -0,0 +1 @@ +xVXBbuIwEP2aHFmRmARyJDRt99AT1a72aOIhserYqWMg9Ot3jB0gBSQqdbUX8DzP2OP3np2ALOruSdOmelEMRBCNWReQhyCKkmmCvxbYOyCM07FDSs2Zx07Akn+AB/u0DWfQDhKNUsLwZggWSkoozACjWqvdMG2txHDXhpZwASwLKi7R35yZyqGzaHrCn4GXVb9zmKRupqZ9sj9JW1GmdmcQyQOy0EoZN6q7BQhLXs+Lq3u8MXtsTIM09xRUKXtiYTGKpdz+XP7JY1qno4lbZUvFxh/YN2v2PQO7ihtYNrSw8Q5VDkhWmVpgFOKQto3jfc07wK2y1mj1BgsllEZUKol1md8GtIHuZv/hkRW0E6gajN5jii8g8ezHNHZV3k0j4rndnaQJe6w6l6UHqbdDeVz+xBgOPGlfIDC8IPDlNc8uSMRjG0uW4KVEpMAzA9KTWUY4um3uJ2rOmK3JNLT8g64O9WOMG8WlOTQfZ0H8YNfaGNW6+2J1WCtp/PUhkY8fac2F5eoXaEYl7dN8X+FQSUFXIDKlGehP6tmiHgoiMo5IPpt/k6oJOap6rmJ0RcX4X4kYXYpI25ZvAcFXq5ztJhFWwZUeCJu8b+z9PTA0cmrMMSFtugM9/TSOSvuf1ytgjMsSczKQRVVT/fYfzHL1jq65EFeE96ZK7/fULbvc5bVveSnI55dicuWhmFyx2OTrFsPw9Igf5s4+hST/Cw== \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/images/mteb_logo/mteb_logo_wide_github.drawio b/testbed/embeddings-benchmark__mteb/docs/images/mteb_logo/mteb_logo_wide_github.drawio new file mode 100644 index 0000000000000000000000000000000000000000..3a0e79cbc361c564f60cb746bc804981e8f59584 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/images/mteb_logo/mteb_logo_wide_github.drawio @@ -0,0 +1 @@ +xVVNc5swEP01HN0xCGxzNA5xe8jJmXZ6lNEaNNEHFbLB+fWVQAQIzozbaaYXW/t2V1q9t1o8tOPNXuGyeJIEmBcsSeOhBy8Iwk1kfi1w7QA/XPsdkitKHDYAB/oKDlw69EwJVJNALSXTtJyCmRQCMj3BsFKynoadJJueWuIcZsAhw2yO/qBEFx26CdYD/hVoXvQn+6u483DcB7ubVAUmsh5BKPXQTkmpuxVvdsAseT0vXd7jB963whQIfU9CEZM98bNFJMTl2+FnGmEeL8JulwtmZ3dhV6y+9gzUBdVwKHFm7dqo7KGk0JwZyzdLXJUd7yfagDkqqbSSL7CTTCqDCilMXjIv1tV/AaWhGUGu+D1IDlpdTYjzogh9Wbt2ct20QI7bepDGDx1WjGXpQezaIX/bfmDMLBxpf0CgPyPw6TlNZiSaO2pLFqO5MEhmaABDT2KvT023bZ2DU0JsTqKgoq/42OYvjV1KKnRbfJR40YPd66xl1b0Xq8NJCu2eDwqc/Yg5ZZar76AIFrgPc3X5UyUZPgJLpCKg3qlnk3rIC9AyQOlm+49UXQ2qjlUMbqgYfZaIwVxEXFX0AgZ8tsrZalbMKnhUE2FXv872/bYMLTo1tiYgLpuWnt5tVrn9T/kRCKEiNzEJiKzgWL38h2a5+UZPlLEbwrumiu/vqY/a5a5e+5xJEd45KP5iThhzGOKtb/QpROlv \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/create_points_table.py b/testbed/embeddings-benchmark__mteb/docs/mmteb/create_points_table.py new file mode 100644 index 0000000000000000000000000000000000000000..c30dd1600d8c190ea6790fb42a280dd9f077cb7e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/create_points_table.py @@ -0,0 +1,40 @@ +import json +from pathlib import Path + +import pandas as pd + + +def load_data(file_path: Path) -> pd.DataFrame: + file_path = Path(__file__).parent / "points" + files = file_path.glob("*.jsonl") + + json_data = [] + for file in files: + with open(file) as f: + for line in f: + json_data.append(json.loads(line)) + + df = pd.DataFrame(json_data) + return df + + +def save_to_markdown(df: pd.DataFrame, file_path: Path) -> None: + df = df.groupby("GitHub").sum().astype(int) + # create a new column with the sum of the points + df["Total"] = df.sum(axis=1) + # sort the dataframe by the total points + df = df.sort_values("Total", ascending=False) + + md = df.to_markdown() + # add title + md = f"# Points\n\n_Note_: this table is **autogenerated** and should not be edited. It is intended to get an overview of contributions.\n\n {md}" + with open(file_path, "w") as f: + f.write(md) + + +if __name__ == "__main__": + file_path = Path(__file__).parent / "points" + save_path = Path(__file__).parent / "points_table.md" + + df = load_data(file_path) + save_to_markdown(df, save_path) diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points.md b/testbed/embeddings-benchmark__mteb/docs/mmteb/points.md new file mode 100644 index 0000000000000000000000000000000000000000..7f4af0226a98c9e814ed4e9b635fa37f27a8c29f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points.md @@ -0,0 +1,91 @@ +# Points + + +**Note**: The points have been moved to [`points`](https://github.com/embeddings-benchmark/mteb/tree/main/docs/mmteb/points) folder to avoid merge conflicts. To add points you will now have to add a jsonl file to the folder. An example could looks like so: + +``` +{"GitHub": "GitHubUser1", "New dataset": 6} +{"GitHub": "GitHubUser2", "Review PR": 2} +``` + +The file should be named after the PR number. E.g. `438.jsonl`, where 438 is the PR number. + +The possible keys to include is: + +```{python} +{ + "GitHub": "GitHubUser1", + "New dataset": 2-6, # 2 points for the dataset and 4 points for the task + "New task": 2, # e.g. a new style of task (e.g. classification, or retrieval) + "Dataset annotations": 1, # 1 point for each full dataset annotation + "Bug fixes": 2-10, # depends on the complexity of the fix + "Running Models": 1, # pr model run + "Review PR": 2, # two points pr. reviewer, can be given to multiple reviewers + "Paper Writing": NA, + "Ideation": NA, + "Coordination": NA +} +``` + +**Note**: The points have been moved to points folder to avoid merge conflicts. + +Note that coordination and ideation is not included in the points yet, but is used to determine first and last authors. + +# Contributor Informations + +Please also add your first name and last name are as you want them to appear in a publication. If you do not with to have your name in a publication, please add a note to that effect. + +| GitHub | First name | Last name | Email | User on openreview | Affiliations | +| ----------------- | ---------- | ---------- | ---------------------------- | -------------------- | ----------------------------------------------------- | +| KennethEnevoldsen | Kenneth | Enevoldsen | kennethcenevoldsen@gmail.com | ~Kenneth_Enevoldsen1 | Aarhus University, Denmark | +| x-tabdeveloping | Márton | Kardos | martonkardos@cas.au.dk | ~Márton_Kardos1 | Aarhus University, Denmark | +| imenelydiaker | Imene | Kerboua | | | Esker, Lyon, France && INSA Lyon, LIRIS, Lyon, France | +| wissam-sib | Wissam | Siblini | wissamsiblini92@gmail.com | | N/A | +| GabrielSequeira | Gabriel | Sequeira | | | N/A | +| schmarion | Marion | Schaeffer | | ~Marion_Schaeffer1 | Wikit, Lyon, France | +| MathieuCiancone | Mathieu | Ciancone | | | Wikit, Lyon, France | +| MartinBernstorff | Martin | Bernstorff | martinbernstorff@gmail.com | ~Martin_Bernstorff1 | Aarhus University, Denmark | +| staoxiao | Shitao | Xiao | 2906698981@qq.com | ~Shitao_Xiao1 | Beijing Academy of Artificial Intelligence | +| ZhengLiu101 | Zheng | Liu | zhengliu1026@gmail.com | ~Zheng_Liu4 | Beijing Academy of Artificial Intelligence | +| achibb | Aaron | Chibb | | | N/A | +| cassanof | Federico | Cassano | federico.cassanno@federico.codes | ~Federico_Cassano1 | Northeastern University, Boston, USA | +| taidnguyen | Nguyen | Tai | taing@seas.upenn.edu | ~Nguyen_Tai1 | University of Pennsylvania | +| xu3kev | Wen-Ding | Li | wl678@cornell.edu | ~Wen-Ding_Li1 | Cornell University | +| Rysias | Jonathan | Rystrøm | jonathan.rystroem@gmail.com | | University of Oxford, UK | +| taeminlee | Taemin | Lee | taeminlee@korea.ac.kr | ~Taemin_Lee1 | Korea University Human-Inspired AI Research | +| izhx | Xin | Zhang | zhangxin2023@stu.hit.edu.cn | | Harbin Institute of Technology, Shenzhen | +| orionw | Orion | Weller | oweller@cs.jhu.edu | ~Orion_Weller1 | Johns Hopkins University | +| slvnwhrl | Silvan | Wehrli | wehrlis@rki.de | ~Silvan_Wehrli1 | Robert Koch Institute, Berlin, Germany | +| manandey | Manan | Dey | manandey1@gmail.com | ~Manan_Dey2 | Salesforce, India | +| isaac-chung | Isaac | Chung | chungisaac1217@gmail.com | ~Isaac_Kwan_Yin_Chung1 | N/A | +| asparius | Ömer | Çağatan | ocagatan19@ku.edu.tr | ~Ömer_Veysel_Çağatan1 | Koç University,Turkey | +| rafalposwiata | Rafał | Poświata | rposwiata@opi.org.pl | ~Rafał_Poświata1 | National Information Processing Institute, Warsaw, Poland | +| rbroc | Roberta | Rocca | roberta.rocca@cas.au.dk | ~Roberta_Rocca1 | Aarhus University, Denmark | +| awinml | Ashwin | Mathur | ashwinxmathur@gmail.com | | N/A | +| guangyusong | Guangyu | Song | guangysong@gmail.com | ~Guangyu_Song1 | N/A | +| davidstap. | David | Stap | dd.stap@gmail.com | ~David_Stap | University of Amsterdam. | +| HLasse | Lasse | Hansen | lasseh0310@gmail.com | ~Lasse_Hansen2 | Aarhus University, Denmark | +| jaygala24 | Jay | Gala | jaygala24@gmail.com | ~Jay_Gala1 | Nilekani Center at AI4Bharat | +| digantamisra | Diganta | Misra | diganta.misra@mila.quebec | ~Diganta_Misra1 | Mila - Quebec AI Institute | +| PranjalChitale | Pranjal | Chitale | cs21s022@smail.iitm.ac.in | ~Pranjal_A_Chitale1 | Indian Institute of Technology Madras | +| Akash190104 | Akash | Kundu | akashkundu2xx4@gmail.com |~Akash_Kundu2 | Heritage Institute of Technology, Kolkata && Apart Research | +| dwzhu-pku | Dawei | Zhu | dwzhu@pku.edu.cn | ~Dawei_Zhu2 | Peking University | +| ljvmiranda921 | Lester James | Miranda | ljm@allenai.org | ~Lester_James_Validad_Miranda1 | Allen Institute for AI | +| Sakshamrzt | Saksham | Thakur | sthakur5@alumni.ncsu.edu | ~Saksham_Thakur1 | N/A | +| Andrian0s | Andrianos | Michail | andrianos.michail@cl.uzh.ch | ~Andrianos_Michail1 | University of Zurich| +| simon-clematide | Simon | Clematide | simon.clematide@cl.uzh.ch | ~Simon_Clematide1 | University of Zurich| +| SaitejaUtpala | Saiteja | Utpala | saitejautpala@gmail.com | ~Saiteja_Utpala1 | Microsoft Research| +| mmhamdy | Mohammed | Hamdy | mhamdy.res@gmail.com | ~Mohammed_Hamdy1 | Cohere For AI Community| +| jupyterjazz | Saba | Sturua | saba.sturua@jina.ai | ~Saba_Sturua1 | Jina AI | +| Ruqyai | Ruqiya | Bin Safi | ruqiya.binsafi@libfstudy.ac.uk | ~Ruqiya_Bin_Safi1 | LIBF : The London Institute of Banking & Finance | +| kranthigv | Kranthi Kiran | GV | kranthi.gv@nyu.edu | ~Kranthi_Kiran_GV1 | New York University| +| shreeya-dhakal | Shreeya | Dhakal | ssdhakal57@gmail.com | | Individual Contributor | +| dipam7 | Dipam | Vasani | dipam44@gmail.com | ~Dipam_Vasani1 | Individual Contributor | +| Art3mis07 | Gayatri | K | gayatrikrishnakumar0707@gmail.com | ~Gayatri_K1 | R. V. College of Engineering, Bengaluru | +| jankounchained | Jan | Kostkan | jan.kostkan@cas.au.dk | ~Jan_Kostkan1 | Aarhus University, Denmark | +| bp-high | Bhavish | Pahwa | t-bpahwa@microsoft.com | ~Bhavish_Pahwa1 | Microsoft Research | +| rasdani | Daniel | Auras | daniel@ellamind.com | ~Daniel_Auras1 | ellamind, Germany | +| ShawonAshraf | Shawon | Ashraf | shawon@ellamind.com | ~Shawon_Ashraf1 | ellamind, Germany | +| bjoernpl | Björn | Plüster | bjoern@ellamind.com | ~Björn_Plüster1 | ellamind, Germany | +| jphme | Jan Philipp| Harries | jan@ellamind.com |~Jan_Philipp_Harries1 | ellamind, Germany | +| malteos | Malte | Ostendorff | malte@occiglot.eu | ~Malte_Ostendorff1| Occiglot | \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/348.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/348.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1e161a6d468c777e7c3e3200d21ab9ab7319dba9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/348.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "marcobellagente93", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/376.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/376.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..54a800059b932e55bee901ecf5974f0ad21bbdf6 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/376.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Rysias", "New dataset": 18} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/393.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/393.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e5e51ba8f32c07f5ff3a87f78581e920d04ebaf2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/393.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dwzhu-pku", "New dataset": 12} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/408.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/408.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..89156ac0882f40f86f86d01a49d63ced7ab0563d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/408.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "KennethEnevoldsen", "Review PR": 4} +{"GitHub": "Muennighoff", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "orionw", "New task": 10} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/409.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/409.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9a5d5f2c290e4cc089271a54e12b9a27188b96fb --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/409.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "davidstap", "New dataset": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/429.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/429.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0226cfc433eea58e090de9d37bdfdc96f680f12e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/429.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "isaac-chung", "New dataset": 6} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/430.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/430.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..73dd5fd9d704340b06538212f59e1d5dd59ce50f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/430.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/431.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/431.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..49a3701e2799ac96be1eea5162fa818e29254e7d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/431.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "asparius", "New dataset": 6} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/432.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/432.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..49a3701e2799ac96be1eea5162fa818e29254e7d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/432.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "asparius", "New dataset": 6} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/433.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/433.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..434be4b17003705f817276c4e9e3d717c8412fc9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/433.jsonl @@ -0,0 +1 @@ +{"GitHub": "manandey", "New dataset": 6} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/436.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/436.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9f2409ee5e1a3a6d577a0fa12c7ba66c9d380ae2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/436.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "guangyusong", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/438.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/438.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..54d3595ceadf014a7481b1bcafbba033a0fbc40f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/438.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "KennethEnevoldsen", "Coordination": 2} +{"GitHub": "x-tabdeveloping", "Coordination": 1} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/439.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/439.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..37f513b0bcb30f0b3f98b9cf3e031d91fbd5c805 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/439.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "rbroc", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/440.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/440.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..597203fc110792a923967f9c80988a9d0e28aaeb --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/440.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "x-tabdeveloping", "New dataset": 94} +{"GitHub": "x-tabdeveloping", "New task": 10} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/448.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/448.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd36b28cccf023aef5fc61eceb212ab55f0c2827 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/448.jsonl @@ -0,0 +1 @@ +{"GitHub": "isaac-chung", "Coordination": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/451.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/451.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8abd68c201fef868096a86808586acf435637640 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/451.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jaygala24", "New dataset": 11} +{"GitHub": "digantamisra98", "New dataset": 11} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/456.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/456.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9f2409ee5e1a3a6d577a0fa12c7ba66c9d380ae2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/456.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "guangyusong", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/457.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/457.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..47007bf9d910e469c81666f35b5d227ada686a7a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/457.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "orionw", "Bug fixes": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} +{"GitHub": "tomaarsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/460.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/460.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0c58b8a8a530d1e0287b31a2aaa4957be5f2ba52 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/460.jsonl @@ -0,0 +1,5 @@ +{"GitHub": "ManuelFay", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/461.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/461.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..78d70a81f00b71a736a555861506c8fe2918a3b9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/461.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "KennethEnevoldsen", "Bug fixes": 3} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/463.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/463.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..73dd5fd9d704340b06538212f59e1d5dd59ce50f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/463.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/466.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/466.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..73dd5fd9d704340b06538212f59e1d5dd59ce50f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/466.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/467.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/467.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d69c949b280b66379eb1d0f029d3357e039eae89 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/467.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Coordination": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/468.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/468.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d69c949b280b66379eb1d0f029d3357e039eae89 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/468.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Coordination": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/470.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/470.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..321c510e8de3fa88fe14a477e5f3fcba309f95d8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/470.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "imenelydiaker", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/471.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/471.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b95f46bcad8a1dceb451acdbb790d8ccb1413fa4 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/471.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/472.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/472.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c5b36ee78f4fb15bfc249ea722b8ec695bb40c44 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/472.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "guangyusong", "New dataset": 6} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/473.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/473.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45324201f93e78ee0b6f26a7ef4d5a608c565320 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/473.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/474.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/474.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bf7eef4e5237b52b1adacb2de254618bdb8c0f32 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/474.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/476.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/476.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f8b85373b66ebdf117357194cf809c35ca61935c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/476.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "jaygala24", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/478.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/478.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff6bd2067c48d6d1fd8fb529cdd55d332803b977 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/478.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/479.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/479.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c2d0ac5fc1ffdecef6358f804d14ca587ec4ac8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/479.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/480.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/480.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..470306f304adf44f34f5c2314efc4c0d749b5401 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/480.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/481.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/481.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..294f6a9f3f3a0ed91ab3a34af110219741399bce --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/481.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "KennethEnevoldsen", "New dataset": 6, "Bug fixes": 6} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/484.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/484.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe80ffb5eb47f18fe12675e38d2d20086def4db --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/484.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/485.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/485.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe80ffb5eb47f18fe12675e38d2d20086def4db --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/485.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/486.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/486.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6a324a296ef9665d8d8e6973ffa4bfec3f8accdd --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/486.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Rysias", "New dataset": 40} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/487.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/487.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e5d6caa8e899b3bf7d4934cbf7879d368ac21ed9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/487.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "rbroc", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/489.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/489.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5f5333e92e270c76d104925ee290ee1fc5e44529 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/489.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jaygala24", "New dataset": 14} +{"GitHub": "digantamisra98", "New dataset": 8} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/491.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/491.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fb2107aca5f85f9809fc31256931794dee198841 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/491.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Akash190104", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/492.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/492.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eddb00521ec895e90e22c56cea197dcc3ec4ef48 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/492.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Akash190104", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/493.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/493.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..74e5bf5ef2fc22e19b7f0886b5fe1d51a5bb3530 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/493.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 6} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/497.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/497.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9c2d0ac5fc1ffdecef6358f804d14ca587ec4ac8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/497.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/499.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/499.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff6bd2067c48d6d1fd8fb529cdd55d332803b977 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/499.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/500.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/500.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe80ffb5eb47f18fe12675e38d2d20086def4db --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/500.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/501.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/501.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f72a055c630942a1614b6fff4b91eca2fa847012 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/501.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/502.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/502.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2f07244f5de8fe641f242cd97b7ecdb9cae5c337 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/502.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "bp-high", "New dataset": 6} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/503.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/503.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe80ffb5eb47f18fe12675e38d2d20086def4db --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/503.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/504.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/504.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe80ffb5eb47f18fe12675e38d2d20086def4db --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/504.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/506.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/506.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3e944cadda9737da38bea6235ed4b9195ecce5d8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/506.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "bp-high", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/509.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/509.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..68268f63eae3245df0c0f8008848fd1cd7323425 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/509.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/512.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/512.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..055d6ae9cfa460177f713bf92c9d4bd65e92a48e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/512.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 2} +{"GitHub": "asparius", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/513.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/513.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cc158d1dcd98b4e5ae9e0b3edf947bf0ef4003aa --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/513.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "isaac-chung", "Coordination": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/514.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/514.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..50f3bcb9a2473cd4e9bb066343d83fedacd9183b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/514.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jaygala24", "New dataset": 24} +{"GitHub": "digantamisra98", "New dataset": 14} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/515.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/515.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d556a7813bb9e265afb275bc32de480ebe12fe49 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/515.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 14} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/518.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/518.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45324201f93e78ee0b6f26a7ef4d5a608c565320 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/518.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/521.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/521.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..afd0a71222f9a5df4379bf7042f5dc5d794c76be --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/521.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "imenelydiaker", "Bug fixes": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/522.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/522.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cc4780801eb5fec266b26e4e6e35b632b21282cf --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/522.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Bug fixes": 3} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/524.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/524.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ce0b774441dcf1cb5c1dfdf3665ea9cf077f0c4c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/524.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jaygala24", "New dataset": 30} +{"GitHub": "digantamisra98", "New dataset": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/525.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/525.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cc4780801eb5fec266b26e4e6e35b632b21282cf --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/525.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Bug fixes": 3} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/527.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/527.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b83de93cbd69e3377c1604bb65ecb36684bc9ede --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/527.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "imenelydiaker", "Bug fixes": 3} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/528.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/528.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..202885f08a01af944bc360b9185f9ce8d87e35d8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/528.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Bug fixes": 1, "New dataset": 8, "Dataset annotations": 1} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/532.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/532.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a01d28100fcbb38164d42994b8f43c4b6ad0b8cc --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/532.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jaygala24", "New dataset": 36} +{"GitHub": "digantamisra98", "New dataset": 18} +{"GitHub": "asparius", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/533.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/533.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cdad1560eb11a451f3586e853cbd5e210b58da0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/533.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "asparius", "New dataset": 6} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/534.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/534.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..806771874a94c39a7c3dd76cd6ec172e0ee65b95 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/534.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "asparius", "New dataset": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/535.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/535.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e702c852a59ff3c94cab2c56d1693424f7ecd0bc --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/535.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "bp-high", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "asparius", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/536.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/536.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a7c2725055b7831285bce38da0879d6f34d93ecd --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/536.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "Akash190104", "New dataset": 2} +{"GitHub": "asparius", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/537.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/537.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9cdad1560eb11a451f3586e853cbd5e210b58da0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/537.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "asparius", "New dataset": 6} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/538.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/538.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..78cca33956f9a521b0700b5f61bdee07818a7b11 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/538.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Akash190104", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/539.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/539.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..68268f63eae3245df0c0f8008848fd1cd7323425 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/539.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/543.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/543.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5f17b7842d9cb341f93cb6652f5c6d567b7cd4e4 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/543.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "davidstap", "New dataset": 68} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/545.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/545.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..644b789d082fab991ec1d84161103f74b4d58f9f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/545.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/546.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/546.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6790f6ff0a998089687d176009583366a1c5b47b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/546.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/547.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/547.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4933e860f0e1a2e98a64c4a41f7ec6b3be075c66 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/547.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jaygala24", "New dataset": 22} +{"GitHub": "PranjalChitale", "New dataset": 16} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/548.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/548.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e80e06984a87ac01f7eec63196cc6b358c895e21 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/548.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "HLasse", "Bug fixes": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/549.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/549.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cc13c81fb97a9719a5d6b5be915ca52153a259bd --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/549.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "HLasse", "Bug fixes": 1} +{"GitHub": "HLasse", "Dataset annotations": 5} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/551.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/551.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1a26d5b943c6b04c33145768e466f52b49877f5d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/551.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "davidstap", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/556.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/556.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1e38b6d70322ee31d8c4fd0437e38c8a34d51113 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/556.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "New dataset": 10} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/557.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/557.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f87e9b7033bdf053dbe46007bc176429ac6c53f0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/557.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/558.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/558.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1e556df1e3499a0f808afe4ab646a275d74bbe0b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/558.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dokato", "Bug fixes": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/560.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/560.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..718c9bf0fa867e7de45a027b09d4a3c5bf085df2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/560.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "Andrian0s", "Review PR": 2} +{"GitHub": "imenelydiaker", "New dataset": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/561.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/561.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..143c50c5eb8723d69bb1224965886630d77fc154 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/561.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dokato", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "asparius", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/563.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/563.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..552ff170000e945009eef5da4401a48fd1a0992a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/563.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 8} +{"GitHub": "dokato", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/564.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/564.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1cf746b170f059f80ce84271bd8d38fac6ab066b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/564.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 14} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/565.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/565.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4c6d03aab4a4edbb2520fdfd446ca889cd8cc837 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/565.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "jaygala24", "New dataset": 10} +{"GitHub": "imenelydiaker", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/569.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/569.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..78cca33956f9a521b0700b5f61bdee07818a7b11 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/569.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Akash190104", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/570.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/570.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4e0576a31bb9bb12600a30e67e1f523308bdf974 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/570.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "isaac-chung", "New dataset": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/571.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/571.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2b64106d2a479825ae07862aa70a82f7b6178962 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/571.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 16} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/572.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/572.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4ae02a8a537f893f4d4c35e2761c11adacb27395 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/572.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "loicmagne", "Bug fixes": 8} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/574.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/574.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f05a65589d7589af3f90a24f997acc02380356a0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/574.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dokato", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/575.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/575.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..83937e3a76c19a7f6fa3a19f47c51f44f399d036 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/575.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "imenelydiaker", "New dataset": 18} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/576.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/576.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..416829ec099fed1cf4c0357f604797004b28d7a5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/576.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/578.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/578.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..087efc1143a7c4abdc54602a25cca8a09b046c11 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/578.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "antoniolanza1996", "Bug fixes": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/579.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/579.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c42ad6b17ff41dbcb10c6e16e638e5f7dd713ebe --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/579.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "awinml", "New dataset": 16} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/583.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/583.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d0c0f1d23b85969a84430aa939357eb7a9a1b67f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/583.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "davidstap", "New dataset": 100} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "dokato", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/585.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/585.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a0ee5d06786dcaea6640f05657ef9c1aee4a1f81 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/585.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dokato", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "asparius", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/588.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/588.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..674def9ff18ba3766b58f1c0e76395df78a4670e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/588.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "dipam7", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/590.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/590.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fa49c2d10eba5f07a1f1aec40d34843e75cad062 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/590.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 30} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/592.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/592.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1e0e134593565fb7e028e95f672999d5704616fc --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/592.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Akash190104", "New dataset": 2} +{"GitHub": "asparius", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/594.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/594.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a8f1e726cbaa2bc8c707726e9a4ff9d3f0fa2f90 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/594.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "cassanof", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/598.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/598.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..32c4cbd45c09d31035cfa21da1f258f85e6147d1 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/598.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "sted97", "New dataset": 10} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/600.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/600.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3cbe04ff102ff44332c43416fe24e7fc86b73847 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/600.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 34} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/603.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/603.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..644b789d082fab991ec1d84161103f74b4d58f9f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/603.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/604.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/604.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0bbc0e3acee69e87e5e2a1bfe9e64928fe32adc3 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/604.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Bug fixes": 4} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/605.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/605.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8a445b207afd85cfd05509be14b57ad4fba6eec7 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/605.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "taeminlee", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/606.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/606.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ad95edb09d0d3abd6675a8e60345d1ffdc02cae5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/606.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "Bug fixes": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/607.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/607.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..04a57d04b4d94e669398c14a4777ad3fe93c9e81 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/607.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "rafalposwiata", "New dataset": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/610.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/610.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..18537874c06c599941a63d64f0ee0204d29dfa64 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/610.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Sakshamrzt", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/611.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/611.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a126fd5ca484c8e342505791be4d049de5274062 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/611.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 16} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/613.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/613.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a126fd5ca484c8e342505791be4d049de5274062 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/613.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 16} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/615.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/615.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..149fd48935bd1183868d808ef04031162a666c3f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/615.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "wissam-sib", "Bug fixes": 4} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/616.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/616.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51022da3236c84fcd246d81c8c2849a5e8a54e24 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/616.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "SaitejaUtpala", "New dataset": 54} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/621.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/621.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b95f46bcad8a1dceb451acdbb790d8ccb1413fa4 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/621.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/622.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/622.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a126fd5ca484c8e342505791be4d049de5274062 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/622.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 16} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/623.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/623.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5f1530f642968558794d494e1c91d14afbf5b390 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/623.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 42} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/624.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/624.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..86b7af1609a0030b1660634c5637f1cd8628dae7 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/624.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "x-tabdeveloping", "New dataset": 2} +{"GitHub": "x-tabdeveloping", "New task": 2} +{"GitHub": "x-tabdeveloping", "Bug fixes": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/626.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/626.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c0a7e20382583da3d4ea29699fe8d09d719600b0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/626.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "ABorghini", "New dataset": 10} +{"GitHub": "imenelydiaker", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/627.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/627.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff6bd2067c48d6d1fd8fb529cdd55d332803b977 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/627.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/628.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/628.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ff6bd2067c48d6d1fd8fb529cdd55d332803b977 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/628.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dipam7", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/629.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/629.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a3a37b9e54f77c8445b1b879ad05e1c467f362a8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/629.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 2} +{"GitHub": "isaac-chung ", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/630.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/630.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1ea531e1f25dc8b18c6fbe82a68ff57946d9ffdf --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/630.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "ljvmiranda921", "New dataset": 2} +{"GitHub": "shreeya-dhakal", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/632.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/632.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..421291c256b2328f2495165bf4174528d69734e1 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/632.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "ljvmiranda921", "New dataset": 6} +{"GitHub": "shreeya-dhakal", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/633.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/633.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..93439a3a22c3ee0aa62ae89644f208907d514262 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/633.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "jupyterjazz", "New dataset": 8} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "shreeya-dhakal", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/634.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/634.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1ea531e1f25dc8b18c6fbe82a68ff57946d9ffdf --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/634.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "ljvmiranda921", "New dataset": 2} +{"GitHub": "shreeya-dhakal", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/635.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/635.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1931d413d3077384af95c4a89103f676c771d582 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/635.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "loicmagne", "Bug fixes": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/636.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/636.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..bf1319b4e85b714873f335ebc83cda8e7f035a23 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/636.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "jupyterjazz", "New dataset": 100} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "Andrian0s", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/637.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/637.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80197d5cfc305b97c113a0efe4586ae159fe9341 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/637.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "sted97", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/643.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/643.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7d36b4bed84b8e92e6d2cde238483440a1ac5d8c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/643.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "bakrianoo", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/644.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/644.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..5adbb1ee167c8ad6707b53986a1c7ad6472c8355 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/644.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/645.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/645.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ec1c5cb2aa78afdd6d508fa51569260df2e33582 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/645.jsonl @@ -0,0 +1,4 @@ +{"GitHub" : "Andrian0s", "New dataset" : 8} +{"GitHub" : "simon-clematide", "New dataset" : 10} +{"GitHub" : "KennethEnevoldsen", "Review PR": 2} +{"GitHub" : "orionw", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/648.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/648.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43c8df7cc68944fe448eb6ea9bfef197f15bbc41 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/648.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/649.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/649.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3a110f2c7cfce2502ece936e60aa027c61d18134 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/649.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "Andrian0s", "New dataset": 6} +{"GitHub": "Andrian0s", "Bug fixes": 2} +{"GitHub": "orionw", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/650.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/650.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3ff4110c2dddf186d4f9c96843e7dd18e66ce9d5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/650.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "jankounchained", "New dataset": 10} +{"GitHub": "x-tabdeveloping", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/653.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/653.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b939b26521d9024e28e4b02a4a606386d61159a5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/653.jsonl @@ -0,0 +1,2 @@ +{"GitHub" : "MexicanLemonade", "New dataset" : 2} +{"GitHub" : "isaac-chung", "Review PR" : 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/655.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/655.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e2fc5871f7f2d9df07116153e2d2187cb64a8bd8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/655.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 20} +{"GitHub": "x-tabdeveloping", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/657.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/657.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..51ab74babf8d5f2915621715b178c4bb28f10a5d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/657.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 18} +{"GitHub": "x-tabdeveloping", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/658.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/658.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2854d8e2ff12a24df093bde0c930428650bc91a8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/658.jsonl @@ -0,0 +1,5 @@ +{"GitHub": "KennethEnevoldsen", "Bug fixes": 6} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "x-tabdeveloping", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/659.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/659.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6c929192a705fc419764d16a412e85963d7130ae --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/659.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 14} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/661.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/661.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb45b7c6fb0bc24f1ecec45e38a5652c404c3a90 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/661.jsonl @@ -0,0 +1 @@ +{"GitHub": "awinml", "New dataset": 20} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/662.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/662.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2dd165b433e820c5344544be4aaf67f09d29b652 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/662.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "Akash190104", "New dataset": 34} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/665.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/665.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb45b7c6fb0bc24f1ecec45e38a5652c404c3a90 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/665.jsonl @@ -0,0 +1 @@ +{"GitHub": "awinml", "New dataset": 20} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/670.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/670.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1424ac649096d0592f2aa229a703885e9e571e5a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/670.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "New dataset": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/671.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/671.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6ac5ffc235869c8092ee885f241a513b623790d5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/671.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Bug fixes": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/672.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/672.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..125db4ced2e94c98afb37675100f2c95a8abb206 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/672.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "wissam-sib", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/673.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/673.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1c648b96500338a7342324211b5c5946e30bd22b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/673.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "mmhamdy", "New dataset": 6} +{"GitHub": "x-tabdeveloping", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/674.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/674.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..251af626ae3bf390fcc54d0990975131802b391a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/674.jsonl @@ -0,0 +1,5 @@ +{"GitHub": "Ruqyai", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "mrshu", "Review PR": 2} +{"GitHub": "KranthiGV", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/675.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/675.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..0a63831b0d5cb5feb5c3b306b0317d4a9bbd2039 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/675.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "wissam-sib", "New dataset": 6} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/676.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/676.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a714dbfa1f8afcda2aae6a9b210ec9e3cc282581 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/676.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "wissam-sib", "New dataset": 6} +{"GitHub": "kranthigv", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/678.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/678.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43c8df7cc68944fe448eb6ea9bfef197f15bbc41 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/678.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/680.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/680.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43c8df7cc68944fe448eb6ea9bfef197f15bbc41 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/680.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/682.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/682.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..43c8df7cc68944fe448eb6ea9bfef197f15bbc41 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/682.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 20} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/690.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/690.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e2b6194c27e2db0f4222f326ca733d9a3cd818ba --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/690.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "kranthigv", "New dataset": 20} +{"GitHub": "awinml", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/693.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/693.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ae33c547e8175e2f18714867c20c615f6f738817 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/693.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 10} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/694.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/694.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..cd2205ed92e8a77798d56e691ee1a4d198eb6838 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/694.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "x-tabdeveloping", "Bug fixes": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/695.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/695.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c0ff9d03cfa751d7080e69ef0ab5f0dcc054e781 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/695.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "mrshu", "New dataset": 8} +{"GitHub": "x-tabdeveloping", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/697.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/697.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2382f989c04de1799ad3dcda8a7e9f76f8c5f09f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/697.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "mrshu", "New dataset": 4} +{"GitHub": "x-tabdeveloping", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/699.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/699.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e831a26fec3d512dfcf25d4b52d206ae41061a8f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/699.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "x-tabdeveloping", "Bug fixes": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "Muenninghoff", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/701.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/701.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..7fe68e4b1e85fda4652fde18b5234cdbcfe26da5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/701.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "Paper writing": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "mrshu", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/712.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/712.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2032208a97cd7f3b556050b36e21e373bdc21397 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/712.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "imenelydiaker", "Bug fixes": 4} +{"GitHub": "Muennighoff", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/714.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/714.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..eb461b9659a4f14762a8a8bca43fbf249a6cd5a4 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/714.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "vaibhavad", "New dataset": 2} +{"GitHub": "vaibhavad", "Bug fixes": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "orionw", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/716.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/716.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3c06dc852a3beaa880a403735f07b5a655d2c843 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/716.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "mrshu", "New dataset": 2} +{"GitHub": "KranthiGV", "Review PR": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/718.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/718.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fc9d9c86c669abda685e6b8d5c280dfd366cdcf8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/718.jsonl @@ -0,0 +1,5 @@ +{"GitHub": "rasdani", "New dataset": 22} +{"GitHub": "ShawonAshraf", "New dataset": 28} +{"GitHub": "bjoernpl", "New dataset": 28} +{"GitHub": "jphme", "New dataset": 28} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/721.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/721.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..afe010acc3af8986be266428c47139d0ce9ade46 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/721.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "wissam-sib", "New dataset": 8} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/723.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/723.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6477375bc905f9aa5a5dc64dffb147343511bcb6 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/723.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "wissam-sib", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/724.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/724.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c2d55561f44559a0b782e288a9b8ac780971ac3d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/724.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "Art3mis07", "New dataset": 12} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "kranthigv", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/725.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/725.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..6477375bc905f9aa5a5dc64dffb147343511bcb6 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/725.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "wissam-sib", "New dataset": 6} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/727.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/727.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..53994d12aad78963c9669bfbbf3445f58a4bda0c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/727.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "mrshu", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/729.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/729.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b2c7f0083d55ccf9df22e72373eba2358034d19b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/729.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/730.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/730.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..77eafc4844b5282a167146178d64f8bde7219548 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/730.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "wissam-sib", "New dataset": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/731.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/731.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1606ce018ae25bdcacbdc4cc5541bc4cf20b5d42 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/731.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "malteos", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/733.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/733.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..75ca33bee51f002e69af78c3049269406322ddee --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/733.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "bp-high", "New dataset": 26} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KranthiGV", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/735.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/735.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b8588b34a6412c39ba4b2c172cc92368374aae17 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/735.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "malteos", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "Ruqyai", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/736.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/736.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..2a95159593052f5161affe18a72b36ebe8292bb4 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/736.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "wissam-sib", "New dataset": 6} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "kranthigv", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/737.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/737.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..65cf01b5bb73410dfce29d779a09cf474923596e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/737.jsonl @@ -0,0 +1,5 @@ +{"GitHub": "malteos", "New dataset": 6} +{"GitHub": "KranthiGV", "Review PR": 2} +{"GitHub": "wissam-sib", "Review PR": 2} +{"GitHub": "Ruqyai", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2, "Bug fixes": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/740.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/740.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d16d99476a60178747b6bf8764074193af6ccf70 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/740.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "shreeya-dhakal", "New dataset": 4} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/745.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/745.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..3f9d7fde6e661add6c7cbf950a0930f735049145 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/745.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 2, "Bug fixes": 2} +{"GitHub": "x-tabdeveloping", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/750.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/750.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fb902563059f7075ee4e610561bb89c5a642c87d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/750.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "xhluca", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "wissam-sib", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/757.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/757.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e4001b1f1bf485ddb2f3605204b6fc5b0e02636f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/757.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "isaac-chung", "Bug fixes": 8} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "Ruqyai", "Review PR": 2} +{"GitHub": "x-tabdeveloping", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/758.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/758.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..338cd8da767f7659efff8b9f6fe7eb4f25a15e03 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/758.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "mrshu", "Dataset annotations": 1} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/759.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/759.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9896601d36f64a35f60443c0f3b2588497ac7f07 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/759.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Bug fixes": 6} +{"GitHub": "x-tabdeveloping", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/767.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/767.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..1bef14f8dfd975b4e114233240f9e8eb3faf729b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/767.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "x-tabdeveloping", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/768.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/768.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..4ef2b2a763b81f91028c1aec63378906be4b45c4 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/768.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 8} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/769.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/769.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9617cb2a3ca5c6338a54d55b0988f2aaac10584 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/769.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "awinml", "New dataset": 2} +{"GitHub": "isaac-chung", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/770.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/770.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9896601d36f64a35f60443c0f3b2588497ac7f07 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/770.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Bug fixes": 6} +{"GitHub": "x-tabdeveloping", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/772.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/772.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8a981ec395ff391169287024ee3eafd2c60c5a6e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/772.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "New dataset": 2, "Bug fixes": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/773.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/773.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..15e972a9e335f1b877817b7aefe0b839ff387bef --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/773.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "dokato", "New dataset": 6} +{"GitHub": "x-tabdeveloping", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/779.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/779.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..442cea64c90025bc702c23b6dffcee0cb69e1856 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/779.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "xhluca", "New dataset": 2} +{"GitHub": "xhluca", "Bug fixes": 2} +{"GitHub": "vaibhavad", "Review PR": 2} +{"GitHub": "orionw", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/781.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/781.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..451a563efed650f7b8cec583ea4eef76340d7c67 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/781.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "KennethEnevoldsen", "Dataset annotations": 26} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/785.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/785.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..45324201f93e78ee0b6f26a7ef4d5a608c565320 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/785.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/787.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/787.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..9ee0b2eb49a7d0da498cc5898c54ca78b39f16c3 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/787.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "New dataset": 6, "Dataset annotations": 1} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "x-tabdeveloping", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/788.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/788.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..fd29fc1f1e6c639fd55196f6f9faca474f21387f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/788.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "jankounchained", "New dataset": 4, "Bug fixes": 8} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/789.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/789.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d4666fd7281bcb4c25fed8c625a102909a4bd41a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/789.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 2} +{"GitHub": "imenelydiaker", "Bug fixes": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/791.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/791.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..d3eb3e090d2019e20fa31df3c4cb6955c7ce937f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/791.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "Bug fixes": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/792.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/792.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..af9c7ff92cf90c258e869921e394b52de5c91bf7 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/792.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "AlexeyVatolin", "Bug fixes": 4} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "Ruqyai", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/793.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/793.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8d34c45d96f8aea792ddb66115d67a6601199b7a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/793.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "AlexeyVatolin", "Bug fixes": 4} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/794.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/794.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b4104704c8541916eb582af123ac8a3bee52739e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/794.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "AlexeyVatolin", "Bug fixes": 4} +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/795.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/795.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..8d34c45d96f8aea792ddb66115d67a6601199b7a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/795.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "AlexeyVatolin", "Bug fixes": 4} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/799.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/799.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..c8399882416d17f4f9b8131361f8ce5955f431a3 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/799.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "vaibhavad", "New dataset": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/805.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/805.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..b2a6430ce3c24bfc22be8a250d20ee0d1e63a0ae --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/805.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "Bug fixes": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/806.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/806.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..804cf48e4f223507fd6284b93d7b57eadef7a18a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/806.jsonl @@ -0,0 +1,4 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Bug fixes": 4} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/807.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/807.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..ae60e6d5f05e1a3066f76460f77a04b790abfd47 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/807.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Bug fixes": 5} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/812.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/812.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..696fecfb7cb6da51eee8adf466cd62624b1166e2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/812.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "dokato", "Bug fixes": 2} +{"GitHub": "isaac-chung", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/826.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/826.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..f2a50886793e46301c583cdab83e757fe111ce26 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/826.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "imenelydiaker", "Review PR": 2} +{"GitHub": "Muennighoff", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Bug fixes": 4} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/827.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/827.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..a9dda512d84ad41b56a619d2cb8e75267d93d476 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/827.jsonl @@ -0,0 +1,3 @@ +{"GitHub": "isaac-chung", "Review PR": 2} +{"GitHub": "KennethEnevoldsen", "Review PR": 2} +{"GitHub": "imenelydiaker", "Bug fixes": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/832.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/832.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..80d2f6f988702f1be22fdb121af253e4a09f875f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/832.jsonl @@ -0,0 +1,2 @@ +{"GitHub": "isaac-chung", "Bug fixes": 4} +{"GitHub": "imenelydiaker", "Review PR": 2} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points/scores_from_old_system.jsonl b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/scores_from_old_system.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..681c17146fc24aceeb2aecca3283c67a79650869 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points/scores_from_old_system.jsonl @@ -0,0 +1,33 @@ +{"GitHub": "KennethEnevoldsen", "New dataset": 54, "Dataset annotations": 8, "Bug fixes": 18, "Review PR": 74, "Coordination": 5} +{"GitHub": "x-tabdeveloping", "New dataset": 48} +{"GitHub": "imenelydiaker", "New dataset": 88, "Bug fixes": 3, "Review PR": 36} +{"GitHub": "wissam-sib", "New dataset": 88, "Review PR": 2} +{"GitHub": "GabrielSequeira", "New dataset": 88} +{"GitHub": "schmarion", "New dataset": 88} +{"GitHub": "MathieuCiancone", "New dataset": 88} +{"GitHub": "Sakshamrzt", "New dataset": 10, "Review PR": 4} +{"GitHub": "MartinBernstorff", "New dataset": 2, "Bug fixes": 7, "Review PR": 8} +{"GitHub": "guenthermi", "New dataset": 12} +{"GitHub": "Muennighoff", "Review PR": 16} +{"GitHub": "rasdani", "New dataset": 6} +{"GitHub": "PhilipMay", "Review PR": 2} +{"GitHub": "slvnwhrl", "New dataset": 12} +{"GitHub": "staoxiao", "New dataset": 40} +{"GitHub": "ZhengLiu101", "New dataset": 10} +{"GitHub": "NouamaneTazi", "Review PR": 2} +{"GitHub": "rafalposwiata", "New dataset": 32} +{"GitHub": "violenil", "New dataset": 26} +{"GitHub": "hanhainebula", "New dataset": 2} +{"GitHub": "taeminlee", "New dataset": 16} +{"GitHub": "izhx", "New dataset": 6} +{"GitHub": "achibb", "New dataset": 2} +{"GitHub": "xu3kev", "New dataset": 10} +{"GitHub": "cassanof", "New dataset": 6, "Bug fixes": 1, "Running Models": 1} +{"GitHub": "taidnguyen", "New dataset": 14} +{"GitHub": "orionw", "Bug fixes": 14} +{"GitHub": "mmhamdy", "New dataset": 14} +{"GitHub": "manandey", "New dataset": 12} +{"GitHub": "isaac-chung", "New dataset": 36, "Review PR": 12} +{"GitHub": "asparius", "New dataset": 8} +{"GitHub": "rbroc", "New dataset": 12} +{"GitHub": "dwzhu-pku", "New dataset": 12} \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/points_table.md b/testbed/embeddings-benchmark__mteb/docs/mmteb/points_table.md new file mode 100644 index 0000000000000000000000000000000000000000..3fa48998ff7dfe9d52a6ec2d966f9fff1788a4b3 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/points_table.md @@ -0,0 +1,81 @@ +# Points + +_Note_: this table is **autogenerated** and should not be edited. It is intended to get an overview of contributions. + + | GitHub | New dataset | Review PR | Coordination | Bug fixes | Dataset annotations | Running Models | Paper writing | New task | Total | +|:------------------|--------------:|------------:|---------------:|------------:|----------------------:|-----------------:|----------------:|-----------:|--------:| +| KennethEnevoldsen | 68 | 226 | 11 | 73 | 35 | 0 | 0 | 0 | 413 | +| isaac-chung | 116 | 180 | 4 | 30 | 1 | 0 | 4 | 0 | 335 | +| awinml | 292 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 294 | +| imenelydiaker | 120 | 136 | 0 | 20 | 0 | 0 | 0 | 0 | 276 | +| x-tabdeveloping | 144 | 28 | 1 | 10 | 0 | 0 | 0 | 12 | 195 | +| davidstap | 176 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 176 | +| jaygala24 | 149 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 149 | +| wissam-sib | 134 | 6 | 0 | 4 | 0 | 0 | 0 | 0 | 144 | +| jupyterjazz | 108 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 108 | +| SaitejaUtpala | 102 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 102 | +| GabrielSequeira | 88 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 88 | +| schmarion | 88 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 88 | +| MathieuCiancone | 88 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 88 | +| dokato | 76 | 4 | 0 | 6 | 0 | 0 | 0 | 0 | 86 | +| digantamisra98 | 71 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 71 | +| shreeya-dhakal | 54 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 62 | +| Rysias | 58 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 58 | +| asparius | 34 | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 48 | +| Akash190104 | 46 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 46 | +| staoxiao | 40 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | +| orionw | 0 | 8 | 0 | 20 | 0 | 0 | 0 | 10 | 38 | +| rafalposwiata | 36 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 36 | +| bp-high | 36 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 36 | +| Muennighoff | 0 | 34 | 0 | 0 | 0 | 0 | 0 | 0 | 34 | +| ShawonAshraf | 28 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | +| rasdani | 28 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | +| jphme | 28 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | +| bjoernpl | 28 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 28 | +| loicmagne | 0 | 0 | 0 | 28 | 0 | 0 | 0 | 0 | 28 | +| violenil | 26 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 26 | +| kranthigv | 20 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 26 | +| dwzhu-pku | 24 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 24 | +| jankounchained | 14 | 0 | 0 | 8 | 0 | 0 | 0 | 0 | 22 | +| taeminlee | 22 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 22 | +| mrshu | 16 | 4 | 0 | 0 | 1 | 0 | 0 | 0 | 21 | +| mmhamdy | 20 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | +| rbroc | 20 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 20 | +| Andrian0s | 14 | 4 | 0 | 2 | 0 | 0 | 0 | 0 | 20 | +| manandey | 18 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 18 | +| MartinBernstorff | 2 | 8 | 0 | 7 | 0 | 0 | 0 | 0 | 17 | +| dipam7 | 14 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 16 | +| Sakshamrzt | 12 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 16 | +| PranjalChitale | 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 16 | +| sted97 | 16 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 16 | +| AlexeyVatolin | 0 | 0 | 0 | 16 | 0 | 0 | 0 | 0 | 16 | +| taidnguyen | 14 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 14 | +| guenthermi | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | +| slvnwhrl | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | +| Art3mis07 | 12 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 12 | +| simon-clematide | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| vaibhavad | 4 | 2 | 0 | 4 | 0 | 0 | 0 | 0 | 10 | +| ABorghini | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| guangyusong | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| Ruqyai | 2 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| cassanof | 8 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | 10 | +| HLasse | 0 | 0 | 0 | 5 | 5 | 0 | 0 | 0 | 10 | +| malteos | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| ZhengLiu101 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| xu3kev | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| ljvmiranda921 | 10 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 10 | +| KranthiGV | 0 | 8 | 0 | 0 | 0 | 0 | 0 | 0 | 8 | +| izhx | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | +| xhluca | 4 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 6 | +| marcobellagente93 | 6 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 6 | +| hanhainebula | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| bakrianoo | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| antoniolanza1996 | 0 | 0 | 0 | 2 | 0 | 0 | 0 | 0 | 2 | +| achibb | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| isaac-chung | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| PhilipMay | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| NouamaneTazi | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| Muenninghoff | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| tomaarsen | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| MexicanLemonade | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | +| ManuelFay | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 2 | \ No newline at end of file diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/readme.md b/testbed/embeddings-benchmark__mteb/docs/mmteb/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..3a480c539f82ef69d4ac4959f3d6c630b7ace250 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/readme.md @@ -0,0 +1,68 @@ +# Welcome to MMTEB! 👋 + +The Massive Multilingual Text Embedding Benchmark (MMTEB) is a community-led extension of [MTEB](https://arxiv.org/abs/2210.07316) to cover embedding tasks for a massive number of languages. + +## Background + +The Massive Text Embedding Benchmark (MTEB) is intended to evaluate the quality of document embeddings. When it was initially introduced, the benchmark consisted of 8 embedding tasks and 58 different datasets. Since then, MTEB has been subject to multiple community contributions as well as benchmark extensions over specific languages such as [SEB](https://openreview.net/pdf/f5f1953a9c798ec61bb050e62bc7a94037fd4fab.pdf), [C-MTEB](https://github.com/FlagOpen/FlagEmbedding/tree/master/C_MTEB) and [MTEB-French](https://github.com/Lyon-NLP/mteb-french). However, we want even wider coverage and thus announce the community-led extension of MTEB, where we seek to expand coverage of MTEB to as many languages as possible. + +## Contributing to MMTEB + +Everyone can join and contribute to this initiative from: +- 10th of April 2024 to 15th of May 2024 for adding new datasets +- 15th of May to 30th of May for running models + +Win some SWAG, and become a co-author of our upcoming paper. We aim to publish the results of our findings at a top conference such as EMNLP, NeurIPS, etc. We have identified four ways to contribute: + +### 🗃️ 1: Contribute a new dataset + +For this segment, you open a PR in the MTEB repository where you create an implementation (subclass) of a task using a new language dataset uploaded to huggingface. Read more about how to add a dataset [here](../adding_a_dataset.md) and check out [one of the previous additions](https://github.com/embeddings-benchmark/mteb/pull/247) for an example. + +### 🖥️ 2: Contribute a new task + +MTEB currently consists of 8 embedding tasks including tasks such as STS, retrieval, reranking, and more. If you feel like there is a category of tasks that is not yet covered, we would welcome contributions of these as well. + +### 🔍 3: Contribute new scores + +Once we have the datasets, we want to evaluate models on them. We welcome evaluation scores for models, which will be added to the leaderboard. + +### 🔓 4: Review PRs + +We welcome reviews of PRs adding new datasets. If you wish to review PRs of a specific language feel free to contact members of the MTEB team. + +## Authorship + +We follow a similar approach as in the [SeaCrowd Project](https://github.com/SEACrowd#contributing-to-seacrowd) and use a point-based system to determine co-authorships. + +To be considered a co-author, at least 10 contribution points are required. The position of contributors in the author list is determined by the score they acquire, higher scores will appear first. + +To monitor how many points you have obtained, the contribution point tracking is now live at [this sheet](points.md) and we recommend updating the score along with your PR. Past contributions also count. + +Everyone with sufficient points will also be added to the MTEB GitHub and Huggingface repository as a contributor. + +# Contribution point guideline +The contribution points are computed using the following table: + +> **Note**: The purpose of the point system is not to barrier collaboration, but to reward contributions. We might adjust the point requirement lower to accommodate more co-authorship if needed. + + +| Contribution type | Demand | Points | Description | +| ------------------- | ------------------- | ------- | ----------------------------------------------------------------------------------------------------------------- | +| New dataset | As many as possible | 2+bonus | The first dataset for a language x task gains 4 bonus points. If the number of new languages is >= 12 then points for that PR for a new dataset are capped at 50 (12 * 4 + 2 = 48 + 2 = 50).| +| New task | If relevant | 10 | Task 2. | +| Dataset annotations | On demand | 1 | Adding missing dataset annotations to existing datasets. | +| Bug fixes | On demand | 1-10 | Points depends the effect of code changes. If you want to find issues related to the MMTEB you can find them [here](https://github.com/embeddings-benchmark/mteb/milestone/1), issues marked with "help-wanted" or "good-first-issue" are great places to start. | +| Running Models | On demand | 1 | Task 3. | +| Review PR | On demand | 2 | Task 4. | + +For the purpose of counting points, a language is defined by its [ISO 639-3](https://en.wikipedia.org/wiki/ISO_639-3) code, however, we encourage dialects or written language variants. All programming languages are considered one language. + +Team submissions are free to distribute points among the members as they like. + +## Communication Channels + +We will communicate via this GitHub repository. Please feel free to open issues or discussions and `Watch` the repository to be notified of any changes. + +# Acknowledgments + +We thank [Contextual AI](https://contextual.ai/) for sponsoring the compute for this project. diff --git a/testbed/embeddings-benchmark__mteb/docs/mmteb/validate_points.py b/testbed/embeddings-benchmark__mteb/docs/mmteb/validate_points.py new file mode 100644 index 0000000000000000000000000000000000000000..59500e70282a767971bf1a58149281fba435aa32 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/mmteb/validate_points.py @@ -0,0 +1,75 @@ +import logging +import os +from typing import Optional + +from jsonlines import Reader +from pydantic import BaseModel, ConfigDict, Field, ValidationError, conint, constr + +commit_exceptions = { + "scores_from_old_system", + # <100 points: from before max points were enforced + "440", + "543", + "616", + "636", + # >100 points: from before max points were enforced (reduced to 100 points) + "583", +} + + +# Define a Pydantic model to represent each JSON object +class JsonObject(BaseModel): + model_config = ConfigDict(extra="forbid") + GitHub: constr(min_length=1) + new_dataset: Optional[conint(ge=2)] = Field(alias="New dataset", default=None) + new_task: Optional[conint(ge=2)] = Field(alias="New task", default=None) + dataset_annotations: Optional[conint(ge=1)] = Field( + alias="Dataset annotations", default=None + ) + bug_fixes: Optional[conint(ge=1)] = Field(alias="Bug fixes", default=None) + running_models: Optional[conint(ge=1)] = Field(alias="Running Models", default=None) + review_pr: Optional[conint(ge=2)] = Field(alias="Review PR", default=None) + paper_writing: Optional[int] = Field(alias="Paper writing", default=None) + Ideation: Optional[int] = None + Coordination: Optional[int] = None + + +def check_max_points(obj: JsonObject, commit_n: str): + if obj.new_dataset is not None: + if obj.new_dataset > 50 and commit_n not in commit_exceptions: + raise ValueError(f"Commit {commit_n} exceeds max points for new_dataset") + + +# Function to validate JSONL files in a folder +def validate_jsonl_files(folder_path): + for filename in os.listdir(folder_path): + if filename.endswith(".jsonl"): + file_path = os.path.join(folder_path, filename) + commit_n = os.path.splitext(filename)[0] + with open(file_path, "r", encoding="utf-8") as file: + try: + # Read JSONL file + reader = Reader(file) + except Exception: + raise Exception("Error reading file:", file_path) + for line in reader: + try: + # Validate JSON object against schema + x = JsonObject(**line) + logging.debug(x) + check_max_points(x, commit_n) + + except ValidationError as e: + raise Exception( + "Validation Error in file:", file_path, line + ) from e + + +# Main function +def main(): + folder_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "points") + validate_jsonl_files(folder_path) + + +if __name__ == "__main__": + main() diff --git a/testbed/embeddings-benchmark__mteb/docs/tasks.md b/testbed/embeddings-benchmark__mteb/docs/tasks.md new file mode 100644 index 0000000000000000000000000000000000000000..f500e7deebcea52d12a79c0b0c974a846b25446f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/docs/tasks.md @@ -0,0 +1,1571 @@ +## Available tasks +The following tables give you an overview of the tasks in MTEB. + +
+ + + +| Name | Languages | Type | Category | Domains | # Samples | Avg. Length (Char.) | +|------|-----------|------|----------|---------|-----------|---------------------| +| [AFQMC](https://aclanthology.org/2021.emnlp-main.357) | ['cmn'] | STS | s2s | | | | +| [AILACasedocs](https://zenodo.org/records/4063986) | ['eng'] | Retrieval | p2p | [Legal] | | | +| [AILAStatutes](https://zenodo.org/records/4063986) | ['eng'] | Retrieval | p2p | [Legal] | | | +| [AJGT](https://link.springer.com/chapter/10.1007/978-3-319-60042-0_66/) (Alomari et al., 2017) | ['ara'] | Classification | s2s | [Social] | {'train': 1800} | {'train': 46.81} | +| [ATEC](https://aclanthology.org/2021.emnlp-main.357) | ['cmn'] | STS | s2s | | | | +| [AfriSentiClassification](https://arxiv.org/abs/2302.08956) | ['amh', 'arq', 'ary', 'hau', 'ibo', 'kin', 'pcm', 'por', 'swa', 'tso', 'twi', 'yor'] | Classification | s2s | [Social] | {'test': 2048} | {'test': 74.77} | +| [AfriSentiLangClassification](https://huggingface.co/datasets/HausaNLP/afrisenti-lid-data/) | ['amh', 'arq', 'ary', 'hau', 'ibo', 'kin', 'pcm', 'por', 'swa', 'tso', 'twi', 'yor'] | Classification | s2s | [Social] | {'test': 5754} | {'test': 77.84} | +| [AllegroReviews](https://aclanthology.org/2020.acl-main.111.pdf) | ['pol'] | Classification | s2s | | {'test': 1006} | {'test': 477.2} | +| [AlloProfClusteringP2P.v2](https://huggingface.co/datasets/lyon-nlp/alloprof) (Lefebvre-Brossard et al., 2023) | ['fra'] | Clustering | p2p | [Encyclopaedic] | {'test': 2556} | {'test': 3539.5} | +| [AlloProfClusteringS2S.v2](https://huggingface.co/datasets/lyon-nlp/alloprof) (Lefebvre-Brossard et al., 2023) | ['fra'] | Clustering | s2s | [Encyclopaedic] | {'test': 2556} | {'test': 32.8} | +| [AlloprofReranking](https://huggingface.co/datasets/antoinelb7/alloprof) (Lefebvre-Brossard et al., 2023) | ['fra'] | Reranking | s2p | [Web, Academic] | {'test': 2316, 'train': 9264} | | +| [AlloprofRetrieval](https://huggingface.co/datasets/antoinelb7/alloprof) | ['fra'] | Retrieval | s2p | | | | +| [AmazonCounterfactualClassification](https://arxiv.org/abs/2104.06893) | ['deu', 'eng', 'jpn'] | Classification | s2s | [Reviews] | {'validation': 335, 'test': 670} | {'validation': 109.2, 'test': 106.1} | +| [AmazonPolarityClassification](https://huggingface.co/datasets/amazon_polarity) (Julian McAuley, 2013) | ['eng'] | Classification | s2s | [Reviews] | {'test': 400000} | {'test': 431.4} | +| [AmazonReviewsClassification](https://arxiv.org/abs/2010.02573) | ['cmn', 'deu', 'eng', 'fra', 'jpn', 'spa'] | Classification | s2s | | {'validation': 30000, 'test': 30000} | {'validation': 159.2, 'test': 160.4} | +| [AngryTweetsClassification](https://aclanthology.org/2021.nodalida-main.53/) (Pauli et al., 2021) | ['dan'] | Classification | s2s | [Social] | {'test': 1050} | {'test': 156.1} | +| [ArEntail](https://link.springer.com/article/10.1007/s10579-024-09731-1) (Obeidat et al., 2024) | ['ara'] | PairClassification | s2s | [News] | {'test': 1000} | {'test': 65.77} | +| [ArXivHierarchicalClusteringP2P](https://www.kaggle.com/Cornell-University/arxiv) | ['eng'] | Clustering | p2p | [Academic] | {'test': 2048} | {'test': 1009.98} | +| [ArXivHierarchicalClusteringS2S](https://www.kaggle.com/Cornell-University/arxiv) | ['eng'] | Clustering | p2p | [Academic] | {'test': 2048} | {'test': 1009.98} | +| [ArguAna](http://argumentation.bplaced.net/arguana/data) | ['eng'] | Retrieval | s2p | | | | +| [ArguAna-PL](https://huggingface.co/datasets/clarin-knext/arguana-pl) | ['pol'] | Retrieval | s2p | | | | +| [ArmenianParaphrasePC](https://github.com/ivannikov-lab/arpa-paraphrase-corpus) (Arthur Malajyan, 2020) | ['hye'] | PairClassification | s2s | [News] | {'train': 4023, 'test': 1470} | {'train': 243.81, 'test': 241.37} | +| [ArxivClassification](https://ieeexplore.ieee.org/document/8675939) (He et al., 2019) | ['eng'] | Classification | s2s | [Academic] | {'test': 2048} | | +| [AskUbuntuDupQuestions](https://github.com/taolei87/askubuntu) | ['eng'] | Reranking | s2s | | {'test': 2255} | {'test': 52.5} | +| [Assin2RTE](https://link.springer.com/chapter/10.1007/978-3-030-41505-1_39) (Real et al., 2020) | ['por'] | PairClassification | s2s | | {'test': 2448} | {'test': 53.55} | +| [Assin2STS](https://link.springer.com/chapter/10.1007/978-3-030-41505-1_39) (Real et al., 2020) | ['por'] | STS | s2s | | {'test': 2448} | {'test': 53.55} | +| [BIOSSES](https://tabilab.cmpe.boun.edu.tr/BIOSSES/DataSet.html) | ['eng'] | STS | s2s | | | | +| [BQ](https://aclanthology.org/2021.emnlp-main.357) | ['cmn'] | STS | s2s | | | | +| [BSARDRetrieval](https://huggingface.co/datasets/maastrichtlawtech/bsard) | ['fra'] | Retrieval | s2p | | | | +| [BUCC.v2](https://comparable.limsi.fr/bucc2018/bucc2018-task.html) | ['cmn', 'deu', 'eng', 'fra', 'rus'] | BitextMining | s2s | | {'test': 641684} | {'test': 101.3} | +| [Banking77Classification](https://arxiv.org/abs/2003.04807) | ['eng'] | Classification | s2s | | {'test': 3080} | {'test': 54.2} | +| [BelebeleRetrieval](https://arxiv.org/abs/2308.16884) (Lucas Bandarkar, 2023) | ['acm', 'afr', 'als', 'amh', 'apc', 'arb', 'ars', 'ary', 'arz', 'asm', 'azj', 'bam', 'ben', 'bod', 'bul', 'cat', 'ceb', 'ces', 'ckb', 'dan', 'deu', 'ell', 'eng', 'est', 'eus', 'fin', 'fra', 'fuv', 'gaz', 'grn', 'guj', 'hat', 'hau', 'heb', 'hin', 'hrv', 'hun', 'hye', 'ibo', 'ilo', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kac', 'kan', 'kat', 'kaz', 'kea', 'khk', 'khm', 'kin', 'kir', 'kor', 'lao', 'lin', 'lit', 'lug', 'luo', 'lvs', 'mal', 'mar', 'mkd', 'mlt', 'mri', 'mya', 'nld', 'nob', 'npi', 'nso', 'nya', 'ory', 'pan', 'pbt', 'pes', 'plt', 'pol', 'por', 'ron', 'rus', 'shn', 'sin', 'slk', 'slv', 'sna', 'snd', 'som', 'sot', 'spa', 'srp', 'ssw', 'sun', 'swe', 'swh', 'tam', 'tel', 'tgk', 'tgl', 'tha', 'tir', 'tsn', 'tso', 'tur', 'ukr', 'urd', 'uzn', 'vie', 'war', 'wol', 'xho', 'yor', 'zho', 'zsm', 'zul'] | Retrieval | s2p | [Web, News] | {'test': 103500} | {'test': 568.0} | +| [BengaliDocumentClassification](https://aclanthology.org/2023.eacl-main.4) | ['ben'] | Classification | s2s | [News] | {'test': 2048} | {'test': 1658.1} | +| [BengaliHateSpeechClassification](https://huggingface.co/datasets/bn_hate_speech) (Karim et al., 2020) | ['ben'] | Classification | s2s | [News] | {'train': 3418} | {'train': 103.42} | +| [BengaliSentimentAnalysis](https://data.mendeley.com/datasets/p6zc7krs37/4) (Sazzed et al., 2020) | ['ben'] | Classification | s2s | [Reviews] | {'train': 11807} | {'train': 69.66} | +| [BibleNLPBitextMining](https://arxiv.org/abs/2304.09919) (Akerman et al., 2023) | ['aai', 'aak', 'aau', 'aaz', 'abt', 'abx', 'aby', 'acf', 'acr', 'acu', 'adz', 'aer', 'aey', 'agd', 'agg', 'agm', 'agn', 'agr', 'agt', 'agu', 'aia', 'aii', 'aka', 'ake', 'alp', 'alq', 'als', 'aly', 'ame', 'amf', 'amk', 'amm', 'amn', 'amo', 'amp', 'amr', 'amu', 'amx', 'anh', 'anv', 'aoi', 'aoj', 'aom', 'aon', 'apb', 'ape', 'apn', 'apr', 'apu', 'apw', 'apz', 'arb', 'are', 'arl', 'arn', 'arp', 'asm', 'aso', 'ata', 'atb', 'atd', 'atg', 'att', 'auc', 'aui', 'auy', 'avt', 'awb', 'awk', 'awx', 'azb', 'azg', 'azz', 'bao', 'bba', 'bbb', 'bbr', 'bch', 'bco', 'bdd', 'bea', 'bef', 'bel', 'ben', 'beo', 'beu', 'bgs', 'bgt', 'bhg', 'bhl', 'big', 'bjk', 'bjp', 'bjr', 'bjv', 'bjz', 'bkd', 'bki', 'bkq', 'bkx', 'blw', 'blz', 'bmh', 'bmk', 'bmr', 'bmu', 'bnp', 'boa', 'boj', 'bon', 'box', 'bpr', 'bps', 'bqc', 'bqp', 'bre', 'bsj', 'bsn', 'bsp', 'bss', 'buk', 'bus', 'bvd', 'bvr', 'bxh', 'byr', 'byx', 'bzd', 'bzh', 'bzj', 'caa', 'cab', 'cac', 'caf', 'cak', 'cao', 'cap', 'car', 'cav', 'cax', 'cbc', 'cbi', 'cbk', 'cbr', 'cbs', 'cbt', 'cbu', 'cbv', 'cco', 'ceb', 'cek', 'ces', 'cgc', 'cha', 'chd', 'chf', 'chk', 'chq', 'chz', 'cjo', 'cjv', 'ckb', 'cle', 'clu', 'cme', 'cmn', 'cni', 'cnl', 'cnt', 'cof', 'con', 'cop', 'cot', 'cpa', 'cpb', 'cpc', 'cpu', 'cpy', 'crn', 'crx', 'cso', 'csy', 'cta', 'cth', 'ctp', 'ctu', 'cub', 'cuc', 'cui', 'cuk', 'cut', 'cux', 'cwe', 'cya', 'daa', 'dad', 'dah', 'dan', 'ded', 'deu', 'dgc', 'dgr', 'dgz', 'dhg', 'dif', 'dik', 'dji', 'djk', 'djr', 'dob', 'dop', 'dov', 'dwr', 'dww', 'dwy', 'ebk', 'eko', 'emi', 'emp', 'eng', 'enq', 'epo', 'eri', 'ese', 'esk', 'etr', 'ewe', 'faa', 'fai', 'far', 'ffm', 'for', 'fra', 'fue', 'fuf', 'fuh', 'gah', 'gai', 'gam', 'gaw', 'gdn', 'gdr', 'geb', 'gfk', 'ghs', 'glk', 'gmv', 'gng', 'gnn', 'gnw', 'gof', 'grc', 'gub', 'guh', 'gui', 'guj', 'gul', 'gum', 'gun', 'guo', 'gup', 'gux', 'gvc', 'gvf', 'gvn', 'gvs', 'gwi', 'gym', 'gyr', 'hat', 'hau', 'haw', 'hbo', 'hch', 'heb', 'heg', 'hin', 'hix', 'hla', 'hlt', 'hmo', 'hns', 'hop', 'hot', 'hrv', 'hto', 'hub', 'hui', 'hun', 'hus', 'huu', 'huv', 'hvn', 'ian', 'ign', 'ikk', 'ikw', 'ilo', 'imo', 'inb', 'ind', 'ino', 'iou', 'ipi', 'isn', 'ita', 'iws', 'ixl', 'jac', 'jae', 'jao', 'jic', 'jid', 'jiv', 'jni', 'jpn', 'jvn', 'kan', 'kaq', 'kbc', 'kbh', 'kbm', 'kbq', 'kdc', 'kde', 'kdl', 'kek', 'ken', 'kew', 'kgf', 'kgk', 'kgp', 'khs', 'khz', 'kik', 'kiw', 'kiz', 'kje', 'kjs', 'kkc', 'kkl', 'klt', 'klv', 'kmg', 'kmh', 'kmk', 'kmo', 'kms', 'kmu', 'kne', 'knf', 'knj', 'knv', 'kos', 'kpf', 'kpg', 'kpj', 'kpr', 'kpw', 'kpx', 'kqa', 'kqc', 'kqf', 'kql', 'kqw', 'ksd', 'ksj', 'ksr', 'ktm', 'kto', 'kud', 'kue', 'kup', 'kvg', 'kvn', 'kwd', 'kwf', 'kwi', 'kwj', 'kyc', 'kyf', 'kyg', 'kyq', 'kyz', 'kze', 'lac', 'lat', 'lbb', 'lbk', 'lcm', 'leu', 'lex', 'lgl', 'lid', 'lif', 'lin', 'lit', 'llg', 'lug', 'luo', 'lww', 'maa', 'maj', 'mal', 'mam', 'maq', 'mar', 'mau', 'mav', 'maz', 'mbb', 'mbc', 'mbh', 'mbj', 'mbl', 'mbs', 'mbt', 'mca', 'mcb', 'mcd', 'mcf', 'mco', 'mcp', 'mcq', 'mcr', 'mdy', 'med', 'mee', 'mek', 'meq', 'met', 'meu', 'mgc', 'mgh', 'mgw', 'mhl', 'mib', 'mic', 'mie', 'mig', 'mih', 'mil', 'mio', 'mir', 'mit', 'miz', 'mjc', 'mkj', 'mkl', 'mkn', 'mks', 'mle', 'mlh', 'mlp', 'mmo', 'mmx', 'mna', 'mop', 'mox', 'mph', 'mpj', 'mpm', 'mpp', 'mps', 'mpt', 'mpx', 'mqb', 'mqj', 'msb', 'msc', 'msk', 'msm', 'msy', 'mti', 'mto', 'mux', 'muy', 'mva', 'mvn', 'mwc', 'mwe', 'mwf', 'mwp', 'mxb', 'mxp', 'mxq', 'mxt', 'mya', 'myk', 'myu', 'myw', 'myy', 'mzz', 'nab', 'naf', 'nak', 'nas', 'nbq', 'nca', 'nch', 'ncj', 'ncl', 'ncu', 'ndg', 'ndj', 'nfa', 'ngp', 'ngu', 'nhe', 'nhg', 'nhi', 'nho', 'nhr', 'nhu', 'nhw', 'nhy', 'nif', 'nii', 'nin', 'nko', 'nld', 'nlg', 'nna', 'nnq', 'noa', 'nop', 'not', 'nou', 'npi', 'npl', 'nsn', 'nss', 'ntj', 'ntp', 'ntu', 'nuy', 'nvm', 'nwi', 'nya', 'nys', 'nyu', 'obo', 'okv', 'omw', 'ong', 'ons', 'ood', 'opm', 'ory', 'ote', 'otm', 'otn', 'otq', 'ots', 'pab', 'pad', 'pah', 'pan', 'pao', 'pes', 'pib', 'pio', 'pir', 'piu', 'pjt', 'pls', 'plu', 'pma', 'poe', 'poh', 'poi', 'pol', 'pon', 'por', 'poy', 'ppo', 'prf', 'pri', 'ptp', 'ptu', 'pwg', 'qub', 'quc', 'quf', 'quh', 'qul', 'qup', 'qvc', 'qve', 'qvh', 'qvm', 'qvn', 'qvs', 'qvw', 'qvz', 'qwh', 'qxh', 'qxn', 'qxo', 'rai', 'reg', 'rgu', 'rkb', 'rmc', 'rmy', 'ron', 'roo', 'rop', 'row', 'rro', 'ruf', 'rug', 'rus', 'rwo', 'sab', 'san', 'sbe', 'sbk', 'sbs', 'seh', 'sey', 'sgb', 'sgz', 'shj', 'shp', 'sim', 'sja', 'sll', 'smk', 'snc', 'snn', 'snp', 'snx', 'sny', 'som', 'soq', 'soy', 'spa', 'spl', 'spm', 'spp', 'sps', 'spy', 'sri', 'srm', 'srn', 'srp', 'srq', 'ssd', 'ssg', 'ssx', 'stp', 'sua', 'sue', 'sus', 'suz', 'swe', 'swh', 'swp', 'sxb', 'tac', 'taj', 'tam', 'tav', 'taw', 'tbc', 'tbf', 'tbg', 'tbo', 'tbz', 'tca', 'tcs', 'tcz', 'tdt', 'tee', 'tel', 'ter', 'tet', 'tew', 'tfr', 'tgk', 'tgl', 'tgo', 'tgp', 'tha', 'tif', 'tim', 'tiw', 'tiy', 'tke', 'tku', 'tlf', 'tmd', 'tna', 'tnc', 'tnk', 'tnn', 'tnp', 'toc', 'tod', 'tof', 'toj', 'ton', 'too', 'top', 'tos', 'tpa', 'tpi', 'tpt', 'tpz', 'trc', 'tsw', 'ttc', 'tte', 'tuc', 'tue', 'tuf', 'tuo', 'tur', 'tvk', 'twi', 'txq', 'txu', 'tzj', 'tzo', 'ubr', 'ubu', 'udu', 'uig', 'ukr', 'uli', 'ulk', 'upv', 'ura', 'urb', 'urd', 'uri', 'urt', 'urw', 'usa', 'usp', 'uvh', 'uvl', 'vid', 'vie', 'viv', 'vmy', 'waj', 'wal', 'wap', 'wat', 'wbi', 'wbp', 'wed', 'wer', 'wim', 'wiu', 'wiv', 'wmt', 'wmw', 'wnc', 'wnu', 'wol', 'wos', 'wrk', 'wro', 'wrs', 'wsk', 'wuv', 'xav', 'xbi', 'xed', 'xla', 'xnn', 'xon', 'xsi', 'xtd', 'xtm', 'yaa', 'yad', 'yal', 'yap', 'yaq', 'yby', 'ycn', 'yka', 'yle', 'yml', 'yon', 'yor', 'yrb', 'yre', 'yss', 'yuj', 'yut', 'yuw', 'yva', 'zaa', 'zab', 'zac', 'zad', 'zai', 'zaj', 'zam', 'zao', 'zap', 'zar', 'zas', 'zat', 'zav', 'zaw', 'zca', 'zga', 'zia', 'ziw', 'zlm', 'zos', 'zpc', 'zpl', 'zpm', 'zpo', 'zpq', 'zpu', 'zpv', 'zpz', 'zsr', 'ztq', 'zty', 'zyp'] | BitextMining | s2s | [Religious] | {'train': 256} | {'train': 120.0} | +| [BigPatentClustering.v2](https://huggingface.co/datasets/NortheasternUniversity/big_patent) (Eva Sharma and Chen Li and Lu Wang, 2019) | ['eng'] | Clustering | p2p | [Legal] | {'test': 2048} | {'test': 30995.5} | +| [BiorxivClusteringP2P.v2](https://api.biorxiv.org/) | ['eng'] | Clustering | p2p | [Academic] | {'test': 2048} | {'test': 1664.0} | +| [BiorxivClusteringS2S.v2](https://api.biorxiv.org/) | ['eng'] | Clustering | s2s | [Academic] | {'test': 2048} | {'test': 101.7} | +| [BlurbsClusteringP2P.v2](https://www.inf.uni-hamburg.de/en/inst/ab/lt/resources/data/germeval-2019-hmc.html) (Steffen Remus, 2019) | ['deu'] | Clustering | p2p | [Fiction] | {'test': 2048} | {'test': 664.09} | +| [BlurbsClusteringS2S.v2](https://www.inf.uni-hamburg.de/en/inst/ab/lt/resources/data/germeval-2019-hmc.html) (Steffen Remus, 2019) | ['deu'] | Clustering | s2s | [Fiction] | {'test': 2048} | {'test': 23.02} | +| [BornholmBitextMining](https://aclanthology.org/W19-6138/) | ['dan'] | BitextMining | s2s | [Web, Social, Fiction] | {'test': 500} | {'test': 89.7} | +| [BrazilianToxicTweetsClassification](https://paperswithcode.com/dataset/told-br) (Joao Augusto Leite and Diego F. Silva and Kalina Bontcheva and Carolina Scarton, 2020) | ['por'] | MultilabelClassification | s2s | [Constructed] | {'test': 2048} | {'test': 85.05} | +| [BulgarianStoreReviewSentimentClassfication](https://doi.org/10.7910/DVN/TXIK9P) (Georgieva-Trifonova et al., 2018) | ['bul'] | Classification | s2s | [Reviews] | {'test': 182} | {'test': 316.7} | +| [CBD](http://2019.poleval.pl/files/poleval2019.pdf) | ['pol'] | Classification | s2s | | {'test': 1000} | {'test': 93.2} | +| [CDSC-E](https://aclanthology.org/P17-1073.pdf) | ['pol'] | PairClassification | s2s | | | | +| [CDSC-R](https://aclanthology.org/P17-1073.pdf) | ['pol'] | STS | s2s | [Web] | {'test': 1000} | {'test': 75.24} | +| [CLSClusteringP2P.v2](https://arxiv.org/abs/2209.05034) (Yudong Li, 2022) | ['cmn'] | Clustering | p2p | [Academic] | {'test': 2048} | | +| [CLSClusteringS2S.v2](https://arxiv.org/abs/2209.05034) (Yudong Li, 2022) | ['cmn'] | Clustering | s2s | [Academic] | {'test': 2048} | | +| [CMedQAv1-reranking](https://github.com/zhangsheng93/cMedQA) | ['cmn'] | Reranking | s2s | | | | +| [CMedQAv2-reranking](https://github.com/zhangsheng93/cMedQA2) | ['cmn'] | Reranking | s2s | | | | +| [CQADupstackAndroidRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackEnglishRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackGamingRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackGisRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackMathematicaRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackPhysicsRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackProgrammersRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackStatsRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackTexRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackUnixRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackWebmastersRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CQADupstackWordpressRetrieval](http://nlp.cis.unimelb.edu.au/resources/cqadupstack/) | ['eng'] | Retrieval | s2p | | | | +| [CSFDCZMovieReviewSentimentClassification](https://arxiv.org/abs/2304.01922) (Michal Štefánik, 2023) | ['ces'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 386.5} | +| [CSFDSKMovieReviewSentimentClassification](https://arxiv.org/abs/2304.01922) (Michal Štefánik, 2023) | ['slk'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 366.2} | +| [CTKFactsNLI](https://arxiv.org/abs/2201.11115) (Ullrich et al., 2023) | ['ces'] | PairClassification | s2s | [News] | {'test': 375, 'validation': 305} | {'test': 225.62, 'validation': 219.32} | +| [CUADAffiliateLicenseLicenseeLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 198} | {'test': 484.11} | +| [CUADAffiliateLicenseLicensorLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 88} | {'test': 633.4} | +| [CUADAntiAssignmentLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1172} | {'test': 340.81} | +| [CUADAuditRightsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1216} | {'test': 337.14} | +| [CUADCapOnLiabilityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1246} | {'test': 375.74} | +| [CUADChangeOfControlLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 416} | {'test': 391.96} | +| [CUADCompetitiveRestrictionExceptionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 220} | {'test': 433.04} | +| [CUADCovenantNotToSueLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 308} | {'test': 402.97} | +| [CUADEffectiveDateLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 236} | {'test': 277.62} | +| [CUADExclusivityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 762} | {'test': 369.17} | +| [CUADExpirationDateLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 876} | {'test': 309.27} | +| [CUADGoverningLawLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 876} | {'test': 289.87} | +| [CUADIPOwnershipAssignmentLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 576} | {'test': 414.0} | +| [CUADInsuranceLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1030} | {'test': 365.54} | +| [CUADIrrevocableOrPerpetualLicenseLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 280} | {'test': 473.4} | +| [CUADJointIPOwnershipLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 192} | {'test': 374.17} | +| [CUADLicenseGrantLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1396} | {'test': 409.89} | +| [CUADLiquidatedDamagesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 220} | {'test': 351.76} | +| [CUADMinimumCommitmentLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 772} | {'test': 364.16} | +| [CUADMostFavoredNationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 64} | {'test': 418.75} | +| [CUADNoSolicitOfCustomersLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 84} | {'test': 392.89} | +| [CUADNoSolicitOfEmployeesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 142} | {'test': 417.94} | +| [CUADNonCompeteLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 442} | {'test': 383.2} | +| [CUADNonDisparagementLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 100} | {'test': 403.08} | +| [CUADNonTransferableLicenseLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 542} | {'test': 399.16} | +| [CUADNoticePeriodToTerminateRenewalLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 222} | {'test': 354.85} | +| [CUADPostTerminationServicesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 808} | {'test': 422.53} | +| [CUADPriceRestrictionsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 46} | {'test': 324.71} | +| [CUADRenewalTermLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 386} | {'test': 340.87} | +| [CUADRevenueProfitSharingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 774} | {'test': 371.55} | +| [CUADRofrRofoRofnLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 690} | {'test': 395.46} | +| [CUADSourceCodeEscrowLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 118} | {'test': 399.18} | +| [CUADTerminationForConvenienceLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 430} | {'test': 326.3} | +| [CUADThirdPartyBeneficiaryLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 68} | {'test': 261.04} | +| [CUADUncappedLiabilityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 294} | {'test': 441.04} | +| [CUADUnlimitedAllYouCanEatLicenseLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 48} | {'test': 368.08} | +| [CUADVolumeRestrictionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 322} | {'test': 306.27} | +| [CUADWarrantyDurationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 320} | {'test': 352.27} | +| [CanadaTaxCourtOutcomesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 244} | {'test': 622.6} | +| [CataloniaTweetClassification](https://aclanthology.org/2020.lrec-1.171/) | ['cat', 'spa'] | Classification | s2s | [Social, Government] | {'validation': 2000, 'test': 2000} | {'validation': 202.61, 'test': 200.49} | +| [ClimateFEVER](https://www.sustainablefinance.uzh.ch/en/research/climate-fever.html) | ['eng'] | Retrieval | s2p | | | | +| [CmedqaRetrieval](https://aclanthology.org/2022.emnlp-main.357.pdf) | ['cmn'] | Retrieval | s2p | | | | +| [Cmnli](https://huggingface.co/datasets/clue/viewer/cmnli) | ['cmn'] | PairClassification | s2s | | | | +| [CodeEditSearchRetrieval](https://huggingface.co/datasets/cassanof/CodeEditSearch/viewer) (Niklas Muennighoff, 2023) | ['c', 'c++', 'go', 'java', 'javascript', 'php', 'python', 'ruby', 'rust', 'scala', 'shell', 'swift', 'typescript'] | Retrieval | p2p | [Programming] | {'train': 13000} | {'train': 553.5} | +| [CodeSearchNetRetrieval](https://huggingface.co/datasets/code_search_net/viewer) (Husain et al., 2019) | ['go', 'java', 'javascript', 'php', 'python', 'ruby'] | Retrieval | p2p | [Programming] | {'test': 1000} | {'test': 1196.4609} | +| [ContractNLIConfidentialityOfAgreementLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 82} | {'test': 473.17} | +| [ContractNLIExplicitIdentificationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 109} | {'test': 506.12} | +| [ContractNLIInclusionOfVerballyConveyedInformationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 139} | {'test': 525.75} | +| [ContractNLILimitedUseLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 208} | {'test': 407.51} | +| [ContractNLINoLicensingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 162} | {'test': 419.42} | +| [ContractNLINoticeOnCompelledDisclosureLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 142} | {'test': 503.45} | +| [ContractNLIPermissibleAcquirementOfSimilarInformationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 178} | {'test': 427.4} | +| [ContractNLIPermissibleCopyLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 87} | {'test': 386.84} | +| [ContractNLIPermissibleDevelopmentOfSimilarInformationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 136} | {'test': 396.4} | +| [ContractNLIPermissiblePostAgreementPossessionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 111} | {'test': 529.09} | +| [ContractNLIReturnOfConfidentialInformationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 66} | {'test': 478.29} | +| [ContractNLISharingWithEmployeesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 170} | {'test': 548.63} | +| [ContractNLISharingWithThirdPartiesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 180} | {'test': 517.29} | +| [ContractNLISurvivalOfObligationsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 157} | {'test': 417.64} | +| [Core17InstructionRetrieval](https://arxiv.org/abs/2403.15246) (Orion Weller, 2024) | ['eng'] | InstructionRetrieval | s2p | [News] | {'eng': 39838} | {'eng': 2768.749235474006} | +| [CorporateLobbyingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 490} | {'test': 6039.85} | +| [CovidRetrieval](https://arxiv.org/abs/2203.03367) | ['cmn'] | Retrieval | s2p | | | | +| [CrossLingualSemanticDiscriminationWMT19](https://huggingface.co/datasets/Andrianos/clsd_wmt19_21) | ['deu', 'fra'] | Retrieval | s2s | [News] | {'test': 2946} | {'test': 161.0} | +| [CrossLingualSemanticDiscriminationWMT21](https://huggingface.co/datasets/Andrianos/clsd_wmt19_21) | ['deu', 'fra'] | Retrieval | s2s | [News] | {'test': 1786} | {'test': 159.0} | +| [CyrillicTurkicLangClassification](https://huggingface.co/datasets/tatiana-merz/cyrillic_turkic_langs) (Goldhahn et al., 2012) | ['bak', 'chv', 'kaz', 'kir', 'krc', 'rus', 'sah', 'tat', 'tyv'] | Classification | s2s | [Web] | {'test': 2048} | {'test': 92.22} | +| [CzechProductReviewSentimentClassification](https://aclanthology.org/W13-1609/) | ['ces'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 153.26} | +| [CzechSoMeSentimentClassification](https://aclanthology.org/W13-1609/) | ['ces'] | Classification | s2s | [Reviews] | {'test': 1000} | {'test': 59.89} | +| [CzechSubjectivityClassification](https://arxiv.org/abs/2009.08712) | ['ces'] | Classification | s2s | [Reviews] | {'validation': 500, 'test': 2000} | {'validation': 108.2, 'test': 108.3} | +| [DBPedia](https://github.com/iai-group/DBpedia-Entity/) | ['eng'] | Retrieval | s2p | | | | +| [DBPedia-PL](https://github.com/iai-group/DBpedia-Entity/) | ['pol'] | Retrieval | s2p | | | | +| [DBpediaClassification](https://arxiv.org/abs/1509.01626) (Zhang et al., 2015) | ['eng'] | Classification | s2s | [Encyclopaedic] | {'test': 70000} | {'test': 281.4} | +| [DKHateClassification](https://aclanthology.org/2020.lrec-1.430/) | ['dan'] | Classification | s2s | [Social] | {'test': 329} | {'test': 104.0} | +| [DalajClassification](https://spraakbanken.gu.se/en/resources/superlim) | ['swe'] | Classification | s2s | [Non-fiction] | {'test': 444} | {'test': 243.8} | +| [DanFEVER](https://aclanthology.org/2021.nodalida-main.47/) | ['dan'] | Retrieval | p2p | [Encyclopaedic, Non-fiction] | {'train': 8897} | {'train': 124.84} | +| [DanishPoliticalCommentsClassification](https://huggingface.co/datasets/danish_political_comments) | ['dan'] | Classification | s2s | [Social] | {'train': 9010} | {'train': 69.9} | +| [DefinitionClassificationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1337} | {'test': 253.72} | +| [DiaBlaBitextMining](https://inria.hal.science/hal-03021633) (González et al., 2019) | ['eng', 'fra'] | BitextMining | s2s | [Social] | | | +| [Diversity1LegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 300} | {'test': 103.21} | +| [Diversity2LegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 300} | {'test': 0.0} | +| [Diversity3LegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 300} | {'test': 135.46} | +| [Diversity4LegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 300} | {'test': 144.52} | +| [Diversity5LegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 300} | {'test': 174.77} | +| [Diversity6LegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 300} | {'test': 301.01} | +| [DuRetrieval](https://aclanthology.org/2022.emnlp-main.357.pdf) | ['cmn'] | Retrieval | s2p | | | | +| [DutchBookReviewSentimentClassification](https://github.com/benjaminvdb/DBRD) (Benjamin et al., 2019) | ['nld'] | Classification | s2s | [Reviews] | {'test': 2224} | {'test': 1443.0} | +| [EcomRetrieval](https://arxiv.org/abs/2203.03367) | ['cmn'] | Retrieval | s2p | | | | +| [EightTagsClustering.v2](https://aclanthology.org/2020.lrec-1.207.pdf) | ['pol'] | Clustering | s2s | [Social] | {'test': 2048} | {'test': 78.73} | +| [EmotionClassification](https://www.aclweb.org/anthology/D18-1404) | ['eng'] | Classification | s2s | [Social] | {'validation': 2000, 'test': 2000} | {'validation': 95.3, 'test': 95.6} | +| [EstQA](https://www.semanticscholar.org/paper/Extractive-Question-Answering-for-Estonian-Language-182912IAPM-Alum%C3%A4e/ea4f60ab36cadca059c880678bc4c51e293a85d6?utm_source=direct_link) | ['est'] | Retrieval | s2p | [Encyclopaedic] | {'test': 603} | {'test': 772.5331950207469} | +| [EstonianValenceClassification](https://figshare.com/articles/dataset/Estonian_Valence_Corpus_Eesti_valentsikorpus/24517054) | ['est'] | Classification | s2s | [News] | {'train': 3270, 'test': 818} | {'train': 226.70642201834863, 'test': 231.5085574572127} | +| [FEVER](https://fever.ai/) | ['eng'] | Retrieval | s2p | | | | +| [FQuADRetrieval](https://huggingface.co/datasets/manu/fquad2_test) | ['fra'] | Retrieval | s2p | [Encyclopaedic] | {'test': 400, 'validation': 100} | {'test': 937.0, 'validation': 930.0} | +| [FalseFriendsGermanEnglish](https://drive.google.com/file/d/1jgq0nBnV-UiYNxbKNrrr2gxDEHm-DMKH/view?usp=share_link) | ['deu'] | PairClassification | s2s | | {'test': 1524} | {'test': 40.3} | +| [FaroeseSTS](https://aclanthology.org/2023.nodalida-1.74.pdf) | ['fao'] | STS | s2s | [News, Web] | {'train': 729} | {'train': 43.6} | +| [FarsTail](https://link.springer.com/article/10.1007/s00500-023-08959-3) (Amirkhani et al., 2023) | ['fas'] | PairClassification | s2s | [Academic] | {'test': 1029} | {'test': 125.84} | +| [FiQA-PL](https://sites.google.com/view/fiqa/) | ['pol'] | Retrieval | s2p | | | | +| [FiQA2018](https://sites.google.com/view/fiqa/) | ['eng'] | Retrieval | s2p | | | | +| [FilipinoHateSpeechClassification](https://pcj.csp.org.ph/index.php/pcj/issue/download/29/PCJ%20V14%20N1%20pp1-14%202019) (Neil Vicente Cabasag et al., 2019) | ['fil'] | Classification | s2s | [Social] | {'validation': 2048, 'test': 2048} | {'validation': 88.1, 'test': 87.4} | +| [FilipinoShopeeReviewsClassification](https://uijrt.com/articles/v4/i8/UIJRTV4I80009.pdf) | ['fil'] | Classification | s2s | [Social] | {'validation': 2250, 'test': 2250} | {'validation': 143.8, 'test': 145.1} | +| [FinParaSTS](https://huggingface.co/datasets/TurkuNLP/turku_paraphrase_corpus) | ['fin'] | STS | s2s | [News, Subtitles] | {'test': 1000, 'validation': 1000} | {'test': 59.0, 'validation': 58.8} | +| [FinToxicityClassification](https://aclanthology.org/2023.nodalida-1.68) | ['fin'] | Classification | s2s | [News] | {'train': 2048, 'test': 2048} | {'train': 432.63, 'test': 401.03} | +| [FinancialPhrasebankClassification](https://arxiv.org/abs/1307.5336) (P. Malo, 2014) | ['eng'] | Classification | s2s | [News] | {'train': 4840} | {'train': 121.96} | +| [FloresBitextMining](https://huggingface.co/datasets/facebook/flores) (Goyal et al., 2022) | ['ace', 'acm', 'acq', 'aeb', 'afr', 'ajp', 'aka', 'als', 'amh', 'apc', 'arb', 'ars', 'ary', 'arz', 'asm', 'ast', 'awa', 'ayr', 'azb', 'azj', 'bak', 'bam', 'ban', 'bel', 'bem', 'ben', 'bho', 'bjn', 'bod', 'bos', 'bug', 'bul', 'cat', 'ceb', 'ces', 'cjk', 'ckb', 'crh', 'cym', 'dan', 'deu', 'dik', 'dyu', 'dzo', 'ell', 'eng', 'epo', 'est', 'eus', 'ewe', 'fao', 'fij', 'fin', 'fon', 'fra', 'fur', 'fuv', 'gaz', 'gla', 'gle', 'glg', 'grn', 'guj', 'hat', 'hau', 'heb', 'hin', 'hne', 'hrv', 'hun', 'hye', 'ibo', 'ilo', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kab', 'kac', 'kam', 'kan', 'kas', 'kat', 'kaz', 'kbp', 'kea', 'khk', 'khm', 'kik', 'kin', 'kir', 'kmb', 'kmr', 'knc', 'kon', 'kor', 'lao', 'lij', 'lim', 'lin', 'lit', 'lmo', 'ltg', 'ltz', 'lua', 'lug', 'luo', 'lus', 'lvs', 'mag', 'mai', 'mal', 'mar', 'min', 'mkd', 'mlt', 'mni', 'mos', 'mri', 'mya', 'nld', 'nno', 'nob', 'npi', 'nso', 'nus', 'nya', 'oci', 'ory', 'pag', 'pan', 'pap', 'pbt', 'pes', 'plt', 'pol', 'por', 'prs', 'quy', 'ron', 'run', 'rus', 'sag', 'san', 'sat', 'scn', 'shn', 'sin', 'slk', 'slv', 'smo', 'sna', 'snd', 'som', 'sot', 'spa', 'srd', 'srp', 'ssw', 'sun', 'swe', 'swh', 'szl', 'tam', 'taq', 'tat', 'tel', 'tgk', 'tgl', 'tha', 'tir', 'tpi', 'tsn', 'tso', 'tuk', 'tum', 'tur', 'twi', 'tzm', 'uig', 'ukr', 'umb', 'urd', 'uzn', 'vec', 'vie', 'war', 'wol', 'xho', 'ydd', 'yor', 'yue', 'zho', 'zsm', 'zul'] | BitextMining | s2s | [Non-fiction, Encyclopaedic] | {'dev': 997, 'devtest': 1012} | | +| [FrenchBookReviews](https://huggingface.co/datasets/Abirate/french_book_reviews) | ['fra'] | Classification | s2s | [Reviews] | {'train': 2048} | {'train': 311.5} | +| [FrenkEnClassification](https://arxiv.org/abs/1906.02045) (Nikola Ljubešić, 2019) | ['eng'] | Classification | s2s | [Social] | {'test': 2300} | {'test': 188.75} | +| [FrenkHrClassification](https://arxiv.org/abs/1906.02045) (Nikola Ljubešić, 2019) | ['hrv'] | Classification | s2s | [Social] | {'test': 2120} | {'test': 89.86} | +| [FrenkSlClassification](https://arxiv.org/pdf/1906.02045) (Nikola Ljubešić, 2019) | ['slv'] | Classification | s2s | [Social] | {'test': 2177} | {'test': 136.61} | +| [FunctionOfDecisionSectionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 367} | {'test': 551.07} | +| [GeorgianFAQRetrieval](https://huggingface.co/datasets/jupyterjazz/georgian-faq) | ['kat'] | Retrieval | s2p | [Web] | {'test': 2566} | {'test': 572.0} | +| [GerDaLIR](https://github.com/lavis-nlp/GerDaLIR) | ['deu'] | Retrieval | s2p | | | | +| [GerDaLIRSmall](https://github.com/lavis-nlp/GerDaLIR) | ['deu'] | Retrieval | p2p | [Legal] | | | +| [GermanDPR](https://huggingface.co/datasets/deepset/germandpr) | ['deu'] | Retrieval | s2p | | | | +| [GermanGovServiceRetrieval](https://huggingface.co/datasets/it-at-m/LHM-Dienstleistungen-QA) | ['deu'] | Retrieval | s2p | [Government] | {'test': 357} | {'test': 1211.69} | +| [GermanPoliticiansTwitterSentimentClassification](https://aclanthology.org/2022.konvens-1.9) | ['deu'] | Classification | s2s | [Social, Government] | {'test': 357} | {'test': 302.48} | +| [GermanQuAD-Retrieval](https://www.kaggle.com/datasets/GermanQuAD) | ['deu'] | Retrieval | s2p | | | | +| [GermanSTSBenchmark](https://github.com/t-systems-on-site-services-gmbh/german-STSbenchmark) | ['deu'] | STS | s2s | | | | +| [GreekCivicsQA](https://huggingface.co/datasets/antoinelb7/alloprof) | ['ell'] | Retrieval | s2p | [Academic] | {'default': 407} | {'default': 2226.85} | +| [GreekLegalCodeClassification](https://arxiv.org/abs/2109.15298) | ['ell'] | Classification | s2s | [Legal] | {'validation': 2048, 'test': 2048} | {'validation': 4046.8, 'test': 4200.8} | +| [GujaratiNewsClassification](https://github.com/goru001/nlp-for-gujarati) | ['guj'] | Classification | s2s | [News] | {'train': 5269, 'test': 1318} | {'train': 61.95, 'test': 61.91} | +| [HALClusteringS2S.v2](https://huggingface.co/datasets/lyon-nlp/clustering-hal-s2s) | ['fra'] | Clustering | s2s | [Academic] | {'test': 2048} | {'test': 86.6} | +| [HagridRetrieval](https://github.com/project-miracl/hagrid) | ['eng'] | Retrieval | s2p | | | | +| [HateSpeechPortugueseClassification](https://aclanthology.org/W19-3510) | ['por'] | Classification | s2s | [Social] | {'train': 2048} | {'train': 101.02} | +| [HebrewSentimentAnalysis](https://huggingface.co/datasets/hebrew_sentiment) | ['heb'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 113.57} | +| [HinDialectClassification](https://lindat.mff.cuni.cz/repository/xmlui/handle/11234/1-4839) (Bafna et al., 2022) | ['anp', 'awa', 'ben', 'bgc', 'bhb', 'bhd', 'bho', 'bjj', 'bns', 'bra', 'gbm', 'guj', 'hne', 'kfg', 'kfy', 'mag', 'mar', 'mup', 'noe', 'pan', 'raj'] | Classification | s2s | [Social, Spoken] | {'test': 1152} | {'test': 583.82} | +| [HindiDiscourseClassification](https://aclanthology.org/2020.lrec-1.149/) | ['hin'] | Classification | s2s | [Fiction, Social] | {'train': 2048} | {'train': 79.23828125} | +| [HotelReviewSentimentClassification](https://link.springer.com/chapter/10.1007/978-3-319-67056-0_3) (Elnagar et al., 2018) | ['ara'] | Classification | s2s | [Reviews] | {'train': 2048} | {'train': 137.2} | +| [HotpotQA](https://hotpotqa.github.io/) | ['eng'] | Retrieval | s2p | | | | +| [HotpotQA-PL](https://hotpotqa.github.io/) | ['pol'] | Retrieval | s2p | | | | +| [HunSum2AbstractiveRetrieval](https://arxiv.org/abs/2404.03555) (Botond Barta, 2024) | ['hun'] | Retrieval | s2p | [News] | {'test': 1998} | {'test': 2462.2177177177177} | +| [IFlyTek](https://www.cluebenchmarks.com/introduce.html) | ['cmn'] | Classification | s2s | | | | +| [IN22ConvBitextMining](https://huggingface.co/datasets/ai4bharat/IN22-Conv) (Jay Gala, 2023) | ['asm', 'ben', 'brx', 'doi', 'eng', 'gom', 'guj', 'hin', 'kan', 'kas', 'mai', 'mal', 'mar', 'mni', 'npi', 'ory', 'pan', 'san', 'sat', 'snd', 'tam', 'tel', 'urd'] | BitextMining | s2s | [Social, Spoken, Fiction] | {'test': 1503} | {'test': 54.3} | +| [IN22GenBitextMining](https://huggingface.co/datasets/ai4bharat/IN22-Gen) (Jay Gala, 2023) | ['asm', 'ben', 'brx', 'doi', 'eng', 'gom', 'guj', 'hin', 'kan', 'kas', 'mai', 'mal', 'mar', 'mni', 'npi', 'ory', 'pan', 'san', 'sat', 'snd', 'tam', 'tel', 'urd'] | BitextMining | s2s | [Web, Legal, Government, News, Religious, Non-fiction] | {'test': 1024} | {'test': 156.7} | +| [IWSLT2017BitextMining](https://aclanthology.org/2017.iwslt-1.1/) | ['ara', 'cmn', 'deu', 'eng', 'fra', 'ita', 'jpn', 'kor', 'nld', 'ron'] | BitextMining | s2s | [Non-fiction, Fiction] | {'validation': 21928} | {'validation': 95.4} | +| [ImdbClassification](http://www.aclweb.org/anthology/P11-1015) | ['eng'] | Classification | p2p | [Reviews] | {'test': 25000} | {'test': 1293.8} | +| [IndicCrosslingualSTS](https://huggingface.co/datasets/jaygala24/indic_sts) (Ramesh et al., 2022) | ['asm', 'ben', 'eng', 'guj', 'hin', 'kan', 'mal', 'mar', 'ory', 'pan', 'tam', 'tel', 'urd'] | STS | s2s | [News, Non-fiction, Web, Spoken, Government] | {'test': 10020} | {'test': 76.22} | +| [IndicGenBenchFloresBitextMining](https://github.com/google-research-datasets/indic-gen-bench/) (Harman Singh, 2024) | ['asm', 'awa', 'ben', 'bgc', 'bho', 'bod', 'boy', 'eng', 'gbm', 'gom', 'guj', 'hin', 'hne', 'kan', 'mai', 'mal', 'mar', 'mni', 'mup', 'mwr', 'nep', 'ory', 'pan', 'pus', 'raj', 'san', 'sat', 'tam', 'tel', 'urd'] | BitextMining | s2s | [Web, News] | {'validation': 997, 'test': 1012} | {'validation': 126.25, 'test': 130.84} | +| [IndicLangClassification](https://arxiv.org/abs/2305.15814) | ['asm', 'ben', 'brx', 'doi', 'gom', 'guj', 'hin', 'kan', 'kas', 'mai', 'mal', 'mar', 'mni', 'npi', 'ory', 'pan', 'san', 'sat', 'snd', 'tam', 'tel', 'urd'] | Classification | s2s | [Web, Non-fiction] | {'test': 30418} | {'test': 106.5} | +| [IndicNLPNewsClassification](https://github.com/AI4Bharat/indicnlp_corpus#indicnlp-news-article-classification-dataset) (Anoop Kunchukuttan, 2020) | ['guj', 'kan', 'mal', 'mar', 'ori', 'pan', 'tam', 'tel'] | Classification | s2s | [News] | {'test': 2048} | {'test': 1169.053974484789} | +| [IndicQARetrieval](https://arxiv.org/abs/2212.05409) (Sumanth Doddapaneni, 2022) | ['asm', 'ben', 'guj', 'hin', 'kan', 'mal', 'mar', 'ory', 'pan', 'tam', 'tel'] | Retrieval | s2p | [Web] | {'test': 18586} | {'test': 930.6} | +| [IndicReviewsClusteringP2P](https://arxiv.org/abs/2212.05409) (Sumanth Doddapaneni, 2022) | ['asm', 'ben', 'brx', 'guj', 'hin', 'kan', 'mal', 'mar', 'ory', 'pan', 'tam', 'tel', 'urd'] | Clustering | p2p | [Reviews] | {'test': 1000} | {'test': 137.6} | +| [IndicSentimentClassification](https://arxiv.org/abs/2212.05409) (Sumanth Doddapaneni, 2022) | ['asm', 'ben', 'brx', 'guj', 'hin', 'kan', 'mal', 'mar', 'ory', 'pan', 'tam', 'tel', 'urd'] | Classification | s2s | [Reviews] | {'test': 1000} | {'test': 137.6} | +| [IndonesianIdClickbaitClassification](http://www.sciencedirect.com/science/article/pii/S2352340920311252) | ['ind'] | Classification | s2s | [News] | {'train': 2048} | {'train': 64.28} | +| [IndonesianMongabayConservationClassification](https://aclanthology.org/2023.sealp-1.4/) | ['ind'] | Classification | s2s | [Web] | {'validation': 984, 'test': 970} | {'validation': 1675.8, 'test': 1675.5} | +| [InsurancePolicyInterpretationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 133} | {'test': 521.88} | +| [InternationalCitizenshipQuestionsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 206.18} | +| [IsiZuluNewsClassification](https://huggingface.co/datasets/dsfsi/za-isizulu-siswati-news) (Madodonga et al., 2023) | ['zul'] | Classification | s2s | [News] | {'train': 752} | {'train': 43.1} | +| [ItaCaseholdClassification](https://doi.org/10.1145/3594536.3595177) (Licari et al., 2023) | ['ita'] | Classification | s2s | [Legal, Government] | {'test': 221} | {'test': 4207.9} | +| [Itacola](https://aclanthology.org/2021.findings-emnlp.250/) | ['ita'] | Classification | s2s | [Non-fiction, Spoken] | {'train': 7801, 'test': 975} | {'train': 35.95, 'test': 36.67} | +| [JCrewBlockerLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 54} | {'test': 1092.22} | +| [JDReview](https://aclanthology.org/2023.nodalida-1.20/) | ['cmn'] | Classification | s2s | | | | +| [JSICK](https://github.com/sbintuitions/JMTEB) (Yanaka et al., 2022) | ['jpn'] | STS | s2s | [Web] | {'test': 1986} | {'test': 21.47} | +| [JSTS](https://aclanthology.org/2022.lrec-1.317.pdf#page=2.00) | ['jpn'] | STS | s2s | [Web] | {'valudtion': 1457} | {'valudtion': 46.34} | +| [JaQuADRetrieval](https://arxiv.org/abs/2202.01764) (ByungHoon So, 2022) | ['jpn'] | Retrieval | p2p | [Encyclopaedic, Non-fiction] | {'validation': 2048} | {'validation': 400.75} | +| [JavaneseIMDBClassification](https://github.com/w11wo/nlp-datasets#javanese-imdb) (Wongso et al., 2021) | ['jav'] | Classification | s2s | [Reviews] | {'test': 25000} | {'test': 481.83} | +| [KLUE-NLI](https://arxiv.org/abs/2105.09680) (Sungjoon Park, 2021) | ['kor'] | PairClassification | s2s | [News, Encyclopaedic] | {'validation': 2000} | {'validation': 35.01} | +| [KLUE-STS](https://arxiv.org/abs/2105.09680) (Sungjoon Park, 2021) | ['kor'] | STS | s2s | [Reviews, News, Spoken] | {'validation': 519} | {'validation': 33.178227360308284} | +| [KLUE-TC](https://arxiv.org/abs/2105.09680) (Sungjoon Park, 2021) | ['kor'] | Classification | s2s | [News] | {'validation': 2048} | {'validation': 27.079609091907326} | +| [KannadaNewsClassification](https://github.com/goru001/nlp-for-kannada) | ['kan'] | Classification | s2s | [News] | {'train': 6460} | {'train': 65.88} | +| Ko-StrategyQA | ['kor'] | Retrieval | s2p | | | | +| Ko-miracl | ['kor'] | Retrieval | s2p | | | | +| [KorFin](https://huggingface.co/datasets/amphora/korfin-asc) (Son et al., 2023) | ['kor'] | Classification | s2s | [News] | {'test': 2048} | {'test': 75.28} | +| [KorHateClassification](https://paperswithcode.com/dataset/korean-hatespeech-dataset) (Jihyung Moon, 2020) | ['kor'] | Classification | s2s | [Social] | {'train': 2048, 'test': 471} | {'train': 38.57, 'test': 38.86} | +| [KorSTS](https://arxiv.org/abs/2004.03289) (Ham et al., 2020) | ['kor'] | STS | s2s | [News, Web] | {'test': 1379} | {'test': 29.279433139534884} | +| [KorSarcasmClassification](https://github.com/SpellOnYou/korean-sarcasm) (Kim et al., 2019) | ['kor'] | Classification | s2s | [Social] | {'train': 2048, 'test': 301} | {'train': 48.45, 'test': 46.77} | +| [KurdishSentimentClassification](https://link.springer.com/article/10.1007/s10579-023-09716-6) (Badawi et al., 2024) | ['kur'] | Classification | s2s | [Web] | {'train': 6000, 'test': 1987} | {'train': 59.38, 'test': 56.11} | +| [LCQMC](https://aclanthology.org/2021.emnlp-main.357) | ['cmn'] | STS | s2s | | | | +| [LEMBNarrativeQARetrieval](https://huggingface.co/datasets/dwzhu/LongEmbed) | ['eng'] | Retrieval | s2p | [Fiction, Non-fiction] | {'test': 10804} | {'test': 326399.3} | +| [LEMBNeedleRetrieval](https://huggingface.co/datasets/dwzhu/LongEmbed) (Zhu et al., 2024) | ['eng'] | Retrieval | s2p | [Academic, Blog] | {'test_256': 150, 'test_512': 150, 'test_1024': 150, 'test_2048': 150, 'test_4096': 150, 'test_8192': 150, 'test_16384': 150, 'test_32768': 150} | {'test_256': 1074.4, 'test_512': 2067.0, 'test_1024': 4129.5, 'test_2048': 8513.4, 'test_4096': 17452.7, 'test_8192': 35261.6, 'test_16384': 72113.7, 'test_32768': 141829.0} | +| [LEMBPasskeyRetrieval](https://huggingface.co/datasets/dwzhu/LongEmbed) (Zhu et al., 2024) | ['eng'] | Retrieval | s2p | [Fiction] | {'test_256': 150, 'test_512': 150, 'test_1024': 150, 'test_2048': 150, 'test_4096': 150, 'test_8192': 150, 'test_16384': 150, 'test_32768': 150} | {'test_256': 914.9, 'test_512': 1823.0, 'test_1024': 3644.7, 'test_2048': 7280.0, 'test_4096': 14555.5, 'test_8192': 29108.1, 'test_16384': 58213.9, 'test_32768': 116417.9} | +| [LEMBQMSumRetrieval](https://huggingface.co/datasets/dwzhu/LongEmbed) | ['eng'] | Retrieval | s2p | [Spoken] | {'test': 1724} | {'test': 56136.4} | +| [LEMBSummScreenFDRetrieval](https://huggingface.co/datasets/dwzhu/LongEmbed) | ['eng'] | Retrieval | s2p | [Spoken] | {'validation': 672} | {'validation': 31445.8} | +| [LEMBWikimQARetrieval](https://huggingface.co/datasets/dwzhu/LongEmbed) (Ho et al., 2020) | ['eng'] | Retrieval | s2p | [Encyclopaedic] | {'test': 500} | {'test': 37513.0} | +| [LanguageClassification](https://huggingface.co/datasets/papluca/language-identification) | ['ara', 'bul', 'cmn', 'deu', 'ell', 'eng', 'fra', 'hin', 'ita', 'jpn', 'nld', 'pol', 'por', 'rus', 'spa', 'swa', 'tha', 'tur', 'urd', 'vie'] | Classification | s2s | [Reviews, Web, Non-fiction, Fiction, Government] | {'test': 2048} | {'test': 107.8} | +| [LccSentimentClassification](https://github.com/fnielsen/lcc-sentiment) | ['dan'] | Classification | s2s | [News, Web] | {'test': 150} | {'test': 118.7} | +| [LeCaRDv2](https://github.com/THUIR/LeCaRDv2) | ['zho'] | Retrieval | p2p | [Legal] | | | +| [LearnedHandsBenefitsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 66} | {'test': 1308.44} | +| [LearnedHandsBusinessLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 174} | {'test': 1144.51} | +| [LearnedHandsConsumerLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 614} | {'test': 1277.45} | +| [LearnedHandsCourtsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 192} | {'test': 1171.02} | +| [LearnedHandsCrimeLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 688} | {'test': 1212.9} | +| [LearnedHandsDivorceLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 150} | {'test': 1242.43} | +| [LearnedHandsDomesticViolenceLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 174} | {'test': 1360.83} | +| [LearnedHandsEducationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 56} | {'test': 1397.44} | +| [LearnedHandsEmploymentLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 710} | {'test': 1262.74} | +| [LearnedHandsEstatesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 178} | {'test': 1200.7} | +| [LearnedHandsFamilyLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 1338.27} | +| [LearnedHandsHealthLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 226} | {'test': 1472.59} | +| [LearnedHandsHousingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 1322.54} | +| [LearnedHandsImmigrationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 134} | {'test': 1216.31} | +| [LearnedHandsTortsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 432} | {'test': 1406.97} | +| [LearnedHandsTrafficLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 556} | {'test': 1182.91} | +| [LegalBenchConsumerContractsQA](https://huggingface.co/datasets/nguha/legalbench/viewer/consumer_contracts_qa) | ['eng'] | Retrieval | s2p | [Legal] | | | +| [LegalBenchCorporateLobbying](https://huggingface.co/datasets/nguha/legalbench/viewer/corporate_lobbying) | ['eng'] | Retrieval | s2p | [Legal] | | | +| [LegalBenchPC](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | PairClassification | s2s | [Legal] | {'test': 2048} | {'test': 287.18} | +| [LegalQuAD](https://github.com/Christoph911/AIKE2021_Appendix) | ['deu'] | Retrieval | s2p | [Legal] | | | +| [LegalReasoningCausalityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 55} | {'test': 1563.76} | +| [LegalSummarization](https://github.com/lauramanor/legal_summarization) | ['eng'] | Retrieval | s2p | [Legal] | | | +| [LivedoorNewsClustering](https://github.com/sbintuitions/JMTEB) | ['jpn'] | Clustering | s2s | [News] | {'test': 1107} | {'test': 1082.61} | +| [MAUDLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 1802.93} | +| [MIRACLReranking](https://project-miracl.github.io/) | ['deu', 'spa'] | Reranking | s2s | | | | +| MIRACLRetrieval | ['deu', 'spa'] | Retrieval | s2p | | | | +| [MLQARetrieval](https://huggingface.co/datasets/mlqa) | ['ara', 'deu', 'eng', 'hin', 'spa', 'vie', 'zho'] | Retrieval | s2p | [Encyclopaedic] | {'test': 158083, 'validation': 15747} | {'test': 37352.28, 'validation': 36952.7} | +| [MLQuestions](https://github.com/McGill-NLP/MLQuestions) | ['eng'] | Retrieval | s2p | [Encyclopaedic, Academic] | {'dev': 1500, 'test': 1500} | {'dev': 305.0, 'test': 307.0} | +| [MLSUMClusteringP2P](https://huggingface.co/datasets/mlsum) (Scialom et al., 2020) | ['deu', 'fra', 'rus', 'spa'] | Clustering | p2p | [News] | {'validation': 38561, 'test': 41206} | {'validation': 4613.0, 'test': 4810.0} | +| [MLSUMClusteringS2S](https://huggingface.co/datasets/mlsum) (Scialom et al., 2020) | ['deu', 'fra', 'rus', 'spa'] | Clustering | s2s | [News] | {'validation': 38561, 'test': 41206} | {'validation': 4613.0, 'test': 4810.0} | +| [MMarcoReranking](https://github.com/unicamp-dl/mMARCO) | ['cmn'] | Reranking | s2s | | | | +| [MMarcoRetrieval](https://arxiv.org/abs/2309.07597) | ['cmn'] | Retrieval | s2p | | | | +| [MSMARCO](https://microsoft.github.io/msmarco/) | ['eng'] | Retrieval | s2p | | | | +| [MSMARCO-PL](https://microsoft.github.io/msmarco/) | ['pol'] | Retrieval | s2p | | | | +| [MSMARCOv2](https://microsoft.github.io/msmarco/TREC-Deep-Learning.html) | ['eng'] | Retrieval | s2p | | | | +| [MTOPDomainClassification](https://arxiv.org/pdf/2008.09335.pdf) | ['deu', 'eng', 'fra', 'hin', 'spa', 'tha'] | Classification | s2s | | {'validation': 2235, 'test': 4386} | {'validation': 36.5, 'test': 36.8} | +| [MTOPIntentClassification](https://arxiv.org/pdf/2008.09335.pdf) | ['deu', 'eng', 'fra', 'hin', 'spa', 'tha'] | Classification | s2s | | {'validation': 2235, 'test': 4386} | {'validation': 36.5, 'test': 36.8} | +| [MacedonianTweetSentimentClassification](https://aclanthology.org/R15-1034/) | ['mkd'] | Classification | s2s | [Social] | {'test': 1139} | {'test': 67.6} | +| [MalayalamNewsClassification](https://github.com/goru001/nlp-for-malyalam) | ['mal'] | Classification | s2s | [News] | {'train': 5036, 'test': 1260} | {'train': 79.48, 'test': 80.44} | +| [MalteseNewsClassification](https://huggingface.co/datasets/MLRS/maltese_news_categories) | ['mlt'] | MultilabelClassification | s2s | [Constructed] | {'train': 10784, 'test': 2297} | {'train': 1595.63, 'test': 1752.1} | +| [MarathiNewsClassification](https://github.com/goru001/nlp-for-marathi) | ['mar'] | Classification | s2s | [News] | {'test': 2048} | {'test': 52.37} | +| [MasakhaNEWSClassification](https://arxiv.org/abs/2304.09972) | ['amh', 'eng', 'fra', 'hau', 'ibo', 'lin', 'lug', 'orm', 'pcm', 'run', 'sna', 'som', 'swa', 'tir', 'xho', 'yor'] | Classification | s2s | | {'test': 422} | {'test': 5116.6} | +| [MasakhaNEWSClusteringP2P](https://huggingface.co/datasets/masakhane/masakhanews) | ['amh', 'eng', 'fra', 'hau', 'ibo', 'lin', 'lug', 'orm', 'pcm', 'run', 'sna', 'som', 'swa', 'tir', 'xho', 'yor'] | Clustering | p2p | | | | +| [MasakhaNEWSClusteringS2S](https://huggingface.co/datasets/masakhane/masakhanews) | ['amh', 'eng', 'fra', 'hau', 'ibo', 'lin', 'lug', 'orm', 'pcm', 'run', 'sna', 'som', 'swa', 'tir', 'xho', 'yor'] | Clustering | s2s | | | | +| [MassiveIntentClassification](https://arxiv.org/abs/2204.08582#:~:text=MASSIVE%20contains%201M%20realistic%2C%20parallel,diverse%20languages%20from%2029%20genera.) | ['afr', 'amh', 'ara', 'aze', 'ben', 'cmo', 'cym', 'dan', 'deu', 'ell', 'eng', 'fas', 'fin', 'fra', 'heb', 'hin', 'hun', 'hye', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kan', 'kat', 'khm', 'kor', 'lav', 'mal', 'mon', 'msa', 'mya', 'nld', 'nob', 'pol', 'por', 'ron', 'rus', 'slv', 'spa', 'sqi', 'swa', 'swe', 'tam', 'tel', 'tgl', 'tha', 'tur', 'urd', 'vie'] | Classification | s2s | | {'validation': 2033, 'test': 2974} | {'validation': 34.8, 'test': 34.6} | +| [MassiveScenarioClassification](https://arxiv.org/abs/2204.08582#:~:text=MASSIVE%20contains%201M%20realistic%2C%20parallel,diverse%20languages%20from%2029%20genera.) | ['afr', 'amh', 'ara', 'aze', 'ben', 'cmo', 'cym', 'dan', 'deu', 'ell', 'eng', 'fas', 'fin', 'fra', 'heb', 'hin', 'hun', 'hye', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kan', 'kat', 'khm', 'kor', 'lav', 'mal', 'mon', 'msa', 'mya', 'nld', 'nob', 'pol', 'por', 'ron', 'rus', 'slv', 'spa', 'sqi', 'swa', 'swe', 'tam', 'tel', 'tgl', 'tha', 'tur', 'urd', 'vie'] | Classification | s2s | | {'validation': 2033, 'test': 2974} | {'validation': 34.8, 'test': 34.6} | +| [MedicalQARetrieval](https://bmcbioinformatics.biomedcentral.com/articles/10.1186/s12859-019-3119-4) (Asma et al., 2019) | ['eng'] | Retrieval | s2s | [Medical] | {'test': 2048} | {'test': 1205.9619140625} | +| [MedicalRetrieval](https://arxiv.org/abs/2203.03367) | ['cmn'] | Retrieval | s2p | | | | +| [MedrxivClusteringP2P.v2](https://api.medrxiv.org/) | ['eng'] | Clustering | p2p | [Academic, Medical] | {'test': 2048} | {'test': 1984.7} | +| [MedrxivClusteringS2S.v2](https://api.medrxiv.org/) | ['eng'] | Clustering | s2s | [Academic, Medical] | {'test': 2048} | {'test': 114.9} | +| [MewsC16JaClustering](https://github.com/sbintuitions/JMTEB) | ['jpn'] | Clustering | s2s | [News] | {'test': 992} | {'test': 95.0} | +| [MindSmallReranking](https://msnews.github.io/assets/doc/ACL2020_MIND.pdf) | ['eng'] | Reranking | s2s | | {'test': 107968} | {'test': 70.9} | +| MintakaRetrieval | ['ara', 'deu', 'fra', 'hin', 'ita', 'jpn', 'por', 'spa'] | Retrieval | s2p | | | | +| [Moroco](https://huggingface.co/datasets/moroco) (Andrei M. Butnaru, 2019) | ['ron'] | Classification | s2s | [News] | {'test': 2048} | {'test': 1710.94} | +| [MovieReviewSentimentClassification](https://github.com/TheophileBlard/french-sentiment-analysis-with-bert) (Théophile Blard, 2020) | ['fra'] | Classification | s2s | [Reviews] | {'validation': 1024, 'test': 1024} | {'validation': 550.3, 'test': 558.1} | +| [MultiEURLEXMultilabelClassification](https://huggingface.co/datasets/coastalcph/multi_eurlex) (Chalkidis et al., 2021) | ['bul', 'ces', 'dan', 'deu', 'ell', 'eng', 'est', 'fin', 'fra', 'hrv', 'hun', 'ita', 'lav', 'lit', 'mlt', 'nld', 'pol', 'por', 'ron', 'slk', 'slv', 'spa', 'swe'] | MultilabelClassification | p2p | [Legal, Government] | {'test': 5000} | {'test': 12014.41} | +| [MultiHateClassification](https://aclanthology.org/2022.woah-1.15/) | ['ara', 'cmn', 'deu', 'eng', 'fra', 'hin', 'ita', 'nld', 'pol', 'por', 'spa'] | Classification | s2s | [Constructed] | {'test': 10000} | {'test': 45.9} | +| [MultiLongDocRetrieval](https://arxiv.org/abs/2402.03216) (Jianlv Chen, 2024) | ['ara', 'cmn', 'deu', 'eng', 'fra', 'hin', 'ita', 'jpn', 'kor', 'por', 'rus', 'spa', 'tha'] | Retrieval | s2p | | | | +| [MultilingualSentiment](https://github.com/tyqiangz/multilingual-sentiment-datasets) | ['cmn'] | Classification | s2s | | | | +| [MultilingualSentimentClassification](https://huggingface.co/datasets/mteb/multilingual-sentiment-classification) | ['ara', 'bam', 'bul', 'cmn', 'cym', 'deu', 'dza', 'ell', 'eng', 'eus', 'fas', 'fin', 'heb', 'hrv', 'ind', 'jpn', 'kor', 'mlt', 'nor', 'pol', 'rus', 'slk', 'spa', 'tha', 'tur', 'uig', 'urd', 'vie', 'zho'] | Classification | s2s | [Reviews] | {'test': 7000} | {'test': 56.0} | +| [MyanmarNews](https://huggingface.co/datasets/myanmar_news) (A. H. Khine, 2017) | ['mya'] | Classification | p2p | [News] | {'train': 2048} | {'train': 174.2} | +| [NFCorpus](https://www.cl.uni-heidelberg.de/statnlpgroup/nfcorpus/) | ['eng'] | Retrieval | s2p | | | | +| [NFCorpus-PL](https://www.cl.uni-heidelberg.de/statnlpgroup/nfcorpus/) | ['pol'] | Retrieval | s2p | | | | +| [NQ](https://ai.google.com/research/NaturalQuestions/) | ['eng'] | Retrieval | s2p | | | | +| [NQ-PL](https://ai.google.com/research/NaturalQuestions/) | ['pol'] | Retrieval | s2p | | | | +| [NTREXBitextMining](https://huggingface.co/datasets/davidstap/NTREX) | ['afr', 'amh', 'arb', 'aze', 'bak', 'bel', 'bem', 'ben', 'bod', 'bos', 'bul', 'cat', 'ces', 'ckb', 'cym', 'dan', 'deu', 'div', 'dzo', 'ell', 'eng', 'eus', 'ewe', 'fao', 'fas', 'fij', 'fil', 'fin', 'fra', 'fuc', 'gle', 'glg', 'guj', 'hau', 'heb', 'hin', 'hmn', 'hrv', 'hun', 'hye', 'ibo', 'ind', 'isl', 'ita', 'jpn', 'kan', 'kat', 'kaz', 'khm', 'kin', 'kir', 'kmr', 'kor', 'lao', 'lav', 'lit', 'ltz', 'mal', 'mar', 'mey', 'mkd', 'mlg', 'mlt', 'mon', 'mri', 'msa', 'mya', 'nde', 'nep', 'nld', 'nno', 'nob', 'nso', 'nya', 'orm', 'pan', 'pol', 'por', 'prs', 'pus', 'ron', 'rus', 'shi', 'sin', 'slk', 'slv', 'smo', 'sna', 'snd', 'som', 'spa', 'sqi', 'srp', 'ssw', 'swa', 'swe', 'tah', 'tam', 'tat', 'tel', 'tgk', 'tha', 'tir', 'ton', 'tsn', 'tuk', 'tur', 'uig', 'ukr', 'urd', 'uzb', 'ven', 'vie', 'wol', 'xho', 'yor', 'yue', 'zho', 'zul'] | BitextMining | s2s | [News] | {'test': 3826252} | {'test': 120.0} | +| [NYSJudicialEthicsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 292} | {'test': 159.45} | +| [NaijaSenti](https://github.com/hausanlp/NaijaSenti) | ['hau', 'ibo', 'pcm', 'yor'] | Classification | s2s | [Social] | {'test': 4800} | {'test': 72.81} | +| [NarrativeQARetrieval](https://metatext.io/datasets/narrativeqa) | ['eng'] | Retrieval | s2p | | | | +| [NepaliNewsClassification](https://github.com/goru001/nlp-for-nepali) | ['nep'] | Classification | s2s | [News] | {'train': 5975, 'test': 1495} | {'train': 196.61, 'test': 196.017} | +| [NeuCLIR2022Retrieval](https://neuclir.github.io/) (Lawrie et al., 2023) | ['fas', 'rus', 'zho'] | Retrieval | s2p | [News] | {'fas': 2232130, 'zho': 3179323, 'rus': 4627657} | {'fas': 3500.5143969099317, 'zho': 2543.1140667919617, 'rus': 3214.755239654659} | +| [NeuCLIR2023Retrieval](https://neuclir.github.io/) (Dawn Lawrie, 2024) | ['fas', 'rus', 'zho'] | Retrieval | s2p | [News] | {'fas': 2232092, 'zho': 3179285, 'rus': 4627619} | {'fas': 3579.508213937439, 'zho': 2704.44834488453, 'rus': 3466.8192213553616} | +| [News21InstructionRetrieval](https://arxiv.org/abs/2403.15246) (Orion Weller, 2024) | ['eng'] | InstructionRetrieval | s2p | [News] | {'eng': 61906} | {'eng': 2983.724665391969} | +| [NewsClassification](https://arxiv.org/abs/1509.01626) | ['eng'] | Classification | s2s | [News] | {'test': 7600} | {'test': 235.29} | +| [NoRecClassification](https://aclanthology.org/L18-1661/) | ['nob'] | Classification | s2s | | {'test': 2050} | {'test': 82.0} | +| [NorQuadRetrieval](https://aclanthology.org/2023.nodalida-1.17/) | ['nob'] | Retrieval | p2p | [Encyclopaedic, Non-fiction] | {'test': 2602} | {'test': 502.19} | +| [NordicLangClassification](https://aclanthology.org/2021.vardial-1.8/) | ['dan', 'fao', 'isl', 'nno', 'nob', 'swe'] | Classification | s2s | | {'test': 3000} | {'test': 78.2} | +| [NorwegianCourtsBitextMining](https://opus.nlpl.eu/ELRC-Courts_Norway-v1.php) | ['nno', 'nob'] | BitextMining | s2s | [Spoken, Legal] | {'test': 456} | {'test': 82.11} | +| [NorwegianCourtsBitextMining](https://opus.nlpl.eu/index.php) (Tiedemann et al., 2020) | ['nno', 'nob'] | BitextMining | s2s | [Legal] | {'test': 2050} | {'test': 1884.0} | +| [NorwegianParliamentClassification](https://huggingface.co/datasets/NbAiLab/norwegian_parliament) | ['nob'] | Classification | s2s | | {'test': 1200, 'validation': 1200} | {'test': 1884.0, 'validation': 1911.0} | +| [NusaX-senti](https://arxiv.org/abs/2205.15960) (Winata et al., 2022) | ['ace', 'ban', 'bbc', 'bjn', 'bug', 'eng', 'ind', 'jav', 'mad', 'min', 'nij', 'sun'] | Classification | s2s | [Reviews, Web, Social, Constructed] | {'test': 4800} | {'test': 52.4} | +| [OPP115DataRetentionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 88} | {'test': 195.2} | +| [OPP115DataSecurityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1334} | {'test': 246.69} | +| [OPP115DoNotTrackLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 110} | {'test': 223.16} | +| [OPP115FirstPartyCollectionUseLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2086} | {'test': 204.25} | +| [OPP115InternationalAndSpecificAudiencesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 980} | {'test': 327.71} | +| [OPP115PolicyChangeLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 431} | {'test': 200.99} | +| [OPP115ThirdPartySharingCollectionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1590} | {'test': 223.64} | +| [OPP115UserAccessEditAndDeletionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 462} | {'test': 218.59} | +| [OPP115UserChoiceControlLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 1546} | {'test': 210.62} | +| [Ocnli](https://arxiv.org/abs/2010.05444) | ['cmn'] | PairClassification | s2s | | | | +| [OdiaNewsClassification](https://github.com/goru001/nlp-for-odia) | ['ory'] | Classification | s2s | [News] | {'test': 2048} | {'test': 49.24} | +| [OnlineShopping](https://aclanthology.org/2023.nodalida-1.20/) | ['cmn'] | Classification | s2s | | | | +| [OnlineStoreReviewSentimentClassification](https://huggingface.co/datasets/Ruqiya/Arabic_Reviews_of_SHEIN) | ['ara'] | Classification | s2s | [Reviews] | {'train': 2048} | {'train': 137.2} | +| [OpusparcusPC](https://gem-benchmark.com/data_cards/opusparcus) | ['deu', 'eng', 'fin', 'fra', 'rus', 'swe'] | PairClassification | s2s | | | | +| [OralArgumentQuestionPurposeLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 312} | {'test': 269.71} | +| [OverrulingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 167.2} | +| [PAC](https://arxiv.org/pdf/2211.13112.pdf) | ['pol'] | Classification | p2p | | {'test': 3453} | {'test': 185.3} | +| [PAWSX](https://aclanthology.org/2021.emnlp-main.357) | ['cmn'] | STS | s2s | | | | +| [PROALegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 95} | {'test': 251.73} | +| [PSC](http://www.lrec-conf.org/proceedings/lrec2014/pdf/1211_Paper.pdf) | ['pol'] | PairClassification | s2s | | | | +| [PatentClassification](https://aclanthology.org/P19-1212.pdf) | ['eng'] | Classification | s2s | [Legal] | {'test': 5000} | {'test': 18620.44} | +| [PawsX](https://arxiv.org/abs/1908.11828) | ['cmn', 'deu', 'eng', 'fra', 'jpn', 'kor', 'spa'] | PairClassification | s2s | | | | +| [PersianFoodSentimentClassification](https://hooshvare.github.io/docs/datasets/sa) (Mehrdad Farahani et al., 2020) | ['fas'] | Classification | s2s | [Reviews] | {'validation': 2048, 'test': 2048} | {'validation': 90.37, 'test': 90.58} | +| [PersonalJurisdictionLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 50} | {'test': 381.14} | +| [PlscClusteringP2P.v2](https://huggingface.co/datasets/rafalposwiata/plsc) | ['pol'] | Clustering | s2s | [Academic] | {'test': 2048} | {'test': 1023.21} | +| [PlscClusteringS2S.v2](https://huggingface.co/datasets/rafalposwiata/plsc) | ['pol'] | Clustering | s2s | [Academic] | {'test': 2048} | {'test': 84.34} | +| [PoemSentimentClassification](https://arxiv.org/abs/2011.02686) (Emily Sheng, 2020) | ['eng'] | Classification | s2s | [Reviews] | {'validation': 105, 'test': 104} | {'validation': 45.3, 'test': 42.4} | +| [PolEmo2.0-IN](https://aclanthology.org/K19-1092.pdf) | ['pol'] | Classification | s2s | | | | +| [PolEmo2.0-OUT](https://aclanthology.org/K19-1092.pdf) | ['pol'] | Classification | s2s | | {'test': 722} | {'test': 756.2} | +| [PpcPC](https://arxiv.org/pdf/2207.12759.pdf) | ['pol'] | PairClassification | s2s | | | | +| [PublicHealthQA](https://huggingface.co/datasets/xhluca/publichealth-qa) | ['ara', 'eng', 'fra', 'kor', 'rus', 'spa', 'vie', 'zho'] | Retrieval | s2p | [Medical, Government, Web] | {'test': 888} | {'test': 778.1655} | +| [PunjabiNewsClassification](https://github.com/goru001/nlp-for-punjabi/) | ['pan'] | Classification | s2s | [News] | {'train': 627, 'test': 157} | {'train': 4222.22, 'test': 4115.14} | +| [QBQTC](https://github.com/CLUEbenchmark/QBQTC/tree/main/dataset) | ['cmn'] | STS | s2s | | | | +| [Quora-PL](https://quoradata.quora.com/First-Quora-Dataset-Release-Question-Pairs) | ['pol'] | Retrieval | s2s | | | | +| [QuoraRetrieval](https://quoradata.quora.com/First-Quora-Dataset-Release-Question-Pairs) | ['eng'] | Retrieval | s2s | | | | +| [RTE3](https://aclanthology.org/W07-1401/) | ['deu', 'eng', 'fra', 'ita'] | PairClassification | s2s | [News, Web, Encyclopaedic] | {'test': 1923} | {'test': 124.79} | +| [RUParaPhraserSTS](https://aclanthology.org/2020.ngt-1.6) (Pivovarova et al., 2017) | ['rus'] | STS | s2s | [News] | {'test': 1924} | {'test': 61.25} | +| [RedditClusteringP2P](https://arxiv.org/abs/2104.07081) | ['eng'] | Clustering | p2p | | {'test': 459399} | {'test': 727.7} | +| [RedditFastClusteringP2P](https://arxiv.org/abs/2104.07081) (Gregor Geigle, 2021) | ['eng'] | Clustering | p2p | [Web, Social] | {'test': 16000} | {'test': 727.7} | +| [RedditFastClusteringS2S](https://arxiv.org/abs/2104.07081) (Gregor Geigle, 2021) | ['eng'] | Clustering | s2s | [Web, Social] | {'test': 16000} | {'test': 64.7} | +| [RestaurantReviewSentimentClassification](https://link.springer.com/chapter/10.1007/978-3-319-18117-2_2) (ElSahar et al., 2015) | ['ara'] | Classification | s2s | [Reviews] | {'train': 2048} | {'train': 231.4} | +| [Robust04InstructionRetrieval](https://arxiv.org/abs/2403.15246) (Orion Weller, 2024) | ['eng'] | InstructionRetrieval | s2p | [News] | {'eng': 95088} | {'eng': 2471.0398058252426} | +| [RomaTalesBitextMining](https://idoc.pub/documents/idocpub-zpnxm9g35ylv) | ['hun', 'rom'] | BitextMining | s2s | [Fiction] | {'test': 215} | {'test': 316.8046511627907} | +| [RomaniBibleClustering](https://romani.global.bible/info) | ['rom'] | Clustering | p2p | [Religious] | {'test': 2048} | {'test': 132.2} | +| [RomanianReviewsSentiment](https://arxiv.org/abs/2101.04197) (Anca Maria Tache, 2021) | ['ron'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 588.6} | +| [RomanianSentimentClassification](https://arxiv.org/abs/2009.08712) (Dumitrescu et al., 2020) | ['ron'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 67.6} | +| [RonSTS](https://openreview.net/forum?id=JH61CD7afTv) (Dumitrescu et al., 2021) | ['ron'] | STS | s2s | [News, Social, Web] | {'test': 1379} | {'test': 60.5} | +| [SCDBPAccountabilityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3520.0} | +| [SCDBPAuditsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3507.0} | +| [SCDBPCertificationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 378} | {'test': 3507.0} | +| [SCDBPTrainingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3506.0} | +| [SCDBPVerificationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3498.0} | +| [SCDDAccountabilityLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 378} | {'test': 3522.0} | +| [SCDDAuditsLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3506.0} | +| [SCDDCertificationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 378} | {'test': 3518.0} | +| [SCDDTrainingLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3499.0} | +| [SCDDVerificationLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 379} | {'test': 3503.0} | +| [SCIDOCS](https://allenai.org/data/scidocs) | ['eng'] | Retrieval | s2p | | | | +| [SCIDOCS-PL](https://allenai.org/data/scidocs) | ['pol'] | Retrieval | s2p | | | | +| [SIB200Classification](https://arxiv.org/abs/2309.07445) (Adelani et al., 2023) | ['ace', 'acm', 'acq', 'aeb', 'afr', 'ajp', 'aka', 'als', 'amh', 'apc', 'arb', 'ars', 'ary', 'arz', 'asm', 'ast', 'awa', 'ayr', 'azb', 'azj', 'bak', 'bam', 'ban', 'bel', 'bem', 'ben', 'bho', 'bjn', 'bod', 'bos', 'bug', 'bul', 'cat', 'ceb', 'ces', 'cjk', 'ckb', 'crh', 'cym', 'dan', 'deu', 'dik', 'dyu', 'dzo', 'ell', 'eng', 'epo', 'est', 'eus', 'ewe', 'fao', 'fij', 'fin', 'fon', 'fra', 'fur', 'fuv', 'gaz', 'gla', 'gle', 'glg', 'grn', 'guj', 'hat', 'hau', 'heb', 'hin', 'hne', 'hrv', 'hun', 'hye', 'ibo', 'ilo', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kab', 'kac', 'kam', 'kan', 'kas', 'kat', 'kaz', 'kbp', 'kea', 'khk', 'khm', 'kik', 'kin', 'kir', 'kmb', 'kmr', 'knc', 'kon', 'kor', 'lao', 'lij', 'lim', 'lin', 'lit', 'lmo', 'ltg', 'ltz', 'lua', 'lug', 'luo', 'lus', 'lvs', 'mag', 'mai', 'mal', 'mar', 'min', 'mkd', 'mlt', 'mni', 'mos', 'mri', 'mya', 'nld', 'nno', 'nob', 'npi', 'nqo', 'nso', 'nus', 'nya', 'oci', 'ory', 'pag', 'pan', 'pap', 'pbt', 'pes', 'plt', 'pol', 'por', 'prs', 'quy', 'ron', 'run', 'rus', 'sag', 'san', 'sat', 'scn', 'shn', 'sin', 'slk', 'slv', 'smo', 'sna', 'snd', 'som', 'sot', 'spa', 'srd', 'srp', 'ssw', 'sun', 'swe', 'swh', 'szl', 'tam', 'taq', 'tat', 'tel', 'tgk', 'tgl', 'tha', 'tir', 'tpi', 'tsn', 'tso', 'tuk', 'tum', 'tur', 'twi', 'tzm', 'uig', 'ukr', 'umb', 'urd', 'uzn', 'vec', 'vie', 'war', 'wol', 'xho', 'ydd', 'yor', 'yue', 'zho', 'zsm', 'zul'] | Classification | s2s | [News] | {'train': 701, 'validation': 99, 'test': 204} | {'train': 111.24, 'validation': 97.11, 'test': 135.53} | +| [SIB200ClusteringFastS2S](https://arxiv.org/abs/2309.07445) (Adelani et al., 2023) | ['ace', 'acm', 'acq', 'aeb', 'afr', 'ajp', 'aka', 'als', 'amh', 'apc', 'arb', 'ars', 'ary', 'arz', 'asm', 'ast', 'awa', 'ayr', 'azb', 'azj', 'bak', 'bam', 'ban', 'bel', 'bem', 'ben', 'bho', 'bjn', 'bod', 'bos', 'bug', 'bul', 'cat', 'ceb', 'ces', 'cjk', 'ckb', 'crh', 'cym', 'dan', 'deu', 'dik', 'dyu', 'dzo', 'ell', 'eng', 'epo', 'est', 'eus', 'ewe', 'fao', 'fij', 'fin', 'fon', 'fra', 'fur', 'fuv', 'gaz', 'gla', 'gle', 'glg', 'grn', 'guj', 'hat', 'hau', 'heb', 'hin', 'hne', 'hrv', 'hun', 'hye', 'ibo', 'ilo', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kab', 'kac', 'kam', 'kan', 'kas', 'kat', 'kaz', 'kbp', 'kea', 'khk', 'khm', 'kik', 'kin', 'kir', 'kmb', 'kmr', 'knc', 'kon', 'kor', 'lao', 'lij', 'lim', 'lin', 'lit', 'lmo', 'ltg', 'ltz', 'lua', 'lug', 'luo', 'lus', 'lvs', 'mag', 'mai', 'mal', 'mar', 'min', 'mkd', 'mlt', 'mni', 'mos', 'mri', 'mya', 'nld', 'nno', 'nob', 'npi', 'nqo', 'nso', 'nus', 'nya', 'oci', 'ory', 'pag', 'pan', 'pap', 'pbt', 'pes', 'plt', 'pol', 'por', 'prs', 'quy', 'ron', 'run', 'rus', 'sag', 'san', 'sat', 'scn', 'shn', 'sin', 'slk', 'slv', 'smo', 'sna', 'snd', 'som', 'sot', 'spa', 'srd', 'srp', 'ssw', 'sun', 'swe', 'swh', 'szl', 'tam', 'taq', 'tat', 'tel', 'tgk', 'tgl', 'tha', 'tir', 'tpi', 'tsn', 'tso', 'tuk', 'tum', 'tur', 'twi', 'tzm', 'uig', 'ukr', 'umb', 'urd', 'uzn', 'vec', 'vie', 'war', 'wol', 'xho', 'ydd', 'yor', 'yue', 'zho', 'zsm', 'zul'] | Classification | s2s | [News] | {'test': 1004} | {'test': 114.78} | +| [SICK-BR-PC](https://linux.ime.usp.br/~thalen/SICK_PT.pdf) | ['por'] | PairClassification | s2s | [Web] | {'test': 1000} | {'test': 54.89} | +| [SICK-BR-STS](https://linux.ime.usp.br/~thalen/SICK_PT.pdf) | ['por'] | STS | s2s | [Web] | {'test': 1000} | {'test': 54.89} | +| [SICK-E-PL](https://aclanthology.org/2020.lrec-1.207) | ['pol'] | PairClassification | s2s | | | | +| [SICK-R](https://aclanthology.org/2020.lrec-1.207) | ['eng'] | STS | s2s | | | | +| [SICK-R-PL](https://aclanthology.org/2020.lrec-1.207) | ['pol'] | STS | s2s | [Web] | {'test': 9812} | {'test': 42.8} | +| [SICKFr](https://huggingface.co/datasets/Lajavaness/SICK-fr) | ['fra'] | STS | s2s | | | | +| [SNLHierarchicalClusteringP2P](https://huggingface.co/datasets/navjordj/SNL_summarization) (Navjord et al., 2023) | ['nob'] | Clustering | p2p | [Encyclopaedic, Non-fiction] | {'test': 1300} | {'test': 1986.9453846153847} | +| [SNLHierarchicalClusteringS2S](https://huggingface.co/datasets/navjordj/SNL_summarization) (Navjord et al., 2023) | ['nob'] | Clustering | s2s | [Encyclopaedic, Non-fiction] | {'test': 1300} | {'test': 242.22384615384615} | +| [SNLRetrieval](https://huggingface.co/datasets/navjordj/SNL_summarization) (Navjord et al., 2023) | ['nob'] | Retrieval | p2p | [Encyclopaedic, Non-fiction] | {'test': 2048} | {'test': 1101.3} | +| [SRNCorpusBitextMining](https://arxiv.org/abs/2212.06383) (Zwennicker et al., 2022) | ['nld', 'srn'] | BitextMining | s2s | [Social, Web] | {'test': 256} | {'test': 55.0} | +| [STS12](https://www.aclweb.org/anthology/S12-1051.pdf) | ['eng'] | STS | s2s | | | | +| [STS13](https://www.aclweb.org/anthology/S13-1004/) | ['eng'] | STS | s2s | | | | +| [STS14](https://www.aclweb.org/anthology/S14-1002) | ['eng'] | STS | s2s | | | | +| [STS15](https://www.aclweb.org/anthology/S15-2010) | ['eng'] | STS | s2s | | | | +| [STS16](https://www.aclweb.org/anthology/S16-1001) | ['eng'] | STS | s2s | | | | +| [STS17](http://alt.qcri.org/semeval2016/task1/) | ['ara', 'deu', 'eng', 'fra', 'ita', 'kor', 'nld', 'spa', 'tur'] | STS | s2s | | {'test': 500} | {'test': 43.3} | +| [STS22](https://competitions.codalab.org/competitions/33835) | ['ara', 'cmn', 'deu', 'eng', 'fra', 'ita', 'pol', 'rus', 'spa', 'tur'] | STS | p2p | | {'test': 8060} | {'train': 1992.8} | +| [STSB](https://aclanthology.org/2021.emnlp-main.357) | ['cmn'] | STS | s2s | | | | +| [STSBenchmark](https://github.com/PhilipMay/stsb-multi-mt/) | ['eng'] | STS | s2s | | | | +| [STSBenchmarkMultilingualSTS](https://github.com/PhilipMay/stsb-multi-mt/) | ['cmn', 'deu', 'eng', 'fra', 'ita', 'nld', 'pol', 'por', 'rus', 'spa'] | STS | s2s | | | | +| [STSES](https://huggingface.co/datasets/PlanTL-GOB-ES/sts-es) | ['spa'] | STS | s2s | | | | +| [SanskritShlokasClassification](https://github.com/goru001/nlp-for-sanskrit) | ['san'] | Classification | s2s | [Religious] | {'train': 383, 'validation': 96} | {'train': 98.415, 'validation': 96.635} | +| [ScalaClassification](https://aclanthology.org/2023.nodalida-1.20/) | ['dan', 'nno', 'nob', 'swe'] | Classification | s2s | [Fiction, News, Non-fiction, Blog, Spoken, Web] | {'test': 4096} | {'test': 102.72} | +| [SciDocsRR](https://allenai.org/data/scidocs) | ['eng'] | Reranking | s2s | [Academic, Non-fiction] | {'test': 19599} | {'test': 69.0} | +| [SciFact](https://github.com/allenai/scifact) | ['eng'] | Retrieval | s2p | | | | +| [SciFact-PL](https://github.com/allenai/scifact) | ['pol'] | Retrieval | s2p | | | | +| [SentimentAnalysisHindi](https://huggingface.co/datasets/OdiaGenAI/sentiment_analysis_hindi) (Shantipriya Parida, 2023) | ['hin'] | Classification | s2s | [Reviews] | {'train': 2497} | {'train': 81.29} | +| [SinhalaNewsClassification](https://huggingface.co/datasets/NLPC-UOM/Sinhala-News-Category-classification) (Nisansa de Silva, 2015) | ['sin'] | Classification | s2s | [News] | {'train': 3327} | {'train': 148.04} | +| [SinhalaNewsSourceClassification](https://huggingface.co/datasets/NLPC-UOM/Sinhala-News-Source-classification) (Dhananjaya et al., 2022) | ['sin'] | Classification | s2s | [News] | {'train': 24094} | {'train': 56.08} | +| [SiswatiNewsClassification](https://huggingface.co/datasets/dsfsi/za-isizulu-siswati-news) (Madodonga et al., 2023) | ['ssw'] | Classification | s2s | [News] | {'train': 80} | {'train': 354.2} | +| [SlovakMovieReviewSentimentClassification](https://arxiv.org/pdf/2304.01922) ({ {S, 2023) | ['svk'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 366.17} | +| [SlovakSumRetrieval](https://huggingface.co/datasets/NaiveNeuron/slovaksum) | ['slk'] | Retrieval | s2s | [News, Social, Web] | {'test': 600} | {'test': 238.44} | +| [SouthAfricanLangClassification](https://www.kaggle.com/competitions/south-african-language-identification/) | ['afr', 'eng', 'nbl', 'nso', 'sot', 'ssw', 'tsn', 'tso', 'ven', 'xho', 'zul'] | Classification | s2s | [Web, Non-fiction] | {'test': 2048} | {'test': 247.49} | +| [SpanishNewsClassification](https://huggingface.co/datasets/MarcOrfilaCarreras/spanish-news) | ['spa'] | Classification | s2s | [News] | {'train': 2048} | {'train': 4218.2} | +| [SpanishNewsClusteringP2P](https://www.kaggle.com/datasets/kevinmorgado/spanish-news-classification) | ['spa'] | Clustering | p2p | | | | +| [SpanishPassageRetrievalS2P](https://mklab.iti.gr/results/spanish-passage-retrieval-dataset/) | ['spa'] | Retrieval | s2p | | | | +| [SpanishPassageRetrievalS2S](https://mklab.iti.gr/results/spanish-passage-retrieval-dataset/) | ['spa'] | Retrieval | s2s | | | | +| [SpanishSentimentClassification](https://huggingface.co/datasets/sepidmnorozy/Spanish_sentiment) | ['spa'] | Classification | s2s | [Reviews] | {'validation': 147, 'test': 296} | {'validation': 85.02, 'test': 87.91} | +| [SprintDuplicateQuestions](https://www.aclweb.org/anthology/D18-1131/) | ['eng'] | PairClassification | s2s | | {'validation': 101000, 'test': 101000} | {'validation': 65.2, 'test': 67.9} | +| [StackExchangeClustering.v2](https://arxiv.org/abs/2104.07081) (Gregor Geigle, 2021) | ['eng'] | Clustering | s2s | [Web] | {'test': 16000} | {'test': 57.0} | +| [StackExchangeClusteringP2P.v2](https://arxiv.org/abs/2104.07081) (Gregor Geigle, 2021) | ['eng'] | Clustering | p2p | [Web] | {'test': 16000} | {'test': 1090.7} | +| [StackOverflowDupQuestions](https://www.microsoft.com/en-us/research/uploads/prod/2019/03/nl4se18LinkSO.pdf) | ['eng'] | Reranking | s2s | | {'test': 3467} | {'test': 49.8} | +| [StatcanDialogueDatasetRetrieval](https://mcgill-nlp.github.io/statcan-dialogue-dataset/) | ['eng', 'fra'] | Retrieval | s2p | [Government, Web] | {'dev': 1000, 'test': 1011, 'corpus': 5907} | {'dev': 776.58, 'test': 857.13, 'corpus': 6806.97} | +| [SummEval](https://tabilab.cmpe.boun.edu.tr/BIOSSES/DataSet.html) | ['eng'] | Summarization | p2p | | {'test': 2800} | {'test': 359.8} | +| [SummEvalFr](https://github.com/Yale-LILY/SummEval) | ['fra'] | Summarization | p2p | | | | +| [SweFaqRetrieval](https://spraakbanken.gu.se/en/resources/superlim) | ['swe'] | Retrieval | s2s | [Government, Non-fiction] | {'test': 1024} | {'test': 195.44} | +| [SweRecClassification](https://aclanthology.org/2023.nodalida-1.20/) | ['swe'] | Classification | s2s | | {'test': 1024} | {'test': 318.8} | +| [SwedishSentimentClassification](https://huggingface.co/datasets/swedish_reviews) | ['swe'] | Classification | s2s | [Reviews] | {'validation': 1024, 'test': 1024} | {'validation': 499.3, 'test': 498.1} | +| [SwednClusteringP2P](https://spraakbanken.gu.se/en/resources/swedn) (Monsen et al., 2021) | ['swe'] | Clustering | p2p | [News, Non-fiction] | {'all': 2048} | {'all': 1619.71} | +| [SwednClusteringS2S](https://spraakbanken.gu.se/en/resources/swedn) (Monsen et al., 2021) | ['swe'] | Clustering | s2s | [News, Non-fiction] | {'all': 2048} | {'all': 1619.71} | +| [SwednRetrieval](https://spraakbanken.gu.se/en/resources/swedn) (Monsen et al., 2021) | ['swe'] | Retrieval | p2p | [News, Non-fiction] | {'test': 2048} | {'test': 1946.35} | +| [SwissJudgementClassification](https://aclanthology.org/2021.nllp-1.3/) (Joel Niklaus, 2022) | ['deu', 'fra', 'ita'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 3411.72} | +| [SyntecReranking](https://huggingface.co/datasets/lyon-nlp/mteb-fr-reranking-syntec-s2p) | ['fra'] | Reranking | s2p | [Legal] | | | +| [SyntecRetrieval](https://huggingface.co/datasets/lyon-nlp/mteb-fr-retrieval-syntec-s2p) | ['fra'] | Retrieval | s2p | | {'test': 90} | {'test': 62.0} | +| [T2Reranking](https://arxiv.org/abs/2304.03679) | ['cmn'] | Reranking | s2s | | | | +| [T2Retrieval](https://arxiv.org/abs/2304.03679) | ['cmn'] | Retrieval | s2p | | | | +| [TNews](https://www.cluebenchmarks.com/introduce.html) | ['cmn'] | Classification | s2s | | | | +| [TRECCOVID](https://ir.nist.gov/covidSubmit/index.html) | ['eng'] | Retrieval | s2p | | | | +| [TRECCOVID-PL](https://ir.nist.gov/covidSubmit/index.html) | ['pol'] | Retrieval | s2p | | | | +| [TV2Nordretrieval](https://huggingface.co/datasets/alexandrainst/nordjylland-news-summarization) | ['dan'] | Retrieval | p2p | [News, Non-fiction] | {'test': 4096} | {'test': 784.11} | +| [TamilNewsClassification](https://github.com/vanangamudi/tamil-news-classification) | ['tam'] | Classification | s2s | [News] | {'train': 14521, 'test': 3631} | {'train': 56.5, 'test': 56.52} | +| [Tatoeba](https://github.com/facebookresearch/LASER/tree/main/data/tatoeba/v1) (Tatoeba community, 2021) | ['afr', 'amh', 'ang', 'ara', 'arq', 'arz', 'ast', 'awa', 'aze', 'bel', 'ben', 'ber', 'bos', 'bre', 'bul', 'cat', 'cbk', 'ceb', 'ces', 'cha', 'cmn', 'cor', 'csb', 'cym', 'dan', 'deu', 'dsb', 'dtp', 'ell', 'eng', 'epo', 'est', 'eus', 'fao', 'fin', 'fra', 'fry', 'gla', 'gle', 'glg', 'gsw', 'heb', 'hin', 'hrv', 'hsb', 'hun', 'hye', 'ido', 'ile', 'ina', 'ind', 'isl', 'ita', 'jav', 'jpn', 'kab', 'kat', 'kaz', 'khm', 'kor', 'kur', 'kzj', 'lat', 'lfn', 'lit', 'lvs', 'mal', 'mar', 'max', 'mhr', 'mkd', 'mon', 'nds', 'nld', 'nno', 'nob', 'nov', 'oci', 'orv', 'pam', 'pes', 'pms', 'pol', 'por', 'ron', 'rus', 'slk', 'slv', 'spa', 'sqi', 'srp', 'swe', 'swg', 'swh', 'tam', 'tat', 'tel', 'tgl', 'tha', 'tuk', 'tur', 'tzl', 'uig', 'ukr', 'urd', 'uzb', 'vie', 'war', 'wuu', 'xho', 'yid', 'yue', 'zsm'] | BitextMining | s2s | | {'test': 2000} | {'test': 39.4} | +| [TbilisiCityHallBitextMining](https://huggingface.co/datasets/jupyterjazz/tbilisi-city-hall-titles) | ['eng', 'kat'] | BitextMining | s2s | [News] | {'test': 1820} | {'test': 78.0} | +| [TelemarketingSalesRuleLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 47} | {'test': 348.29} | +| [TeluguAndhraJyotiNewsClassification](https://github.com/AnushaMotamarri/Telugu-Newspaper-Article-Dataset) | ['tel'] | Classification | s2s | [News] | {'test': 4329} | {'test': 1428.28} | +| [TenKGnadClassification](https://tblock.github.io/10kGNAD/) | ['deu'] | Classification | p2p | [News] | {'test': 1028} | {'test': 2627.31} | +| [TenKGnadClusteringP2P.v2](https://tblock.github.io/10kGNAD/) | ['deu'] | Clustering | p2p | [News, Non-fiction] | {'test': 10275} | {'test': 2641.03} | +| [TenKGnadClusteringS2S.v2](https://tblock.github.io/10kGNAD/) | ['deu'] | Clustering | s2s | [News, Non-fiction] | {'test': 10275} | {'test': 50.96} | +| [TextualismToolDictionariesLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 107} | {'test': 943.23} | +| [TextualismToolPlainLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 165} | {'test': 997.97} | +| [ThuNewsClusteringP2P.v2](http://thuctc.thunlp.org/) | ['cmn'] | Clustering | p2p | [News] | {'test': 2048} | | +| [ThuNewsClusteringS2S.v2](http://thuctc.thunlp.org/) | ['cmn'] | Clustering | s2s | [News] | {'test': 2048} | | +| [TopiOCQA](https://mcgill-nlp.github.io/topiocqa) (Adlakha et al., 2022) | ['eng'] | Retrieval | s2p | [Encyclopaedic] | {'dev': 2514} | {'validation': 708.0} | +| [Touche2020](https://webis.de/events/touche-20/shared-task-1.html) | ['eng'] | Retrieval | s2p | | | | +| [ToxicChatClassification](https://aclanthology.org/2023.findings-emnlp.311/) (Zi Lin, 2023) | ['eng'] | Classification | s2s | [Constructed] | {'test': 1427} | {'test': 189.4} | +| [ToxicConversationsClassification](https://www.kaggle.com/competitions/jigsaw-unintended-bias-in-toxicity-classification/overview) (cjadams et al., 2019) | ['eng'] | Classification | s2s | [Social] | {'test': 50000} | {'test': 296.6} | +| [TswanaNewsClassification](https://link.springer.com/chapter/10.1007/978-3-031-49002-6_17) (Vukosi Marivate, 2023) | ['tsn'] | Classification | s2s | [News] | {'validation': 487, 'test': 487} | {'validation': 2417.72, 'test': 2369.52} | +| [TurHistQuadRetrieval](https://github.com/okanvk/Turkish-Reading-Comprehension-Question-Answering-Dataset) (Soygazi et al., 2021) | ['tur'] | Retrieval | p2p | [Encyclopaedic, Non-fiction, Academic] | {'test': 1330} | {'test': 1513.83} | +| [TurkicClassification](https://huggingface.co/datasets/Electrotubbie/classification_Turkic_languages/) | ['bak', 'kaz', 'kir'] | Classification | s2s | [News] | {'train': 193056} | {'train': 1103.13} | +| [TurkishMovieSentimentClassification](https://www.win.tue.nl/~mpechen/publications/pubs/MT_WISDOM2013.pdf) (Erkin Demirtas, 2013) | ['tur'] | Classification | s2s | [Reviews] | {'test': 2644} | {'test': 141.5} | +| [TurkishProductSentimentClassification](https://www.win.tue.nl/~mpechen/publications/pubs/MT_WISDOM2013.pdf) (Erkin Demirtas, 2013) | ['tur'] | Classification | s2s | [Reviews] | {'test': 800} | {'test': 246.85} | +| [TweetEmotionClassification](https://link.springer.com/chapter/10.1007/978-3-319-77116-8_8) (Al-Khatib et al., 2018) | ['ara'] | Classification | s2s | [Social] | {'train': 2048} | {'train': 78.8} | +| [TweetSarcasmClassification](https://aclanthology.org/2020.osact-1.5/) | ['ara'] | Classification | s2s | [Social] | {'test': 2110} | {'test': 102.1} | +| [TweetSentimentClassification](https://aclanthology.org/2022.lrec-1.27) | ['ara', 'deu', 'eng', 'fra', 'hin', 'ita', 'por', 'spa'] | Classification | s2s | [Social] | {'test': 2048} | {'test': 83.51} | +| [TweetSentimentExtractionClassification](https://www.kaggle.com/competitions/tweet-sentiment-extraction/overview) (Maggie et al., 2020) | ['eng'] | Classification | s2s | [Social] | {'test': 3534} | {'test': 67.8} | +| [TweetTopicSingleClassification](https://arxiv.org/abs/2209.09824) | ['eng'] | Classification | s2s | [Social, News] | {'test_2021': 1693} | {'test_2021': 167.66} | +| [TwentyNewsgroupsClustering.v2](https://scikit-learn.org/0.19/datasets/twenty_newsgroups.html) (Ken Lang, 1995) | ['eng'] | Clustering | s2s | [News] | {'test': 2048} | {'test': 32.0} | +| [TwitterHjerneRetrieval](https://huggingface.co/datasets/sorenmulli/da-hashtag-twitterhjerne) (Holm et al., 2024) | ['dan'] | Retrieval | p2p | [Social] | {'train': 340} | {'train': 138.23} | +| [TwitterSemEval2015](https://alt.qcri.org/semeval2015/task1/) | ['eng'] | PairClassification | s2s | | {'test': 16777} | {'test': 38.3} | +| [TwitterURLCorpus](https://languagenet.github.io/) | ['eng'] | PairClassification | s2s | | {'test': 51534} | {'test': 79.5} | +| [UCCVCommonLawLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 94} | {'test': 114.127} | +| [UkrFormalityClassification](https://huggingface.co/datasets/ukr-detect/ukr-formality-dataset-translated-gyafc) | ['ukr'] | Classification | s2s | [News] | {'train': 2048, 'test': 2048} | {'train': 52.1, 'test': 53.07} | +| [UnfairTOSLegalBenchClassification](https://huggingface.co/datasets/nguha/legalbench) (Neel Guha, 2023) | ['eng'] | Classification | s2s | [Legal] | {'test': 2048} | {'test': 184.69} | +| [UrduRomanSentimentClassification](https://archive.ics.uci.edu/dataset/458/roman+urdu+data+set) (Sharf,Zareen, 2018) | ['urd'] | Classification | s2s | [Social] | {'train': 2048} | {'train': 68.248} | +| [VGHierarchicalClusteringP2P](https://huggingface.co/datasets/navjordj/VG_summarization) (Navjord et al., 2023) | ['nob'] | Clustering | p2p | [News, Non-fiction] | {'test': 2048} | {'test': 2670.3243084794544} | +| [VGHierarchicalClusteringS2S](https://huggingface.co/datasets/navjordj/VG_summarization) (Navjord et al., 2023) | ['nob'] | Clustering | p2p | [News, Non-fiction] | {'test': 2048} | {'test': 139.31247668283325} | +| [VideoRetrieval](https://arxiv.org/abs/2203.03367) | ['cmn'] | Retrieval | s2p | | | | +| [VieMedEVBitextMining](https://aclanthology.org/2015.iwslt-evaluation.11/) (Nhu Vo, 2024) | ['eng', 'vie'] | BitextMining | s2s | [Medical] | {'test': 2048} | {'test': 139.23} | +| [VieQuADRetrieval](https://aclanthology.org/2020.coling-main.233.pdf) | ['vie'] | Retrieval | s2p | [Encyclopaedic, Non-fiction] | {'validation': 2048} | {'validation': 790.24} | +| [VieStudentFeedbackClassification](https://ieeexplore.ieee.org/document/8573337) (Nguyen et al., 2018) | ['vie'] | Classification | s2s | [Reviews] | {'test': 2048} | {'test': 14.22} | +| [WRIMEClassification](https://aclanthology.org/2021.naacl-main.169/) | ['jpn'] | Classification | s2s | [Social] | {'test': 2048} | {'test': 47.78} | +| [Waimai](https://aclanthology.org/2023.nodalida-1.20/) | ['cmn'] | Classification | s2s | | | | +| [WikiCitiesClustering](https://huggingface.co/datasets/wikipedia) | ['eng'] | Clustering | p2p | | | | +| [WikiClusteringFastP2P](https://github.com/Rysias/wiki-clustering) | ['bos', 'cat', 'ces', 'dan', 'eus', 'glv', 'ilo', 'kur', 'lav', 'min', 'mlt', 'sco', 'sqi', 'wln'] | Clustering | p2p | [Encyclopaedic] | {'test': 2048} | {'test': 625.3} | +| [WikipediaRerankingMultilingual](https://huggingface.co/datasets/ellamind/wikipedia-2023-11-reranking-multilingual) | ['ben', 'bul', 'ces', 'dan', 'deu', 'eng', 'fas', 'fin', 'hin', 'ita', 'nld', 'nor', 'por', 'ron', 'srp', 'swe'] | Reranking | s2p | [Encyclopaedic] | {'en': 1500, 'de': 1500, 'it': 1500, 'pt': 1500, 'nl': 1500, 'cs': 1500, 'ro': 1500, 'bg': 1500, 'sr': 1500, 'fi': 1500, 'da': 1500, 'fa': 1500, 'hi': 1500, 'bn': 1500, 'no': 1500, 'sv': 1500} | {'test': 452.0} | +| [WikipediaRetrievalMultilingual](https://huggingface.co/datasets/ellamind/wikipedia-2023-11-retrieval-pt) | ['ben', 'bul', 'ces', 'dan', 'deu', 'eng', 'fas', 'fin', 'hin', 'ita', 'nld', 'nor', 'por', 'ron', 'srp', 'swe'] | Retrieval | s2p | [Encyclopaedic] | {'en': 1500, 'de': 1500, 'it': 1500, 'pt': 1500, 'nl': 1500, 'cs': 1500, 'ro': 1500, 'bg': 1500, 'sr': 1500, 'fi': 1500, 'da': 1500, 'fa': 1500, 'hi': 1500, 'bn': 1500, 'no': 1500, 'sv': 1500} | {'test': 452.0} | +| [WisesightSentimentClassification](https://github.com/PyThaiNLP/wisesight-sentiment) | ['tha'] | Classification | s2s | [Social, News] | {'train': 2048} | {'train': 103.42} | +| XMarket | ['deu', 'eng', 'spa'] | Retrieval | s2p | | | | +| [XNLI](https://aclanthology.org/D18-1269/) (Conneau et al., 2018) | ['ara', 'bul', 'deu', 'ell', 'eng', 'fra', 'hin', 'rus', 'spa', 'swa', 'tha', 'tur', 'vie', 'zho'] | PairClassification | s2s | [Non-fiction, Fiction, Government] | {'validation': 2163, 'test': 2460} | {'validation': 106.5, 'test': 106.5} | +| [XNLIV2](https://arxiv.org/pdf/2301.06527) (Upadhyay et al., 2023) | ['asm', 'ben', 'bho', 'ell', 'guj', 'kan', 'mar', 'ory', 'pan', 'rus', 'san', 'tam', 'tur'] | PairClassification | s2s | [Non-fiction, Fiction, Government] | {'test': 5010} | {'test': 80.06} | +| [XPQARetrieval](https://arxiv.org/abs/2305.09249) (Shen et al., 2023) | ['ara', 'cmn', 'deu', 'eng', 'fra', 'hin', 'ita', 'jpn', 'kor', 'pol', 'por', 'spa', 'tam'] | Retrieval | s2p | [Reviews] | {'test': 19801} | {'test': 104.68} | +| [XQuADRetrieval](https://huggingface.co/datasets/xquad) (Mikel Artetxe, 2019) | ['arb', 'deu', 'ell', 'eng', 'hin', 'ron', 'rus', 'spa', 'tha', 'tur', 'vie', 'zho'] | Retrieval | s2p | [Web] | {'test': 1190} | {'test': 788.7} | +| [XStance](https://github.com/ZurichNLP/xstance) | ['deu', 'fra', 'ita'] | PairClassification | s2s | [Social] | {'test': 2048} | {'test': 152.41} | +| [YahooAnswersTopicsClassification](https://huggingface.co/datasets/yahoo_answers_topics) | ['eng'] | Classification | s2s | [Web] | {'test': 60000} | {'test': 346.35} | +| [YelpReviewFullClassification](https://arxiv.org/abs/1509.01626) (Zhang et al., 2015) | ['eng'] | Classification | s2s | [Reviews] | {'test': 50000} | | +| [YueOpenriceReviewClassification](https://github.com/Christainx/Dataset_Cantonese_Openrice) (Xiang et al., 2019) | ['yue'] | Classification | s2s | [Reviews] | {'test': 6161} | {'test': 173.0} | +| [indonli](https://link.springer.com/chapter/10.1007/978-3-030-41505-1_39) | ['ind'] | PairClassification | s2s | [Encyclopaedic, Web, News] | {'test_expert': 2040} | {'test_expert': 145.88} | + + +
+ +
+ +## Task Count per Language + +
+ + +| Language | BitextMining | Classification | Clustering | InstructionRetrieval | MultilabelClassification | PairClassification | Reranking | Retrieval | STS | Summarization | +|---|------|------|------|------|------|------|------|------|------|---| +| aai | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aak | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aau | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aaz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| abt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| abx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aby | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ace | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| acf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| acm | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| acq | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| acr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| acu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| adz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aeb | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aer | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aey | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| afr | 3 | 5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| agd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| agg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| agm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| agn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| agr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| agt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| agu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aia | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aii | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ajp | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aka | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ake | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| alp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| alq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| als | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| aly | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ame | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amh | 3 | 7 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| amk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| amx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ang | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| anh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| anp | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| anv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aoi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aoj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aom | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aon | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apc | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| ape | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| apz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ara | 2 | 12 | 0 | 0 | 0 | 2 | 0 | 5 | 2 | 0 | +| arb | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | +| are | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| arl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| arn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| arp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| arq | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ars | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| ary | 1 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| arz | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| asm | 5 | 4 | 1 | 0 | 0 | 1 | 0 | 2 | 1 | 0 | +| aso | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ast | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ata | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| atb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| atd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| atg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| att | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| auc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aui | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| auy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| avt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| awa | 3 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| awb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| awk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| awx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ayr | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| azb | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| aze | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| azg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| azj | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| azz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bak | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bam | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| ban | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bao | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bba | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bbb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bbc | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bbr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bch | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bco | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bdd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bea | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bef | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bel | 4 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bem | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ben | 7 | 10 | 1 | 0 | 0 | 1 | 1 | 3 | 1 | 0 | +| beo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ber | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| beu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bgc | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bgs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bgt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bhb | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bhd | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bhg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bhl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bho | 2 | 3 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | +| big | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjj | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjn | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bjz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bkd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bki | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bkq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bkx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| blw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| blz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bmh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bmk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bmr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bmu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bnp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bns | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| boa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bod | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| boj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bon | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bos | 3 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| box | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| boy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bpr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bps | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bqc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bqp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bra | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bre | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| brx | 2 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bsj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bsn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bsp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bss | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bug | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| buk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bul | 3 | 5 | 0 | 0 | 1 | 1 | 1 | 2 | 0 | 0 | +| bus | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bvd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bvr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bxh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| byr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| byx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bzd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bzh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| bzj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| caa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cab | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cac | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| caf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cak | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cao | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cap | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| car | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cat | 3 | 3 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| cav | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cax | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbk | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cbv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cco | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ceb | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| cek | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ces | 4 | 6 | 1 | 0 | 1 | 1 | 1 | 2 | 0 | 0 | +| cgc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cha | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| chd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| chf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| chk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| chq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| chv | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| chz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cjk | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cjo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cjv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ckb | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| cle | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| clu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cme | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cmn | 4 | 10 | 4 | 0 | 0 | 3 | 4 | 10 | 9 | 0 | +| cmo | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cni | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cnl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cnt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| code | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 19 | 0 | 0 | +| cof | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| con | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cop | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cor | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cot | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cpa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cpb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cpc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cpu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cpy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| crh | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| crn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| crx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| csb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cso | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| csy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cta | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cth | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ctp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ctu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cub | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cuc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cui | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cuk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cut | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cux | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cwe | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cya | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| cym | 3 | 5 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| daa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dad | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dah | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dan | 5 | 10 | 1 | 0 | 1 | 0 | 1 | 5 | 0 | 0 | +| ded | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| deu | 6 | 15 | 6 | 0 | 1 | 6 | 2 | 17 | 4 | 0 | +| dgc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dgr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dgz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dhg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dif | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dik | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| div | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dji | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| djk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| djr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dob | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| doi | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dop | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dov | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dsb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dtp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dwr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dww | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dwy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dyu | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dza | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| dzo | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ebk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| eko | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ell | 3 | 7 | 0 | 0 | 1 | 2 | 0 | 3 | 0 | 0 | +| emi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| emp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| eng | 12 | 144 | 16 | 3 | 1 | 8 | 5 | 52 | 12 | 1 | +| enq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| epo | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| eri | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ese | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| esk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| est | 2 | 3 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | +| etr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| eus | 3 | 3 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| ewe | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| faa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fai | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fao | 3 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | +| far | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fas | 1 | 4 | 0 | 0 | 0 | 1 | 1 | 3 | 0 | 0 | +| ffm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fij | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fil | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fin | 3 | 6 | 0 | 0 | 1 | 1 | 1 | 2 | 1 | 0 | +| fon | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| for | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fra | 7 | 14 | 7 | 0 | 1 | 5 | 2 | 12 | 4 | 1 | +| fry | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fuc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fue | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fuf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fuh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fur | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| fuv | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| gah | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gai | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gam | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gaw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gaz | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| gbm | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gdn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gdr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| geb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gfk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ghs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gla | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gle | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| glg | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| glk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| glv | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gmv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gng | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gnn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gnw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gof | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gom | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| grc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| grn | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| gsw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gub | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| guh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gui | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| guj | 6 | 7 | 1 | 0 | 0 | 1 | 0 | 2 | 1 | 0 | +| gul | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gum | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gun | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| guo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gup | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gux | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gvc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gvf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gvn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gvs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gwi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gym | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| gyr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hat | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| hau | 3 | 6 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| haw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hbo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hch | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| heb | 4 | 6 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| heg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hin | 7 | 13 | 1 | 0 | 0 | 1 | 1 | 8 | 1 | 0 | +| hix | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hla | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hlt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hmn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hmo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hne | 2 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hns | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hop | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hot | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hrv | 4 | 4 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | +| hsb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hto | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hub | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hui | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hun | 5 | 4 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | +| hus | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| huu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| huv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hvn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| hye | 3 | 4 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | +| ian | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ibo | 2 | 6 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| ido | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ign | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ikk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ikw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ile | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ilo | 2 | 2 | 1 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| imo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ina | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| inb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ind | 4 | 8 | 0 | 0 | 0 | 1 | 0 | 1 | 0 | 0 | +| ino | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| iou | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ipi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| isl | 3 | 5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| isn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ita | 5 | 10 | 0 | 0 | 1 | 2 | 1 | 5 | 3 | 0 | +| iws | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ixl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jac | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jae | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jao | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jav | 2 | 6 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| jic | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jid | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jiv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jni | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| jpn | 5 | 9 | 2 | 0 | 0 | 1 | 0 | 5 | 2 | 0 | +| jvn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kab | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kac | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| kam | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kan | 6 | 8 | 1 | 0 | 0 | 1 | 0 | 2 | 1 | 0 | +| kaq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kas | 3 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kat | 4 | 4 | 0 | 0 | 0 | 0 | 0 | 2 | 0 | 0 | +| kaz | 3 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| kbc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kbh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kbm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kbp | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kbq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kdc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kde | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kdl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kea | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| kek | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ken | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kew | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kfg | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kfy | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kgf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kgk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kgp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| khk | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| khm | 3 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| khs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| khz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kik | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kin | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| kir | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| kiw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kiz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kje | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kjs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kkc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kkl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| klt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| klv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmb | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmr | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kms | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kmu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| knc | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kne | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| knf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| knj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| knv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kon | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kor | 4 | 9 | 0 | 0 | 0 | 2 | 0 | 6 | 3 | 0 | +| kos | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kpf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kpg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kpj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kpr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kpw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kpx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kqa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kqc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kqf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kql | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kqw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| krc | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ksd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ksj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ksr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ktm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kto | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kud | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kue | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kup | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kur | 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kvg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kvn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kwd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kwf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kwi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kwj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kyc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kyf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kyg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kyq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kyz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kze | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| kzj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lac | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lao | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| lat | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lav | 1 | 2 | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | +| lbb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lbk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lcm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| leu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lex | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lfn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lgl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lid | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lif | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lij | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lim | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lin | 2 | 3 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| lit | 4 | 2 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | +| llg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lmo | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ltg | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ltz | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lua | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lug | 2 | 3 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| luo | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| lus | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| lvs | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| lww | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| maa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mad | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mag | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mai | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| maj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mal | 7 | 8 | 1 | 0 | 0 | 0 | 0 | 2 | 1 | 0 | +| mam | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| maq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mar | 7 | 7 | 1 | 0 | 0 | 1 | 0 | 2 | 1 | 0 | +| mau | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mav | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| max | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| maz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mbt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mca | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mcb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mcd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mcf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mco | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mcp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mcq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mcr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mdy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| med | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mee | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mek | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| meq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| met | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| meu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mey | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mgc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mgh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mgw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mhl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mhr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mib | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mic | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mie | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mig | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mih | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mil | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| min | 1 | 3 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mio | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mir | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mit | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| miz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mjc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mkd | 3 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| mkj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mkl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mkn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mks | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mle | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mlg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mlh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mlp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mlt | 2 | 3 | 1 | 0 | 2 | 0 | 0 | 1 | 0 | 0 | +| mmo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mmx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mna | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mni | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mon | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mop | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mos | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mox | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mph | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mpj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mpm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mpp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mps | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mpt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mpx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mqb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mqj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mri | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| msa | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| msb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| msc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| msk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| msm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| msy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mti | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mto | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mup | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mux | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| muy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mva | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mvn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mwc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mwe | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mwf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mwp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mwr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mxb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mxp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mxq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mxt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mya | 3 | 5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| myk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| myu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| myw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| myy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| mzz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nab | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| naf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nak | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nas | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nbl | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nbq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nca | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nch | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ncj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ncl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ncu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nde | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ndg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ndj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nds | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nep | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nfa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ngp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ngu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhe | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nho | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nhy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nif | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nii | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nij | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nin | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nko | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nld | 6 | 7 | 0 | 0 | 1 | 0 | 1 | 2 | 2 | 0 | +| nlg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nna | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nno | 5 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nnq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| noa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nob | 5 | 8 | 4 | 0 | 0 | 0 | 0 | 3 | 0 | 0 | +| noe | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nop | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nor | 0 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 | +| not | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nou | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nov | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| npi | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| npl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nqo | 0 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nsn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nso | 2 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| nss | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ntj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ntp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ntu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nus | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nuy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nvm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nwi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nya | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| nys | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| nyu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| obo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| oci | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| okv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| omw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ong | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ons | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ood | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| opm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ori | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| orm | 1 | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| orv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ory | 5 | 5 | 1 | 0 | 0 | 1 | 0 | 2 | 1 | 0 | +| ote | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| otm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| otn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| otq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ots | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pab | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pad | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pag | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pah | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pam | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pan | 6 | 7 | 1 | 0 | 0 | 1 | 0 | 2 | 1 | 0 | +| pao | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pap | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pbt | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| pcm | 0 | 4 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pes | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| pib | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pio | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pir | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| piu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pjt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pls | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| plt | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| plu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pma | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pms | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| poe | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| poh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| poi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pol | 4 | 12 | 3 | 0 | 1 | 4 | 0 | 13 | 4 | 0 | +| pon | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| por | 4 | 10 | 0 | 0 | 2 | 2 | 1 | 5 | 3 | 0 | +| poy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ppo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| prf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pri | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| prs | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ptp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ptu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pus | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| pwg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qub | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| quc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| quf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| quh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qul | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qup | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| quy | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qve | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qvz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qwh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qxh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qxn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| qxo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rai | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| raj | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| reg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rgu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rkb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rmc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rmy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rom | 1 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ron | 5 | 7 | 0 | 0 | 1 | 0 | 1 | 3 | 1 | 0 | +| roo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rop | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| row | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rro | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ruf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rug | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| run | 1 | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| rus | 5 | 7 | 2 | 0 | 0 | 3 | 0 | 6 | 3 | 0 | +| rwo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sab | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sag | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sah | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| san | 5 | 4 | 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | +| sat | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sbe | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sbk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sbs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| scn | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sco | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| seh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sey | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sgb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sgz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| shi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| shj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| shn | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| shp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sim | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sin | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| sja | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| slk | 3 | 4 | 0 | 0 | 1 | 0 | 0 | 2 | 0 | 0 | +| sll | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| slv | 3 | 5 | 0 | 0 | 1 | 0 | 0 | 1 | 0 | 0 | +| smk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| smo | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sna | 2 | 3 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| snc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| snd | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| snn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| snp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| snx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sny | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| som | 3 | 3 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| soq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sot | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| soy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| spa | 4 | 14 | 3 | 0 | 1 | 2 | 1 | 11 | 4 | 0 | +| spl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| spm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| spp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sps | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| spy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sqi | 2 | 2 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| srd | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sri | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| srm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| srn | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| srp | 4 | 2 | 0 | 0 | 0 | 0 | 1 | 2 | 0 | 0 | +| srq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ssd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ssg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ssw | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| ssx | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| stp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sua | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sue | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sun | 1 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| sus | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| suz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| svk | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| swa | 1 | 6 | 2 | 0 | 0 | 1 | 0 | 0 | 0 | 0 | +| swe | 4 | 9 | 2 | 0 | 1 | 1 | 1 | 4 | 0 | 0 | +| swg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| swh | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| swp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| sxb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| szl | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tac | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tah | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| taj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tam | 7 | 8 | 1 | 0 | 0 | 1 | 0 | 3 | 1 | 0 | +| taq | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tat | 3 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tav | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| taw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tbc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tbf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tbg | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tbo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tbz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tca | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tcs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tcz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tdt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tee | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tel | 7 | 8 | 1 | 0 | 0 | 0 | 0 | 2 | 1 | 0 | +| ter | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tet | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tew | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tfr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tgk | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| tgl | 3 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| tgo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tgp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tha | 4 | 9 | 0 | 0 | 0 | 1 | 0 | 3 | 0 | 0 | +| tif | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tim | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tir | 2 | 3 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| tiw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tiy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tke | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tku | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tlf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tmd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tna | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tnc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tnk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tnn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tnp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| toc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tod | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tof | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| toj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ton | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| too | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| top | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tos | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tpa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tpi | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tpt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tpz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| trc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tsn | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| tso | 1 | 5 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| tsw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ttc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tte | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tuc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tue | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tuf | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tuk | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tum | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tuo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tur | 4 | 8 | 0 | 0 | 0 | 2 | 0 | 3 | 2 | 0 | +| tvk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| twi | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| txq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| txu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tyv | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tzj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tzl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tzm | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| tzo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ubr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ubu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| udu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| uig | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ukr | 4 | 3 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| uli | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ulk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| umb | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| upv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ura | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| urb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| urd | 7 | 9 | 1 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | +| uri | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| urt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| urw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| usa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| usp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| uvh | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| uvl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| uzb | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| uzn | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| vec | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ven | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| vid | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| vie | 5 | 7 | 0 | 0 | 0 | 1 | 0 | 5 | 0 | 0 | +| viv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| vmy | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| waj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wal | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wap | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| war | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| wat | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wbi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wbp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wed | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wer | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wim | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wiu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wiv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wln | 0 | 0 | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wmt | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wmw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wnc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wnu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wol | 3 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| wos | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wrk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wro | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wrs | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wsk | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wuu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| wuv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xav | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xbi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xed | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xho | 3 | 4 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| xla | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xnn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xon | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xsi | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xtd | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| xtm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yaa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yad | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yal | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yap | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yaq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yby | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ycn | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ydd | 1 | 2 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yid | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yka | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yle | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yml | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yon | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yor | 3 | 6 | 2 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| yrb | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yre | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yss | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yue | 3 | 3 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yuj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yut | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yuw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| yva | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zaa | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zab | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zac | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zad | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zai | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zaj | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zam | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zao | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zap | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zar | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zas | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zat | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zav | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zaw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zca | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zga | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zho | 2 | 3 | 0 | 0 | 0 | 1 | 0 | 7 | 0 | 0 | +| zia | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ziw | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zlm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zos | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpc | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpl | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpm | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpo | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpu | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpv | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zpz | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zsm | 2 | 2 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| zsr | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| ztq | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zty | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| zul | 2 | 4 | 0 | 0 | 0 | 0 | 0 | 1 | 0 | 0 | +| zyp | 1 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | +| Total | 1363 | 963 | 105 | 3 | 25 | 66 | 28 | 331 | 72 | 2 | + + +
diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTask.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTask.py new file mode 100644 index 0000000000000000000000000000000000000000..a48a258ba78351ec28bfa633729c257ddf58fe3c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTask.py @@ -0,0 +1,238 @@ +from __future__ import annotations + +import logging +import random +from abc import ABC, abstractmethod +from typing import Any, Sequence + +import datasets +import numpy as np +import torch +from datasets import DatasetDict +from sklearn.model_selection import train_test_split +from sklearn.preprocessing import MultiLabelBinarizer + +from mteb.abstasks.TaskMetadata import TaskMetadata +from mteb.encoder_interface import Encoder, EncoderWithQueryCorpusEncode +from mteb.languages import LanguageScripts + +from ..MTEBResults import HFSubset, ScoresDict + +logger = logging.getLogger(__name__) + + +def _multilabel_subsampling( + dataset_dict: datasets.DatasetDict, + seed: int, + splits: list[str] = ["test"], + label: str = "label", + n_samples: int = 2048, +) -> datasets.DatasetDict: + """Startified subsampling for multilabel problems.""" + for split in splits: + labels = dataset_dict[split][label] + encoded_labels = MultiLabelBinarizer().fit_transform(labels) + idxs = np.arange(len(labels)) + try: + idxs, *_ = train_test_split( + idxs, + encoded_labels, + stratify=encoded_labels, + random_state=seed, + train_size=n_samples, + ) + except ValueError: + logger.warn("Couldn't subsample, continuing with full split.") + dataset_dict.update({split: dataset_dict[split].select(idxs)}) + return dataset_dict + + +class AbsTask(ABC): + metadata: TaskMetadata + superseeded_by: None | str = None + + def __init__(self, seed: int = 42, **kwargs: Any): + self.dataset = None + self.data_loaded = False + self.is_multilingual = False + self.is_crosslingual = False + self.save_suffix = kwargs.get("save_suffix", "") + + self.seed = seed + random.seed(self.seed) + np.random.seed(self.seed) + torch.manual_seed(self.seed) + torch.cuda.manual_seed_all(self.seed) + + def check_if_dataset_is_superseeded(self): + """Check if the dataset is superseeded by a newer version""" + if self.superseeded_by: + logger.warning( + f"Dataset '{self.metadata.name}' is superseeded by '{self.superseeded_by}', you might consider using the newer version of the dataset." + ) + + def dataset_transform(self): + """Transform operations applied to the dataset after loading. + Override this method if your dataset requires any transformation. + """ + pass + + def evaluate( + self, + model: Encoder | EncoderWithQueryCorpusEncode, + split: str = "test", + **kwargs: Any, + ) -> dict[HFSubset, ScoresDict]: + """Evaluates a Sentence Embedding Model on the task. + Returns a dict (that can be serialized to json). + + Args: + model: Sentence embedding method. Implements a encode(sentences) method, that encodes sentences and returns a numpy matrix with the + sentence embeddings + split: Which datasplit to be used. + kwargs: Additional keyword arguments that are passed to the _evaluate_subset method. + """ + if not self.data_loaded: + self.load_data() + + self.dataset: dict[HFSubset, DatasetDict] + + scores = {} + hf_subsets = ( + [l for l in self.dataset.keys()] + if self.is_crosslingual or self.is_multilingual + else ["default"] + ) + + for hf_subset in hf_subsets: + logger.info( + f"\nTask: {self.metadata_dict['name']}, split: {split}, subset: {hf_subset}. Running..." + ) + if hf_subset not in self.dataset and hf_subset == "default": + data_split = self.dataset[split] + else: + data_split = self.dataset[hf_subset][split] + scores[hf_subset] = self._evaluate_subset(model, data_split, **kwargs) + return scores + + @abstractmethod + def _evaluate_subset(self, model, data_split, **kwargs) -> ScoresDict: + raise NotImplementedError( + "If you are using the default evaluate method, you must implement _evaluate_subset method." + ) + + @staticmethod + def stratified_subsampling( + dataset_dict: datasets.DatasetDict, + seed: int, + splits: list[str] = ["test"], + label: str = "label", + n_samples: int = 2048, + ) -> datasets.DatasetDict: + """Subsamples the dataset with stratification by the supplied label. + Returns a datasetDict object. + + Args: + dataset_dict: the DatasetDict object. + seed: the random seed. + splits: the splits of the dataset. + label: the label with which the stratified sampling is based on. + n_samples: Optional, number of samples to subsample. Default is max_n_samples. + """ + ## Can only do this if the label column is of ClassLabel. + if not isinstance(dataset_dict[splits[0]].features[label], datasets.ClassLabel): + try: + dataset_dict = dataset_dict.class_encode_column(label) + except ValueError as e: + if isinstance(dataset_dict[splits[0]][label][0], Sequence): + return _multilabel_subsampling( + dataset_dict, seed, splits, label, n_samples + ) + else: + raise e + + for split in splits: + dataset_dict.update( + { + split: dataset_dict[split].train_test_split( + test_size=n_samples, seed=seed, stratify_by_column=label + )["test"] + } + ) ## only take the specified test split. + return dataset_dict + + def load_data(self, **kwargs): + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = datasets.load_dataset(**self.metadata_dict["dataset"]) # type: ignore + self.dataset_transform() + self.data_loaded = True + + @property + def metadata_dict(self) -> dict[str, Any]: + return dict(self.metadata) + + @property + def languages(self) -> list[str]: + """Returns the languages of the task""" + # check if self.hf_subsets is set + has_lang_splits = self.is_crosslingual or self.is_multilingual + if has_lang_splits and hasattr(self, "hf_subsets"): + assert isinstance( + self.metadata.eval_langs, dict + ), "eval_langs must be dict for multilingual tasks" + eval_langs = self.metadata.eval_langs + languages = [] + + for lang in self.hf_subsets: + for langscript in eval_langs[lang]: + iso_lang, script = langscript.split("-") + languages.append(iso_lang) + + return sorted(set(languages)) + + return self.metadata.languages + + def filter_languages( + self, languages: list[str] | None, script: list[str] | None = None + ) -> AbsTask: + """Filter the languages of the task. + + Args: + languages: list of languages to filter the task by can be either a 3-letter langauge code (e.g. "eng") or also include the script + (e.g. "eng-Latn") + script: list of scripts to filter the task by. Will be ignored if language code specified the script. If None, all scripts are included. + If the language code does not specify the script the intersection of the language and script will be used. + """ + lang_scripts = LanguageScripts.from_languages_and_scripts(languages, script) + + subsets_to_keep = [] + + if not isinstance(self.metadata.eval_langs, dict): + self.hf_subsets = self.metadata.eval_langs + return self + + for hf_subset, langs in self.metadata.eval_langs.items(): + for langscript in langs: + if lang_scripts.contains_language( + langscript + ) or lang_scripts.contains_script(langscript): + subsets_to_keep.append(hf_subset) + break + + self.hf_subsets = subsets_to_keep + return self + + def __repr__(self) -> str: + """Format the representation of the task such that it appears as: + + TaskObjectName(name='{name}', languages={lang1, lang2, ...}) + """ + langs = self.languages + if len(langs) > 3: + langs = langs[:3] + langs.append("...") + return ( + f"{self.__class__.__name__}(name='{self.metadata.name}', languages={langs})" + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..b029727fe758f308017003bc542e45be423f2538 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskBitextMining.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import logging + +from datasets import Dataset + +from ..evaluation.evaluators import BitextMiningEvaluator +from ..MTEBResults import HFSubset, ScoresDict +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +class AbsTaskBitextMining(AbsTask): + """Abstract class for BitextMining tasks + The similarity is computed between pairs and the results are ranked. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns: + id: str + sentence1: str + sentence2: str + """ + + parallel_subsets = False + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def evaluate(self, model, split, **kwargs) -> dict[HFSubset, ScoresDict]: + if not self.data_loaded: + self.load_data() + + hf_subsets = ( + [l for l in self.dataset] + if self.is_multilingual or self.is_crosslingual + else ["default"] + ) + + scores = {} + if self.parallel_subsets: + scores["default"] = self._evaluate_subset( + model, self.dataset[split], parallel=True, **kwargs + ) + else: + for hf_subet in hf_subsets: + logger.info( + f"\nTask: {self.metadata_dict['name']}, split: {split}, subset: {hf_subet}. Running..." + ) + + if hf_subet not in self.dataset and hf_subet == "default": + data_split = self.dataset[split] + else: + data_split = self.dataset[hf_subet][split] + scores[hf_subet] = self._evaluate_subset( + model, data_split, subsets=["sentence1", "sentence2"], **kwargs + ) + + return scores + + def _evaluate_subset( + self, model, data_split: Dataset, parallel=False, **kwargs + ) -> ScoresDict: + evaluator = BitextMiningEvaluator(data_split, **kwargs) + metrics = evaluator(model) + if parallel: + for v in metrics.values(): + self._add_main_score(v) + else: + self._add_main_score(metrics) + return metrics + + def _add_main_score(self, scores) -> None: + scores["main_score"] = scores[self.metadata.main_score] diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClassification.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..b2b813964e53f95d93eef6e8394066464afaa417 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClassification.py @@ -0,0 +1,164 @@ +from __future__ import annotations + +import logging +from collections import defaultdict +from typing import Any + +import numpy as np + +from ..evaluation.evaluators import ( + kNNClassificationEvaluator, + kNNClassificationEvaluatorPytorch, + logRegClassificationEvaluator, +) +from ..MTEBResults import HFSubset, ScoresDict +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +class AbsTaskClassification(AbsTask): + """Abstract class for kNN classification tasks + The similarity is computed between pairs and the results are ranked. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It + must contain the following columns: + text: str + label: int + """ + + def __init__( + self, + method: str = "logReg", + n_experiments: int | None = None, + samples_per_label: int | None = None, + k: int = 3, + batch_size: int = 32, + **kwargs, + ): + super().__init__(**kwargs) + self.batch_size = batch_size + self.method = method + + # Bootstrap parameters + self.n_experiments: int = ( # type: ignore + n_experiments + if n_experiments is not None + else self.metadata_dict.get("n_experiments", 10) + ) + self.samples_per_label: int = ( # type: ignore + samples_per_label + if samples_per_label is not None + else self.metadata_dict.get("samples_per_label", 8) + ) + + # kNN parameters + self.k = k + + # Run metadata validation by instantiating addressing the attribute + # This is quite hacky. Ideally, this would be done in the constructor of + # each concrete task, but then we have to duplicate the __init__ method's + # interface. + if hasattr(self, "metadata"): + self.metadata + + def _add_main_score(self, scores: dict[HFSubset, ScoresDict]) -> None: + scores["main_score"] = scores[self.metadata.main_score] + + def evaluate( + self, model, eval_split="test", train_split="train", **kwargs + ) -> dict[HFSubset, ScoresDict]: + if not self.data_loaded: + self.load_data() + + scores = {} + hf_subsets = [l for l in self.dataset] if self.is_multilingual else ["default"] + + for hf_subset in hf_subsets: + logger.info( + f"\nTask: {self.metadata.name}, split: {eval_split}, subset: {hf_subset}. Running..." + ) + + if hf_subset not in self.dataset and hf_subset == "default": + ds = self.dataset + else: + ds = self.dataset[hf_subset] + scores[hf_subset] = self._evaluate_subset( + model, ds, eval_split, train_split, **kwargs + ) + self._add_main_score(scores[hf_subset]) + + return scores + + def _evaluate_subset( + self, model, dataset, eval_split="test", train_split="train", **kwargs + ) -> ScoresDict: + train_split = dataset[train_split] + eval_split = dataset[eval_split] + params = {"k": self.k, "batch_size": self.batch_size} + params.update(kwargs) + + scores = [] + test_cache, idxs = ( + None, + None, + ) # we store idxs to make the shuffling reproducible + for i in range(self.n_experiments): + logger.info( + "=" * 10 + f" Experiment {i+1}/{self.n_experiments} " + "=" * 10 + ) + # Bootstrap `self.samples_per_label` samples per label for each split + X_sampled, y_sampled, idxs = self._undersample_data( + train_split["text"], train_split["label"], self.samples_per_label, idxs + ) + + if self.method == "kNN": + evaluator = kNNClassificationEvaluator( + X_sampled, + y_sampled, + eval_split["text"], + eval_split["label"], + **params, + ) + elif self.method == "kNN-pytorch": + evaluator = kNNClassificationEvaluatorPytorch( + X_sampled, + y_sampled, + eval_split["text"], + eval_split["label"], + **params, + ) + elif self.method == "logReg": + evaluator = logRegClassificationEvaluator( + X_sampled, + y_sampled, + eval_split["text"], + eval_split["label"], + **params, + ) + else: + raise ValueError(f"Method {self.method} not supported") + + scores_exp, test_cache = evaluator(model, test_cache=test_cache) + scores.append(scores_exp) + + avg_scores: dict[str, Any] = { + k: np.mean([s[k] for s in scores]) for k in scores[0].keys() + } + avg_scores["scores_per_experiment"] = scores + return avg_scores + + def _undersample_data(self, X, y, samples_per_label: int, idxs=None): + """Undersample data to have samples_per_label samples of each label""" + X_sampled = [] + y_sampled = [] + if idxs is None: + idxs = np.arange(len(y)) + np.random.shuffle(idxs) + label_counter = defaultdict(int) + for i in idxs: + if label_counter[y[i]] < samples_per_label: + X_sampled.append(X[i]) + y_sampled.append(y[i]) + label_counter[y[i]] += 1 + return X_sampled, y_sampled, idxs diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClustering.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClustering.py new file mode 100644 index 0000000000000000000000000000000000000000..2512b90f16d4a9f6b15d7ce066885433052ca556 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClustering.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +import logging + +import numpy as np +import tqdm +from datasets import Dataset + +from mteb.encoder_interface import Encoder, EncoderWithQueryCorpusEncode +from mteb.MTEBResults import ScoresDict + +from ..evaluation.evaluators import ClusteringEvaluator +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +class AbsTaskClustering(AbsTask): + """Abstract class for Clustering tasks + The similarity is computed between pairs and the results are ranked. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns: + sentences: list of str + labels: list of str + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def _add_main_score(self, scores) -> None: + scores["main_score"] = scores[self.metadata.main_score] + + def _evaluate_subset( + self, model: EncoderWithQueryCorpusEncode | Encoder, dataset: Dataset, **kwargs + ) -> ScoresDict: + v_measures = [] + for cluster_set in tqdm.tqdm(dataset, desc="Clustering"): + evaluator = ClusteringEvaluator( + cluster_set["sentences"], # type: ignore + cluster_set["labels"], # type: ignore + **kwargs, + ) + metrics = evaluator(model) + v_measures.append(metrics["v_measure"]) + + v_mean = np.mean(v_measures) + v_std = np.std(v_measures) + scores = {"v_measure": v_mean, "v_measure_std": v_std, "v_measures": v_measures} + self._add_main_score(scores) + return scores diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClusteringFast.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClusteringFast.py new file mode 100644 index 0000000000000000000000000000000000000000..ceb8d24595d5e1fb739f6cd6c18c6d6f4900cd4f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskClusteringFast.py @@ -0,0 +1,217 @@ +from __future__ import annotations + +import itertools +import logging +import random +from collections import defaultdict +from typing import Any, Dict, Optional + +import numpy as np +import sklearn +import sklearn.cluster +from datasets import Dataset, DatasetDict +from sklearn.metrics.cluster import v_measure_score + +from ..MTEBResults import HFSubset +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +MultilingualDataset = Dict[HFSubset, DatasetDict] + + +def evaluate_clustering_bootstrapped( + embeddings: np.ndarray, + labels: list[list[str]], + n_clusters: int, + cluster_size: int, + kmean_batch_size: int, + max_depth: Optional[int], + rng_state: random.Random = random.Random(), +) -> dict[str, list[float]]: + """Bootstrapped evaluation of clustering performance using V-measure. + + The bootstrapping is done by sampling N samples from the corpus and clustering them. It is done without replacement to get a diverse set of + samples. + """ + n_embeddings = embeddings.shape[0] + + v_measures = defaultdict(list) + if max_depth is not None: + max_depth = min(max_depth, max(map(len, labels))) + else: + max_depth = max(map(len, labels)) + # Evaluate on each level til max depth + for i_level in range(max_depth): + level_labels = [] + # Assign -1 to gold label if the level is not there + for label in labels: + if len(label) > i_level: + level_labels.append(label[i_level]) + else: + level_labels.append(-1) + level_labels = np.array(level_labels) + valid_idx = level_labels != -1 + level_labels = level_labels[valid_idx] + level_embeddings = embeddings[valid_idx] + clustering_model = sklearn.cluster.MiniBatchKMeans( + n_clusters=len(set(level_labels)), + batch_size=kmean_batch_size, + n_init="auto", + ) + for _ in range(n_clusters): + # sample N samples from the corpus with replacement + n_embeddings = len(level_embeddings) + cluster_indices = rng_state.choices(range(n_embeddings), k=cluster_size) + + _embeddings = level_embeddings[cluster_indices] + _labels = level_labels[cluster_indices] + cluster_assignment = clustering_model.fit_predict(_embeddings) + v_measure = v_measure_score(_labels, cluster_assignment) + v_measures[f"Level {i_level}"].append(v_measure) + + return v_measures + + +class AbsTaskClusteringFast(AbsTask): + """Abstract class for Clustering tasks. + + This class embeds the corpus sentences then samples N samples from the corpus and clusters them. + The similarity then is calculated using the V-measure metric, which is invariant to the permutation of the labels. + This approach is then repeated K times. + + If the clustering is hieararchical, and more than one label is specified in order for each observation, + V-measures are calculated in the outlined way on each of the levels separately. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. + It must contain the following columns: + sentences: list[str] + labels: list[str] | list[list[str]] + """ + + max_documents_to_embed = 16_384 + max_documents_per_cluster = 2048 + n_clusters = 10 + k_mean_batch_size = 512 + max_depth = None + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def _add_main_score(self, scores): + if self.metadata_dict["main_score"] in scores: + scores["main_score"] = scores[self.metadata_dict["main_score"]] + else: + logger.warn( + f"main score {self.metadata_dict['main_score']} not found in scores {scores.keys()}" + ) + + def _evaluate_subset( + self, model, dataset: DatasetDict, **kwargs: Any + ) -> dict[str, float | dict[str, list[float]]]: + rng_state = random.Random(self.seed) + + if len(dataset) > self.max_documents_to_embed: + example_indices = rng_state.sample( + range(len(dataset)), k=self.max_documents_to_embed + ) + downsampled_dataset = dataset.select(example_indices) + else: + downsampled_dataset = dataset + + logger.info(f"Encoding {len(downsampled_dataset)} sentences...") + + embeddings = model.encode(downsampled_dataset["sentences"]) + labels = [] + for label in downsampled_dataset["labels"]: + if not isinstance(label, list): + label = [label] + labels.append(label) + + v_measures = evaluate_clustering_bootstrapped( + embeddings, + labels, + n_clusters=self.n_clusters, + cluster_size=self.max_documents_per_cluster, + kmean_batch_size=self.k_mean_batch_size, + max_depth=self.max_depth, + rng_state=rng_state, + ) + all_v_scores = itertools.chain.from_iterable(v_measures.values()) + mean_v_measure = np.mean(list(all_v_scores)) + scores = {"v_measures": v_measures, "v_measure": float(mean_v_measure)} + self._add_main_score(scores) + return scores + + +def clustering_downsample( + dataset: DatasetDict, seed: int, max_samples_in_cluster: int = 2048 +) -> DatasetDict: + """In cases where it is not possible to convert the dataset to a fast version, we can downsample the dataset to speed up the evaluation. + + This might be necessary when the clusters in the dataset is not sampled from the same distribution. + """ + rng_state = random.Random(seed) + + ds = {} + for split in dataset: + _docs = [] + _labels = [] + + n_clusters = len(dataset[split]) + + for i in range(n_clusters): + labels = dataset[split]["labels"][i] + sentences = dataset[split]["sentences"][i] + + n_sample = min(max_samples_in_cluster, len(sentences)) + + # sample n_sample from each cluster + idxs = rng_state.sample(range(len(sentences)), n_sample) + _docs.append([sentences[idx] for idx in idxs]) + _labels.append([labels[idx] for idx in idxs]) + + ds[split] = Dataset.from_dict({"sentences": _docs, "labels": _labels}) + return DatasetDict(ds) + + +def convert_to_fast( + dataset: DatasetDict, seed: int, max_size: int = 100_000 +) -> DatasetDict: + """Converts a clustering dataset to a fast version. This concats the cluster into two columns, sentences and labels. + It additionally downsamples the dataset to max_size. + """ + categories = None + rng_state = random.Random(seed) + + ds = {} + for split in dataset: + sent_set = set() + labels = [] + sentences = [] + n_clusters = len(dataset[split]) + for i in range(n_clusters): + lab = dataset[split]["labels"][i] + sents = dataset[split]["sentences"][i] + for l, s in zip(lab, sents): + if s not in sent_set: + labels.append(l) + sentences.append(s) + sent_set.add(s) # ensuring no duplicates + + # check that it is the same distribution + if categories is None: + categories = set(labels) + else: + assert ( + categories == set(labels) + ), "The clusters are not sampled from the same distribution as they have different labels." + + ds[split] = Dataset.from_dict({"sentences": sentences, "labels": labels}) + + if len(ds[split]) > max_size: + idxs = rng_state.sample(range(len(ds[split])), max_size) + ds[split] = ds[split].select(idxs) + + return DatasetDict(ds) diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskInstructionRetrieval.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskInstructionRetrieval.py new file mode 100644 index 0000000000000000000000000000000000000000..dbcead59c47096cd56c7190708735a741a8bc3fe --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskInstructionRetrieval.py @@ -0,0 +1,656 @@ +import json +import logging +import os +from collections import defaultdict +from time import time +from typing import Dict, List, Tuple + +import tqdm +from datasets import Features, Value, load_dataset + +from ..evaluation.evaluators import utils +from ..evaluation.evaluators.InstructionRetrievalEvaluator import ( + InstructionRetrievalEvaluator, +) +from .AbsTask import AbsTask +from .AbsTaskRetrieval import HFDataLoader + +logger = logging.getLogger(__name__) + + +# Adapted from https://github.com/beir-cellar/beir/blob/f062f038c4bfd19a8ca942a9910b1e0d218759d4/beir/datasets/data_loader_hf.py#L10 +class HFDataLoaderInstructions(HFDataLoader): + def __init__( + self, + hf_repo: str = None, + hf_repo_qrels: str = None, + data_folder: str = None, + prefix: str = None, + corpus_file: str = "corpus.jsonl", + query_file: str = "queries.jsonl", + qrels_folder: str = "qrels", + qrels_file: str = "", + streaming: bool = False, + keep_in_memory: bool = False, + ): + self.corpus = {} + self.queries = {} + self.qrels = {} + self.og_instructions = {} + self.changed_instructions = {} + self.top_ranked = {} + self.hf_repo = hf_repo + if hf_repo: + # By default fetch qrels from same repo not a second repo with "-qrels" like in original + self.hf_repo_qrels = hf_repo_qrels if hf_repo_qrels else hf_repo + else: + # data folder would contain these files: + # (1) fiqa/corpus.jsonl (format: jsonlines) + # (2) fiqa/queries.jsonl (format: jsonlines) + # (3) fiqa/qrels/test.tsv (format: tsv ("\t")) + if prefix: + query_file = prefix + "-" + query_file + qrels_folder = prefix + "-" + qrels_folder + + self.corpus_file = ( + os.path.join(data_folder, corpus_file) if data_folder else corpus_file + ) + self.query_file = ( + os.path.join(data_folder, query_file) if data_folder else query_file + ) + self.qrels_folder = ( + os.path.join(data_folder, qrels_folder) if data_folder else None + ) + self.qrels_file = qrels_file + self.streaming = streaming + self.keep_in_memory = keep_in_memory + + def load( + self, split="test" + ) -> Tuple[ + Dict[str, Dict[str, str]], + Dict[str, str], + Dict[str, Dict[str, int]], + Dict[str, Dict[str, int]], + ]: + if not self.hf_repo: + self.og_qrels_file = os.path.join(self.qrels_folder + "_og", split + ".tsv") + self.changed_qrels_file = os.path.join( + self.qrels_folder + "_changed", split + ".tsv" + ) + self.check(fIn=self.corpus_file, ext="jsonl") + self.check(fIn=self.query_file, ext="jsonl") + self.check(fIn=self.og_qrels_file, ext="tsv") + self.check(fIn=self.changed_qrels_file, ext="tsv") + + if not len(self.corpus): + logger.info("Loading Corpus...") + self._load_corpus() + logger.info("Loaded %d %s Documents.", len(self.corpus), split.upper()) + logger.info("Doc Example: %s", self.corpus[0]) + + if not len(self.queries): + logger.info("Loading Queries...") + self._load_queries() + + self._load_qrels(split, changed=False) + self._load_qrels(split, changed=True) + # filter queries with no qrels + og_qrels_dict = defaultdict(dict) + changed_qrels_dict = defaultdict(dict) + + def qrels_dict_init(row): + og_qrels_dict[row["query-id"]][row["corpus-id"]] = int(row["score"]) + + def qrels_changed_dict_init(row): + changed_qrels_dict[row["query-id"]][row["corpus-id"]] = int(row["score"]) + + self.changed_qrels.map(qrels_dict_init) + self.og_qrels.map(qrels_changed_dict_init) + self.og_qrels = og_qrels_dict + self.changed_qrels = changed_qrels_dict + self.queries = self.queries.filter(lambda x: x["id"] in self.og_qrels) + logger.info("Loaded %d %s Queries.", len(self.queries), split.upper()) + logger.info("Query Example: %s", self.queries[0]) + + # load top_ranked + self.load_top_ranked() + + return ( + self.corpus, + self.queries, + self.og_qrels, + self.changed_qrels, + self.top_ranked, + ) + + def load_top_ranked(self) -> None: + if self.hf_repo: + top_ranked_ds = load_dataset( + self.hf_repo, + "top_ranked", + keep_in_memory=self.keep_in_memory, + streaming=self.streaming, + ) + else: + top_ranked_ds = load_dataset( + "json", + data_files=self.top_ranked_file, + streaming=self.streaming, + keep_in_memory=self.keep_in_memory, + ) + top_ranked_ds = next(iter(top_ranked_ds.values())) # get first split + top_ranked_ds = top_ranked_ds.cast_column("qid", Value("string")) + top_ranked_ds = top_ranked_ds.cast_column("pid", Value("string")) + top_ranked_ds = top_ranked_ds.remove_columns( + [col for col in top_ranked_ds.column_names if col not in ["qid", "pid"]] + ) + self.top_ranked = top_ranked_ds + + def _load_queries(self): + if self.hf_repo: + queries_ds = load_dataset( + self.hf_repo, + "queries", + keep_in_memory=self.keep_in_memory, + streaming=self.streaming, + ) + else: + queries_ds = load_dataset( + "json", + data_files=self.query_file, + streaming=self.streaming, + keep_in_memory=self.keep_in_memory, + ) + queries_ds = next(iter(queries_ds.values())) # get first split + queries_ds = queries_ds.cast_column("_id", Value("string")) + queries_ds = queries_ds.rename_column("_id", "id") + queries_ds = queries_ds.remove_columns( + [ + col + for col in queries_ds.column_names + if col + not in [ + "id", + "text", + "instruction_og", + "instruction_changed", + "keywords", + "short_query", + ] + ] + ) + self.queries = queries_ds + + def _load_qrels(self, split, changed=False): + if self.hf_repo: + qrels_ds = load_dataset( + self.hf_repo_qrels, + "qrels_og" if not changed else "qrels_changed", + keep_in_memory=self.keep_in_memory, + streaming=self.streaming, + )[split] + else: + qrels_file = self.og_qrels_file if not changed else self.changed_qrels_file + qrels_ds = load_dataset( + "csv", + data_files=qrels_file, + delimiter="\t", + keep_in_memory=self.keep_in_memory, + ) + features = Features( + { + "query-id": Value("string"), + "corpus-id": Value("string"), + "score": Value("float"), + } + ) + qrels_ds = qrels_ds.cast(features) + + if changed: + self.changed_qrels = qrels_ds + else: + self.og_qrels = qrels_ds + + +class AbsTaskInstructionRetrieval(AbsTask): + """Abstract class for retrieval tasks that use instructions. An example from Core17 would be + query: What is the ongoing status of The Three Gorges Project? + instruction: A relevant document will provide the projected or actual date of completion of the project, its estimated or actual total cost, or the estimated or ongoing electrical output of the finished project. Discussions of the social, political, or ecological impact of the project are not relevant. + + Child-classes must implement the following properties: + self.corpus = Dict[id, Dict[str, str]] #id => dict with document datas like title and text + self.queries = Dict[id, str] #id => query + self.relevant_docs = List[id, id, score] + self.og_instructions = Dict[str, str] query => original instruction + self.changed_instructions = Dict[str, str] query => changed instruction + self.top_ranked = Dict[id, List[id]] #id => list of top ranked document ids + + See https://arxiv.org/abs/2403.15246 for more details + """ + + def __init__( + self, + hf_repo: str = None, + hf_repo_qrels: str = None, + data_folder: str = None, + prefix: str = None, + corpus_file: str = "corpus.jsonl", + query_file: str = "queries.jsonl", + qrels_folder: str = "qrels", + qrels_file: str = "", + streaming: bool = False, + keep_in_memory: bool = False, + **kwargs, + ): + super().__init__(**kwargs) + self.do_length_ablation = kwargs.get("do_length_ablation", False) + if self.do_length_ablation: + logger.info("Running length ablation also...") + + def load_data(self, **kwargs): + if self.data_loaded: + return + self.corpus, self.queries, self.og_relevant_docs, self.changed_relevant_docs = ( + {}, + {}, + {}, + {}, + ) + self.og_instructions, self.changed_instructions = {}, {} + self.top_ranked = {} + if self.do_length_ablation: + self.keywords, self.short_instructions = {}, {} + + dataset_path = self.metadata_dict["dataset"]["path"] + hf_repo_qrels = ( + dataset_path + "-qrels" if "clarin-knext" in dataset_path else None + ) + for split in kwargs.get("eval_splits", self.metadata_dict["eval_splits"]): + corpus, queries, og_qrels, changed_qrels, top_ranked_init = ( + HFDataLoaderInstructions( + hf_repo=dataset_path, + hf_repo_qrels=hf_repo_qrels, + streaming=False, + keep_in_memory=False, + ).load(split=split) + ) + + # Conversion from DataSet + top_ranked = defaultdict(list) + [ + top_ranked[cur_inst["qid"]].append(cur_inst["pid"]) + for cur_inst in top_ranked_init + ] + og_instructions = { + query["text"]: query["instruction_og"] for query in queries + } + changed_instructions = { + query["text"]: query["instruction_changed"] for query in queries + } + if self.do_length_ablation: + keywords = {query["text"]: query["keywords"] for query in queries} + short_instructions = { + query["text"]: query["short_query"] for query in queries + } + queries = {query["id"]: query["text"] for query in queries} + corpus = { + doc["id"]: {"title": doc["title"], "text": doc["text"]} + for doc in corpus + } + assert ( + len(top_ranked) == len(queries) + ), f"Top ranked not loaded properly! Expected {len(self.queries)} but got {len(self.top_ranked)}." + + ( + self.corpus[split], + self.queries[split], + self.og_relevant_docs[split], + self.changed_relevant_docs[split], + ) = corpus, queries, og_qrels, changed_qrels + self.changed_instructions[split], self.og_instructions[split] = ( + changed_instructions, + og_instructions, + ) + self.top_ranked[split] = top_ranked + + if self.do_length_ablation: + self.keywords[split], self.short_instructions[split] = ( + keywords, + short_instructions, + ) + + self.data_loaded = True + + def evaluate(self, model, split="test", **kwargs): + retriever = InstructionRetrievalEvaluator(model, **kwargs) + + scores_og = {} + scores_changed = {} + results_og = {} + results_changed = {} + scores_base = {} + results_base = {} + overall_changed_scores = {} + if self.is_multilingual: + for lang in self.hf_subsets: + logger.info(f"Language: {lang}") + corpus, queries = self.corpus[lang][split], self.queries[lang][split] + og_relevant_docs, changed_relevant_docs = ( + self.og_relevant_docs[lang][split], + self.changed_relevant_docs[lang][split], + ) + og_instructions, changed_instructions = ( + self.og_instructions[lang][split], + self.changed_instructions[lang][split], + ) + + top_ranked = self.top_ranked[lang][split] + scores_og[lang], results_og[lang] = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + og_instructions, + top_ranked, + lang, + **kwargs, + ) + scores_changed[lang], results_changed[lang] = self._evaluate_subset( + retriever, + corpus, + queries, + changed_relevant_docs, + changed_instructions, + top_ranked, + lang, + **kwargs, + ) + + newly_irrelevant_qrels = self.create_qrel_diff( + self.og_relevant_docs[lang][split], + self.changed_relevant_docs[lang][split], + ) + overall_changed_scores[lang] = utils.evaluate_change( + results_og[lang], results_changed[lang], newly_irrelevant_qrels + ) + + overall_changed_scores[lang]["individual"] = { + "original": scores_og[lang], + "changed": scores_changed[lang], + } + + if self.do_length_ablation: + keywords, short_instructions = ( + self.keywords[lang][split], + self.short_instructions[lang][split], + ) + scores_base[lang], results_base[lang] = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + defaultdict(str), + top_ranked, + lang, + **kwargs, + ) + scores_w_keywords = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + keywords, + top_ranked, + lang, + **kwargs, + ) + scores_w_short_instr = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + short_instructions, + top_ranked, + lang, + **kwargs, + ) + overall_changed_scores[lang]["length_ablation"] = { + "keywords": scores_w_keywords, + "short_instructions": scores_w_short_instr, + "base": scores_base[lang], + } + else: # seems like these two can be combined into one (with the new lang="default") + lang = "default" + corpus, queries = self.corpus[split], self.queries[split] + og_relevant_docs, changed_relevant_docs = ( + self.og_relevant_docs[split], + self.changed_relevant_docs[split], + ) + og_instructions, changed_instructions = ( + self.og_instructions[split], + self.changed_instructions[split], + ) + top_ranked = self.top_ranked[split] + + scores_og, results_og = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + og_instructions, + top_ranked, + None, + **kwargs, + ) + + scores_changed, results_changed = self._evaluate_subset( + retriever, + corpus, + queries, + changed_relevant_docs, + changed_instructions, + top_ranked, + None, + **kwargs, + ) + + newly_irrelevant_qrels = self.create_qrel_diff( + self.og_relevant_docs[split], self.changed_relevant_docs[split] + ) + overall_changed_scores[lang] = utils.evaluate_change( + results_og, results_changed, newly_irrelevant_qrels + ) + + overall_changed_scores[lang]["individual"] = { + "original": scores_og, + "changed": scores_changed, + } + + if self.do_length_ablation: + keywords, short_instructions = ( + self.keywords[split], + self.short_instructions[split], + ) + scores_w_keywords = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + keywords, + top_ranked, + None, + **kwargs, + ) + scores_w_short_instr = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + short_instructions, + top_ranked, + None, + **kwargs, + ) + scores_base, results_base = self._evaluate_subset( + retriever, + corpus, + queries, + og_relevant_docs, + defaultdict(str), + top_ranked, + None, + **kwargs, + ) + overall_changed_scores[lang]["length_ablation"] = { + "keywords": scores_w_keywords, + "short_instructions": scores_w_short_instr, + "base": scores_base, + } + + return overall_changed_scores + + def _evaluate_subset( + self, + retriever: InstructionRetrievalEvaluator, + corpus: Dict[str, Dict[str, str]], + queries: Dict[str, str], + relevant_docs: Dict[str, Dict[str, int]], + instructions: Dict[str, str], + top_ranked: Dict[str, List[str]], + lang=None, + **kwargs, + ): + start_time = time() + + # do the results by query and relevant docs only + all_results = [] + for query_id in tqdm.tqdm(list(queries.keys()), leave=False, desc="Retrieving"): + cur_queries = {query_id: queries[query_id]} + cur_instructions = {queries[query_id]: instructions[queries[query_id]]} + cur_docs = { + key: value + for (key, value) in corpus.items() + if key in top_ranked[query_id] + } + all_results.append( + retriever( + cur_docs, cur_queries, instructions=cur_instructions, qid=query_id + ) + ) + + # combine all the results (which are {'qid' -> {'doc_id' -> score} mappings) + # we know all are unique qids, so we can smash together + results = {k: v for d in all_results for k, v in d.items()} + + end_time = time() + logger.info( + "Time taken to retrieve: {:.2f} seconds".format(end_time - start_time) + ) + + if kwargs.get("save_predictions", False): + output_folder = kwargs.get("output_folder", "results") + if not os.path.isdir(output_folder): + os.makedirs(output_folder) + top_k = kwargs.get("top_k", None) + if top_k is not None: + for qid in list(results.keys()): + doc_ids = set( + sorted( + results[qid], key=lambda x: results[qid][x], reverse=True + )[:top_k] + ) + results[qid] = { + k: v for k, v in results[qid].items() if k in doc_ids + } + if lang is None: + qrels_save_path = ( + f"{output_folder}/{self.metadata_dict['name']}_predictions.json" + ) + else: + qrels_save_path = f"{output_folder}/{self.metadata_dict['name']}_{lang}_predictions.json" + + with open(qrels_save_path, "w") as f: + json.dump(results, f) + + ndcg, _map, recall, precision = retriever.evaluate( + relevant_docs, + results, + retriever.k_values, + ignore_identical_ids=kwargs.get("ignore_identical_ids", True), + ) + mrr = retriever.evaluate_custom( + relevant_docs, results, retriever.k_values, "mrr" + ) + scores = { + **{f"ndcg_at_{k.split('@')[1]}": v for (k, v) in ndcg.items()}, + **{f"map_at_{k.split('@')[1]}": v for (k, v) in _map.items()}, + **{f"recall_at_{k.split('@')[1]}": v for (k, v) in recall.items()}, + **{f"precision_at_{k.split('@')[1]}": v for (k, v) in precision.items()}, + **{f"mrr_at_{k.split('@')[1]}": v for (k, v) in mrr.items()}, + } + return scores, results + + def create_qrel_diff(self, og_qrels, changed_qrels): + newly_irrelevant_qrels = {} + for qid in og_qrels: + newly_irrelevant_qrels[qid] = [] + for doc_id in og_qrels[qid]: + if changed_qrels[qid][doc_id] != og_qrels[qid][doc_id]: + newly_irrelevant_qrels[qid].append(doc_id) + + return newly_irrelevant_qrels + + def calculate_metadata_metrics(self) -> None: + self.load_data() + + for split in self.metadata_dict["eval_splits"]: + if self.is_multilingual: + for lang in self.og_relevant_docs.keys(): + process_language( + self.og_relevant_docs[lang][split], + self.queries[lang][split], + self.corpus[lang][split], + self.changed_instructions[lang][split], + lang, + ) + else: + process_language( + self.og_relevant_docs[split], + self.queries[split], + self.corpus[split], + self.changed_instructions[split], + ) + + +def process_language(relevant_docs, queries, corpus, instructions, lang=None): + total_length, num_pairs = calculate_length_and_count( + relevant_docs, queries, corpus, instructions + ) + average_length = total_length / num_pairs if num_pairs else 0 + num_documents = len(queries) + len(corpus) + + language_description = f" for language {lang}" if lang else "" + print( + f"Average character length for changed{language_description} is {average_length}" + ) + print( + f"Number of queries and documents{language_description} is {num_documents} (repeated 2x)" + ) + + +def calculate_length_and_count(relevant_docs, queries, corpus, instructions): + total_length = 0 + num_pairs = 0 + for query_id, docs in relevant_docs.items(): + query = queries[query_id] + query += " " + instructions[query] + for doc_id in docs: + # not relevant + if docs[doc_id] == 0: + continue + doc = corpus[doc_id] + doc_text = doc["title"] + doc["text"] + total_length += len(query) + len(doc_text) + num_pairs += 1 + return total_length, num_pairs diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskMultilabelClassification.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskMultilabelClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..9ea5b82b277ba2aeeadcdf4be2bf1452b076888e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskMultilabelClassification.py @@ -0,0 +1,173 @@ +from __future__ import annotations + +import itertools +import logging +from collections import defaultdict +from typing import Any + +import numpy as np +from sklearn.base import ClassifierMixin, clone +from sklearn.metrics import f1_score, label_ranking_average_precision_score +from sklearn.model_selection import train_test_split +from sklearn.neighbors import KNeighborsClassifier +from sklearn.preprocessing import MultiLabelBinarizer + +from ..MTEBResults import HFSubset, ScoresDict +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +def evaluate_classifier( + embeddings_train: np.ndarray, + y_train: np.ndarray, + embeddings_test: np.ndarray, + y_test: np.ndarray, + classifier: ClassifierMixin, +): + scores = {} + classifier = clone(classifier) + classifier.fit(embeddings_train, y_train) + y_pred = classifier.predict(embeddings_test) + accuracy = classifier.score(embeddings_test, y_test) + f1 = f1_score(y_test, y_pred, average="macro") + scores["accuracy"] = accuracy + scores["f1"] = f1 + lrap = label_ranking_average_precision_score(y_test, y_pred) + scores["lrap"] = lrap + return scores + + +class AbsTaskMultilabelClassification(AbsTask): + """Abstract class for multioutput classification tasks + The similarity is computed between pairs and the results are ranked. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns: + text: str + label: list[Hashable] + """ + + classifier = KNeighborsClassifier(n_neighbors=5) + + def __init__( + self, + n_experiments=None, + samples_per_label=None, + batch_size=32, + **kwargs, + ): + super().__init__(**kwargs) + self.batch_size = batch_size + + # Bootstrap parameters + self.n_experiments = n_experiments or getattr(self, "n_experiments", 10) + self.samples_per_label = samples_per_label or getattr( + self, "samples_per_label", 8 + ) + # Run metadata validation by instantiating addressing the attribute + # This is quite hacky. Ideally, this would be done in the constructor of + # each concrete task, but then we have to duplicate the __init__ method's + # interface. + if hasattr(self, "metadata"): + self.metadata + + def _add_main_score(self, scores): + scores["main_score"] = scores[self.metadata.main_score] + + def evaluate( + self, model, eval_split="test", train_split="train", **kwargs + ) -> dict[HFSubset, ScoresDict]: + if not self.data_loaded: + self.load_data() + + scores = {} + hf_subsets = [l for l in self.dataset] if self.is_multilingual else ["default"] + + for hf_subset in hf_subsets: + logger.info( + f"\nTask: {self.metadata.name}, split: {eval_split}, subset: {hf_subset}. Running..." + ) + + if hf_subset not in self.dataset and hf_subset == "default": + ds = self.dataset + else: + ds = self.dataset[hf_subset] + scores[hf_subset] = self._evaluate_subset( + model, ds, eval_split, train_split, **kwargs + ) + self._add_main_score(scores[hf_subset]) + + return scores + + def _evaluate_subset( + self, model, dataset, eval_split="test", train_split="train", **kwargs + ) -> ScoresDict: + train_split = dataset[train_split] + eval_split = dataset[eval_split] + params = { + "classifier_type": type(self.classifier).__name__, + "classifier_params": self.classifier.get_params(), + "batch_size": self.batch_size, + } + params.update(kwargs) + + scores = [] + # Bootstrap sample indices from training set for each experiment + train_samples = [] + for _ in range(self.n_experiments): + sample_indices, _ = self._undersample_data_indices( + train_split["label"], self.samples_per_label, None + ) + train_samples.append(sample_indices) + # Encode all unique sentences at the indices + unique_train_indices = list(set(itertools.chain.from_iterable(train_samples))) + unique_train_sentences = train_split.select(unique_train_indices)["text"] + unique_train_embeddings = dict( + zip(unique_train_indices, model.encode(unique_train_sentences)) + ) + test_text = eval_split["text"] + binarizer = MultiLabelBinarizer() + y_test = binarizer.fit_transform(eval_split["label"]) + # Stratified subsampling of test set to 2000 examples. + try: + if len(test_text) > 2000: + test_text, _, y_test, _ = train_test_split( + test_text, y_test, stratify=y_test, train_size=2000 + ) + except ValueError: + logger.warn("Couldn't subsample, continuing with the entire test set.") + X_test = model.encode(test_text) + for i_experiment, sample_indices in enumerate(train_samples): + logger.info( + "=" * 10 + + f" Experiment {i_experiment+1}/{self.n_experiments} " + + "=" * 10 + ) + X_train = np.stack([unique_train_embeddings[idx] for idx in sample_indices]) + y_train = train_split.select(sample_indices)["label"] + y_train = binarizer.transform(y_train) + scores_exp = evaluate_classifier( + X_train, y_train, X_test, y_test, self.classifier + ) + scores.append(scores_exp) + + avg_scores: dict[str, Any] = { + k: np.mean([s[k] for s in scores]) for k in scores[0].keys() + } + avg_scores["scores_per_experiment"] = scores + + return avg_scores + + def _undersample_data_indices(self, y, samples_per_label, idxs=None): + """Undersample data to have samples_per_label samples of each label""" + sample_indices = [] + if idxs is None: + idxs = np.arange(len(y)) + np.random.shuffle(idxs) + label_counter = defaultdict(int) + for i in idxs: + if any((label_counter[label] < samples_per_label) for label in y[i]): + sample_indices.append(i) + for label in y[i]: + label_counter[label] += 1 + return sample_indices, idxs diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskPairClassification.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskPairClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..8b3be7f3f82bb25e899b233b0a395ba3674fb6a6 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskPairClassification.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +import logging +from collections import defaultdict + +from datasets import Dataset + +from ..encoder_interface import Encoder, EncoderWithQueryCorpusEncode +from ..evaluation.evaluators import PairClassificationEvaluator +from ..MTEBResults import ScoresDict +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +class AbsTaskPairClassification(AbsTask): + """Abstract class for PairClassificationTasks + The similarity is computed between pairs and the results are ranked. Average precision + is computed to measure how well the methods can be used for pairwise pair classification. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns: + sent1: list[str] + sent2: list[str] + labels: list[int] + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def _add_main_score(self, scores) -> None: + scores["main_score"] = scores["max"][self.metadata.main_score] + + def _evaluate_subset( + self, + model: Encoder | EncoderWithQueryCorpusEncode, + dataset: Dataset, + **kwargs, + ) -> ScoresDict: + data_split = dataset[0] + logging.getLogger( + "sentence_transformers.evaluation.PairClassificationEvaluator" + ).setLevel(logging.WARN) + evaluator = PairClassificationEvaluator( + data_split["sent1"], data_split["sent2"], data_split["labels"], **kwargs + ) + scores = evaluator.compute_metrics(model) + + # Compute max + max_scores = defaultdict(list) + for sim_fct in scores: + for metric in ["accuracy", "f1", "ap"]: + max_scores[metric].append(scores[sim_fct][metric]) + + for metric in max_scores: + max_scores[metric] = max(max_scores[metric]) + + scores["max"] = dict(max_scores) + + self._add_main_score(scores) + return scores diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskReranking.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskReranking.py new file mode 100644 index 0000000000000000000000000000000000000000..f69cd576cec6a6148f6384ce048de54df2f8849e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskReranking.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from typing import Any + +from datasets import Dataset + +from mteb.encoder_interface import Encoder, EncoderWithQueryCorpusEncode +from mteb.MTEBResults import ScoresDict + +from ..evaluation.evaluators import RerankingEvaluator +from .AbsTask import AbsTask + + +class AbsTaskReranking(AbsTask): + """Abstract class for re-ranking experiments. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns: + query: str + positive: list[str] + negative: list[str] + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def _evaluate_subset( + self, + model: Encoder | EncoderWithQueryCorpusEncode, + data_split: Dataset, + **kwargs: Any, + ) -> ScoresDict: + evaluator = RerankingEvaluator(data_split, **kwargs) + scores = evaluator(model) + + self._add_main_score(scores) + return scores + + def _add_main_score(self, scores: ScoresDict) -> None: + scores["main_score"] = scores[self.metadata.main_score] diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskRetrieval.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskRetrieval.py new file mode 100644 index 0000000000000000000000000000000000000000..e29f03e32fae0c67e06272bda2bd004bb2bb5f5a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskRetrieval.py @@ -0,0 +1,374 @@ +from __future__ import annotations + +import json +import logging +import os +from collections import defaultdict +from pathlib import Path +from time import time +from typing import Dict, Tuple + +from datasets import Features, Value, load_dataset + +from ..evaluation.evaluators import RetrievalEvaluator +from ..MTEBResults import ScoresDict +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +# Adapted from https://github.com/beir-cellar/beir/blob/f062f038c4bfd19a8ca942a9910b1e0d218759d4/beir/datasets/data_loader_hf.py#L10 +class HFDataLoader: + def __init__( + self, + hf_repo: str | None = None, + hf_repo_qrels: str | None = None, + data_folder: str | None = None, + prefix: str | None = None, + corpus_file: str = "corpus.jsonl", + query_file: str = "queries.jsonl", + qrels_folder: str = "qrels", + qrels_file: str = "", + streaming: bool = False, + keep_in_memory: bool = False, + ): + self.corpus = {} + self.queries = {} + self.qrels = {} + self.hf_repo = hf_repo + if hf_repo: + # By default fetch qrels from same repo not a second repo with "-qrels" like in original + self.hf_repo_qrels = hf_repo_qrels if hf_repo_qrels else hf_repo + else: + # data folder would contain these files: + # (1) fiqa/corpus.jsonl (format: jsonlines) + # (2) fiqa/queries.jsonl (format: jsonlines) + # (3) fiqa/qrels/test.tsv (format: tsv ("\t")) + if prefix: + query_file = prefix + "-" + query_file + qrels_folder = prefix + "-" + qrels_folder + + self.corpus_file = ( + os.path.join(data_folder, corpus_file) if data_folder else corpus_file + ) + self.query_file = ( + os.path.join(data_folder, query_file) if data_folder else query_file + ) + self.qrels_folder = ( + os.path.join(data_folder, qrels_folder) if data_folder else None + ) + self.qrels_file = qrels_file + self.streaming = streaming + self.keep_in_memory = keep_in_memory + + @staticmethod + def check(fIn: str, ext: str): + if not os.path.exists(fIn): + raise ValueError( + "File {} not present! Please provide accurate file.".format(fIn) + ) + + if not fIn.endswith(ext): + raise ValueError( + "File {} must be present with extension {}".format(fIn, ext) + ) + + def load( + self, split="test" + ) -> Tuple[Dict[str, dict[str, str]], dict[str, str], dict[str, dict[str, int]]]: + if not self.hf_repo: + self.qrels_file = os.path.join(self.qrels_folder, split + ".tsv") + self.check(fIn=self.corpus_file, ext="jsonl") + self.check(fIn=self.query_file, ext="jsonl") + self.check(fIn=self.qrels_file, ext="tsv") + + if not len(self.corpus): + logger.info("Loading Corpus...") + self._load_corpus() + logger.info("Loaded %d %s Documents.", len(self.corpus), split.upper()) + logger.info("Doc Example: %s", self.corpus[0]) + + if not len(self.queries): + logger.info("Loading Queries...") + self._load_queries() + + self._load_qrels(split) + # filter queries with no qrels + qrels_dict = defaultdict(dict) + + def qrels_dict_init(row): + qrels_dict[row["query-id"]][row["corpus-id"]] = int(row["score"]) + + self.qrels.map(qrels_dict_init) + self.qrels = qrels_dict + self.queries = self.queries.filter(lambda x: x["id"] in self.qrels) + logger.info("Loaded %d %s Queries.", len(self.queries), split.upper()) + logger.info("Query Example: %s", self.queries[0]) + + return self.corpus, self.queries, self.qrels + + def load_corpus(self) -> dict[str, dict[str, str]]: + if not self.hf_repo: + self.check(fIn=self.corpus_file, ext="jsonl") + + if not len(self.corpus): + logger.info("Loading Corpus...") + self._load_corpus() + logger.info("Loaded %d %s Documents.", len(self.corpus)) + logger.info("Doc Example: %s", self.corpus[0]) + + return self.corpus + + def _load_corpus(self): + if self.hf_repo: + corpus_ds = load_dataset( + self.hf_repo, + "corpus", + keep_in_memory=self.keep_in_memory, + streaming=self.streaming, + ) + else: + corpus_ds = load_dataset( + "json", + data_files=self.corpus_file, + streaming=self.streaming, + keep_in_memory=self.keep_in_memory, + ) + corpus_ds = next(iter(corpus_ds.values())) # get first split + corpus_ds = corpus_ds.cast_column("_id", Value("string")) + corpus_ds = corpus_ds.rename_column("_id", "id") + corpus_ds = corpus_ds.remove_columns( + [ + col + for col in corpus_ds.column_names + if col not in ["id", "text", "title"] + ] + ) + self.corpus = corpus_ds + + def _load_queries(self): + if self.hf_repo: + queries_ds = load_dataset( + self.hf_repo, + "queries", + keep_in_memory=self.keep_in_memory, + streaming=self.streaming, + ) + else: + queries_ds = load_dataset( + "json", + data_files=self.query_file, + streaming=self.streaming, + keep_in_memory=self.keep_in_memory, + ) + queries_ds = next(iter(queries_ds.values())) # get first split + queries_ds = queries_ds.cast_column("_id", Value("string")) + queries_ds = queries_ds.rename_column("_id", "id") + queries_ds = queries_ds.remove_columns( + [col for col in queries_ds.column_names if col not in ["id", "text"]] + ) + self.queries = queries_ds + + def _load_qrels(self, split): + if self.hf_repo: + qrels_ds = load_dataset( + self.hf_repo_qrels, + keep_in_memory=self.keep_in_memory, + streaming=self.streaming, + )[split] + else: + qrels_ds = load_dataset( + "csv", + data_files=self.qrels_file, + delimiter="\t", + keep_in_memory=self.keep_in_memory, + ) + features = Features( + { + "query-id": Value("string"), + "corpus-id": Value("string"), + "score": Value("float"), + } + ) + qrels_ds = qrels_ds.cast(features) + self.qrels = qrels_ds + + +class AbsTaskRetrieval(AbsTask): + """Abstract class for re-ranking experiments. + + Child-classes must implement the following properties: + + self.corpus: dict[str, dict[str, str]] + Semantically, it should contain dict[split_name, dict[sample_id, dict[str, str]]] + E.g. {"test": {"document_one": {"_id": "d1", "title": "title", "text": "text"}}} + + self.queries: dict[str, dict[str, Union[str, List[str]]]] + Semantically, it should contain dict[split_name, dict[sample_id, str]] or dict[split_name, dict[sample_id, List[str]]] for conversations + E.g. {"test": {"q1": "query"}} + or {"test": {"q1": ["turn1", "turn2", "turn3"]}} + + self.relevant_docs: dict[str, dict[str, dict[str, int]]] + Semantically, it should contain dict[split_name, dict[sample_id, dict[doc_id, score]]] + E.g.: {"test": {"q1": {"document_one": 1}}} + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + def load_data(self, **kwargs): + if self.data_loaded: + return + self.corpus, self.queries, self.relevant_docs = {}, {}, {} + dataset_path = self.metadata_dict["dataset"]["path"] + hf_repo_qrels = ( + dataset_path + "-qrels" if "clarin-knext" in dataset_path else None + ) + for split in kwargs.get("eval_splits", self.metadata_dict["eval_splits"]): + corpus, queries, qrels = HFDataLoader( + hf_repo=dataset_path, + hf_repo_qrels=hf_repo_qrels, + streaming=False, + keep_in_memory=False, + ).load(split=split) + # Conversion from DataSet + queries = {query["id"]: query["text"] for query in queries} + corpus = { + doc["id"]: {"title": doc["title"], "text": doc["text"]} + for doc in corpus + } + self.corpus[split], self.queries[split], self.relevant_docs[split] = ( + corpus, + queries, + qrels, + ) + + self.data_loaded = True + + def evaluate(self, model, split="test", **kwargs): + retriever = RetrievalEvaluator(model, **kwargs) + + scores = {} + hf_subsets = ( + [l for l in self.hf_subsets] + if (self.is_multilingual or self.is_crosslingual) + else ["default"] + ) + + for hf_subset in hf_subsets: + logger.info(f"Subset: {hf_subset}") + + if hf_subset == "default": + corpus, queries, relevant_docs = ( + self.corpus[split], + self.queries[split], + self.relevant_docs[split], + ) + else: + corpus, queries, relevant_docs = ( + self.corpus[hf_subset][split], + self.queries[hf_subset][split], + self.relevant_docs[hf_subset][split], + ) + scores[hf_subset] = self._evaluate_subset( + retriever, corpus, queries, relevant_docs, hf_subset, **kwargs + ) + return scores + + def _evaluate_subset( + self, retriever, corpus, queries, relevant_docs, hf_subset: str, **kwargs + ): + start_time = time() + results = retriever(corpus, queries) + end_time = time() + logger.info( + "Time taken to retrieve: {:.2f} seconds".format(end_time - start_time) + ) + + if kwargs.get("save_predictions", False): + output_folder = Path(kwargs.get("output_folder", "results")) + if not os.path.isdir(output_folder): + os.makedirs(output_folder) + top_k = kwargs.get("top_k", None) + if top_k is not None: + for qid in list(results.keys()): + doc_ids = set( + sorted( + results[qid], key=lambda x: results[qid][x], reverse=True + )[:top_k] + ) + results[qid] = { + k: v for k, v in results[qid].items() if k in doc_ids + } + qrels_save_path = ( + output_folder + / f"{self.metadata_dict['name']}_{hf_subset}_predictions.json" + ) + + with open(qrels_save_path, "w") as f: + json.dump(results, f) + + ndcg, _map, recall, precision = retriever.evaluate( + relevant_docs, + results, + retriever.k_values, + ignore_identical_ids=kwargs.get("ignore_identical_ids", True), + ) + mrr = retriever.evaluate_custom( + relevant_docs, results, retriever.k_values, "mrr" + ) + scores = { + **{f"ndcg_at_{k.split('@')[1]}": v for (k, v) in ndcg.items()}, + **{f"map_at_{k.split('@')[1]}": v for (k, v) in _map.items()}, + **{f"recall_at_{k.split('@')[1]}": v for (k, v) in recall.items()}, + **{f"precision_at_{k.split('@')[1]}": v for (k, v) in precision.items()}, + **{f"mrr_at_{k.split('@')[1]}": v for (k, v) in mrr.items()}, + } + self._add_main_score(scores) + return scores + + def _add_main_score(self, scores: ScoresDict) -> None: + scores["main_score"] = scores[self.metadata.main_score] + + def calculate_metadata_metrics(self) -> None: + self.load_data() + + for split in self.metadata_dict["eval_splits"]: + if self.is_multilingual: + for lang in self.relevant_docs.keys(): + process_language( + self.relevant_docs[lang][split], + self.queries[lang][split], + self.corpus[lang][split], + lang, + ) + else: + process_language( + self.relevant_docs[split], self.queries[split], self.corpus[split] + ) + + +def process_language(relevant_docs, queries, corpus, lang=None): + total_length, num_pairs = calculate_length_and_count(relevant_docs, queries, corpus) + average_length = total_length / num_pairs if num_pairs else 0 + num_documents = len(queries) + len(corpus) + + language_description = f" for language {lang}" if lang else "" + print(f"Average character length{language_description} is {average_length}") + print(f"Number of queries and documents{language_description} is {num_documents}") + + +def calculate_length_and_count(relevant_docs, queries, corpus): + total_length = 0 + num_pairs = 0 + for query_id, docs in relevant_docs.items(): + query = queries[query_id] + for doc_id in docs: + # not relevant + if docs[doc_id] == 0: + continue + doc = corpus[doc_id] + doc_text = doc["title"] + doc["text"] + total_length += len(query) + len(doc_text) + num_pairs += 1 + return total_length, num_pairs diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskSTS.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskSTS.py new file mode 100644 index 0000000000000000000000000000000000000000..0f658438cdc7a39f9c86e7f5a217f0074d62c83b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskSTS.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +import logging + +from ..evaluation.evaluators import STSEvaluator +from ..MTEBResults import ScoresDict +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +class AbsTaskSTS(AbsTask): + """Abstract class for STS experiments. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns:: + sentence1: str + sentence2: str + score: float + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + @property + def min_score(self) -> int: + return self.metadata_dict["min_score"] + + @property + def max_score(self) -> int: + return self.metadata_dict["max_score"] + + def _evaluate_subset(self, model, data_split, **kwargs) -> ScoresDict: + def normalize(x): + return (x - self.min_score) / (self.max_score - self.min_score) + + normalized_scores = list(map(normalize, data_split["score"])) + evaluator = STSEvaluator( + data_split["sentence1"], + data_split["sentence2"], + normalized_scores, + **kwargs, + ) + scores = evaluator(model) + + self._add_main_score(scores) + return scores + + def _add_main_score(self, scores: ScoresDict) -> None: + m_score = self.metadata.main_score + dist, metric = m_score.split("_") + dist_mapping = {"cosine": "cos_sim"} + scores["main_score"] = scores[dist_mapping.get(dist, dist)][metric] diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskSummarization.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskSummarization.py new file mode 100644 index 0000000000000000000000000000000000000000..99a1018efac0bb2ed9c78ed64bb5f4db5b81ed02 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/AbsTaskSummarization.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +import logging + +import numpy as np + +from mteb.MTEBResults import ScoresDict + +from ..evaluation.evaluators import SummarizationEvaluator +from .AbsTask import AbsTask + +logger = logging.getLogger(__name__) + + +class AbsTaskSummarization(AbsTask): + """Abstract class for summarization experiments. + + self.load_data() must generate a huggingface dataset with a split matching self.metadata_dict["eval_splits"], and assign it to self.dataset. It must contain the following columns: + text: str + human_summaries: list[str] + machine_summaries: list[str] + relevance: list[float] (the score of the machine generated summaries) + """ + + def __init__(self, **kwargs): + super().__init__(**kwargs) + + @property + def min_score(self): + return self.metadata_dict["min_score"] + + @property + def max_score(self): + return self.metadata_dict["max_score"] + + def _evaluate_subset(self, model, data_split, **kwargs) -> ScoresDict: + normalized_scores = list( + map( + lambda x: (np.array(x) - self.min_score) + / (self.max_score - self.min_score), + data_split["relevance"], + ) + ) + evaluator = SummarizationEvaluator( + machine_summaries=data_split["machine_summaries"], + human_summaries=data_split["human_summaries"], + texts=data_split["text"], + gold_scores=normalized_scores, + **kwargs, + ) + scores = evaluator(model) + self._add_main_score(scores) + return scores + + def _add_main_score(self, scores: ScoresDict) -> None: + m_score = self.metadata.main_score + dist, metric = m_score.split("_") + dist_mapping = {"cosine": "cos_sim"} + scores["main_score"] = scores[dist_mapping.get(dist, dist)][metric] diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/CrosslingualTask.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/CrosslingualTask.py new file mode 100644 index 0000000000000000000000000000000000000000..90aaf01cb9e26ab823ad2f13a18dbeb3b3206227 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/CrosslingualTask.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +from .AbsTask import AbsTask +from .MultiSubsetLoader import MultiSubsetLoader + + +class CrosslingualTask(MultiSubsetLoader, AbsTask): + def __init__(self, hf_subsets=None, **kwargs): + super().__init__(**kwargs) + if isinstance(hf_subsets, list): + hf_subsets = [ + lang for lang in hf_subsets if lang in self.metadata.eval_langs + ] + if hf_subsets is not None and len(hf_subsets) > 0: + self.hf_subsets = hf_subsets + else: + self.hf_subsets = self.metadata.eval_langs + self.is_crosslingual = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/MultiSubsetLoader.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/MultiSubsetLoader.py new file mode 100644 index 0000000000000000000000000000000000000000..1613ac68ae01251b7c08e5af45fc0a224e6ada49 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/MultiSubsetLoader.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +import datasets + + +class MultiSubsetLoader: + def load_data(self, **kwargs): + """Load dataset containing multiple subsets from HuggingFace hub""" + if self.data_loaded: + return + + fast_loading = self.fast_loading if hasattr(self, "fast_loading") else False + if fast_loading: + self.fast_load() + else: + self.slow_load() + + self.dataset_transform() + self.data_loaded = True + + def fast_load(self, **kwargs): + """Load all subsets at once, then group by language with Polars. Using fast loading has two requirements: + - Each row in the dataset should have a 'lang' feature giving the corresponding language/language pair + - The datasets must have a 'default' config that loads all the subsets of the dataset (see https://huggingface.co/docs/datasets/en/repository_structure#configurations) + """ + self.dataset = {} + merged_dataset = datasets.load_dataset( + **self.metadata_dict["dataset"] + ) # load "default" subset + for split in merged_dataset.keys(): + df_split = merged_dataset[split].to_polars() + df_grouped = dict(df_split.group_by("lang")) + for lang in set(df_split["lang"].unique()) & set(self.hf_subsets): + self.dataset.setdefault(lang, {}) + self.dataset[lang][split] = datasets.Dataset.from_polars( + df_grouped[lang].drop("lang") + ) # Remove lang column and convert back to HF datasets, not strictly necessary but better for compatibility + for lang, subset in self.dataset.items(): + self.dataset[lang] = datasets.DatasetDict(subset) + + def slow_load(self, **kwargs): + """Load each subsets iteratively""" + self.dataset = {} + for lang in self.hf_subsets: + self.dataset[lang] = datasets.load_dataset( + name=lang, + **self.metadata_dict.get("dataset", None), + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/MultilingualTask.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/MultilingualTask.py new file mode 100644 index 0000000000000000000000000000000000000000..b14149a1effe4a1be0ee8714fb6fbe8b00642425 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/MultilingualTask.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from .AbsTask import AbsTask +from .MultiSubsetLoader import MultiSubsetLoader + + +class MultilingualTask(MultiSubsetLoader, AbsTask): + def __init__(self, hf_subsets=None, **kwargs): + super().__init__(**kwargs) + if isinstance(hf_subsets, list): + hf_subsets = [ + lang for lang in hf_subsets if lang in self.metadata_dict["eval_langs"] + ] + if hf_subsets is not None and len(hf_subsets) > 0: + self.hf_subsets = ( + hf_subsets # TODO: case where user provides langs not in the dataset + ) + else: + self.hf_subsets = self.metadata_dict["eval_langs"] + self.is_multilingual = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/TaskMetadata.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/TaskMetadata.py new file mode 100644 index 0000000000000000000000000000000000000000..2784491b7a6109956cd451edfe7b75be34ea626c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/TaskMetadata.py @@ -0,0 +1,297 @@ +from __future__ import annotations + +import logging +from datetime import date +from typing import List, Mapping, Union + +from pydantic import AnyUrl, BaseModel, BeforeValidator, TypeAdapter, field_validator +from typing_extensions import Annotated, Literal + +from ..languages import ( + ISO_LANGUAGE_SCRIPT, + ISO_TO_LANGUAGE, + ISO_TO_SCRIPT, + path_to_lang_codes, + path_to_lang_scripts, +) + +TASK_SUBTYPE = Literal[ + "Article retrieval", + "Conversational retrieval", + "Dialect pairing", + "Dialog Systems", + "Discourse coherence", + "Language identification", + "Linguistic acceptability", + "Political classification", + "Question answering", + "Sentiment/Hate speech", + "Thematic clustering", + "Scientific Reranking", + "Claim verification", + "Topic classification", + "Code retrieval", + "False Friends", + "Cross-Lingual Semantic Discrimination", + "Textual Entailment", + "Counterfactual Detection", +] + +TASK_DOMAIN = Literal[ + "Academic", + "Blog", + "Constructed", + "Encyclopaedic", + "Fiction", + "Government", + "Legal", + "Medical", + "News", + "Non-fiction", + "Poetry", + "Religious", + "Reviews", + "Social", + "Spoken", + "Subtitles", + "Web", + "Programming", +] + +TEXT_CREATION_METHOD = Literal[ + "found", + "created", + "machine-translated", + "human-translated and localized", + "human-translated", + "machine-translated and verified", + "machine-translated and localized", + "LM-generated and verified", +] + +SOCIOECONOMIC_STATUS = Literal[ + "high", + "medium", + "low", + "mixed", +] + +TASK_TYPE = Literal[ + "BitextMining", + "Classification", + "MultilabelClassification", + "Clustering", + "PairClassification", + "Reranking", + "Retrieval", + "STS", + "Summarization", + "InstructionRetrieval", +] + +TASK_CATEGORY = Literal[ + "s2s", # Sentence-to-sentence + "s2p", # Sentence-to-paragraph + "p2p", # Paragraph-to-paragraph +] + +ANNOTATOR_TYPE = Literal[ + "expert-annotated", "human-annotated", "derived", "LM-generated" +] + +http_url_adapter = TypeAdapter(AnyUrl) +STR_URL = Annotated[ + str, BeforeValidator(lambda value: str(http_url_adapter.validate_python(value))) +] # Allows the type to be a string, but ensures that the string is a URL + +pastdate_adapter = TypeAdapter(date) +STR_DATE = Annotated[ + str, BeforeValidator(lambda value: str(pastdate_adapter.validate_python(value))) +] # Allows the type to be a string, but ensures that the string is a valid date + +SPLIT_NAME = str +HFSubset = str +LANGUAGES = Union[ + List[ISO_LANGUAGE_SCRIPT], Mapping[HFSubset, List[ISO_LANGUAGE_SCRIPT]] +] + +PROGRAMMING_LANGS = [ + "python", + "javascript", + "typescript", + "go", + "ruby", + "java", + "php", + "c", + "c++", + "rust", + "swift", + "scala", + "shell", +] + +logger = logging.getLogger(__name__) + + +class TaskMetadata(BaseModel): + """Metadata for a task. + + Args: + dataset: All arguments to pass to datasets.load_dataset to load the dataset for the task. Refer to https://huggingface.co/docs/datasets/v2.18.0/en/package_reference/loading_methods#datasets.load_dataset + name: The name of the task. + description: A description of the task. + type: The type of the task. These includes "Classification", "Summarization", "STS", "Retrieval", "Reranking", "Clustering", + "PairClassification", "BitextMining". The type should match the abstask type. + category: The category of the task. E.g. includes "s2s", "s2p", "p2p" (s=sentence, p=paragraph). + reference: A URL to the documentation of the task. E.g. a published paper. + eval_splits: The splits of the dataset used for evaluation. + eval_langs: The languages of the dataset used for evaluation. Langauges follows a ETF BCP 47 standard consisting of "{language}-{script}" + tag (e.g. "eng-Latn"). Where language is specified as a list of ISO 639-3 language codes (e.g. "eng") followed by ISO 15924 script codes + (e.g. "Latn"). Can be either a list of languages or a dictionary mapping huggingface subsets to lists of languages (e.g. if a the + huggingface dataset contain different languages). + main_score: The main score used for evaluation. + date: The date when the data was collected. Specified as a tuple of two dates. + form: The form of the data. Either "spoken", "written". + domains: The domains of the data. These includes "Non-fiction", "Social", "Fiction", "News", "Academic", "Blog", "Encyclopaedic", + "Government", "Legal", "Medical", "Poetry", "Religious", "Reviews", "Web", "Spoken". A dataset can belong to multiple domains. + task_subtypes: The subtypes of the task. E.g. includes "Sentiment/Hate speech", "Thematic Clustering". Feel free to update the list as needed. + license: The license of the data. + socioeconomic_status: The socioeconomic status of the data. Includes "high", "medium", "low", "mixed". + annotations_creators: The type of the annotators. Includes "expert-annotated" (annotated by experts), "human-annotated" (annotated e.g. by + mturkers), "derived" (derived from structure in the data). + dialect: The dialect of the data, if applicable. Ideally specified as a BCP-47 language tag. Empty list if no dialects are present. + text_creation: The method of text creation. Includes "found", "created", "machine-translated", "machine-translated and verified", and + "machine-translated and localized". + bibtex_citation: The BibTeX citation for the dataset. Should be an empty string if no citation is available. + n_samples: The number of samples in the dataset. This should only be for the splits evaluated on. For retrieval tasks, this should be the + number of query-document pairs. + avg_character_length: The average character length of the samples in the dataset. This should only be for the splits evaluated on. For + retrieval tasks, this should be the average character length of the query-document pairs. + """ + + dataset: dict + + name: str + description: str + type: TASK_TYPE + category: TASK_CATEGORY + reference: STR_URL | None # URL to documentation, e.g. published paper + + eval_splits: list[str] + eval_langs: LANGUAGES + main_score: str # Might want a literal here + + date: tuple[STR_DATE, STR_DATE] | None # When the data was collected + form: list[Literal["spoken", "written"]] | None + domains: list[TASK_DOMAIN] | None + task_subtypes: list[TASK_SUBTYPE] | None + license: str | None + + socioeconomic_status: SOCIOECONOMIC_STATUS | None + annotations_creators: ANNOTATOR_TYPE | None + dialect: list[str] | None + + text_creation: TEXT_CREATION_METHOD | None + bibtex_citation: str | None + + n_samples: dict[SPLIT_NAME, int] | None + avg_character_length: dict[SPLIT_NAME, float] | None + + @field_validator("dataset") + def _check_dataset_path_is_specified(cls, dataset): + """This method checks that the dataset path is specified.""" + if "path" not in dataset or dataset["path"] is None: + raise ValueError( + "You must specify the path to the dataset in the dataset dictionary. " + "See https://huggingface.co/docs/datasets/main/en/package_reference/loading_methods#datasets.load_dataset" + ) + return dataset + + @field_validator("dataset") + def _check_dataset_revision_is_specified(cls, dataset): + if "revision" not in dataset: + raise ValueError( + "You must explicitly specify a revision for the dataset (either a SHA or None)." + ) + if dataset["revision"] is None: + logger.warning( + "Revision missing for the dataset %s. It is encourage to specify a dataset revision for reproducability.", + dataset["path"], + ) + return dataset + + @field_validator("eval_langs") + def _check_eval_langs(cls, eval_langs): + """This method checks that the eval_langs are specified as a list of languages.""" + if isinstance(eval_langs, dict): + for langs in eval_langs.values(): + for code in langs: + cls._check_language_code(code) + else: + for code in eval_langs: + cls._check_language_code(code) + return eval_langs + + @staticmethod + def _check_language_code(code): + """This method checks that the language code (e.g. "eng-Latn") is valid.""" + lang, script = code.split("-") + if script == "Code": + if lang in PROGRAMMING_LANGS: + return # override for code + else: + raise ValueError( + f"Programming language {lang} is not a valid programming language." + ) + if lang not in ISO_TO_LANGUAGE: + raise ValueError( + f"Invalid language code: {lang}, you can find valid ISO 639-3 codes in {path_to_lang_codes}" + ) + if script not in ISO_TO_SCRIPT: + raise ValueError( + f"Invalid script code: {script}, you can find valid ISO 15924 codes in {path_to_lang_scripts}" + ) + + @property + def languages(self) -> list[str]: + """Return the languages of the dataset as iso639-3 codes.""" + + def get_lang(lang: str) -> str: + return lang.split("-")[0] + + if isinstance(self.eval_langs, dict): + return sorted( + set( + get_lang(lang) + for langs in self.eval_langs.values() + for lang in langs + ) + ) + return sorted(set([get_lang(lang) for lang in self.eval_langs])) + + @property + def scripts(self) -> set[str]: + """Return the scripts of the dataset as iso15924 codes.""" + + def get_script(lang: str) -> str: + return lang.split("-")[1] + + if isinstance(self.eval_langs, dict): + return set( + get_script(lang) for langs in self.eval_langs.values() for lang in langs + ) + return set(get_script(lang) for lang in self.eval_langs) + + def is_filled(self) -> bool: + """Check if all the metadata fields are filled.""" + return all( + getattr(self, field_name) is not None for field_name in self.model_fields + ) + + @property + def hf_subsets_to_langscripts(self) -> dict[HFSubset, list[ISO_LANGUAGE_SCRIPT]]: + """Return a dictionary mapping huggingface subsets to languages.""" + if isinstance(self.eval_langs, dict): + return self.eval_langs + return {"default": self.eval_langs} # type: ignore diff --git a/testbed/embeddings-benchmark__mteb/mteb/abstasks/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/abstasks/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4e052d66b0b827565228abb35807d54136384d9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/abstasks/__init__.py @@ -0,0 +1,16 @@ +from __future__ import annotations + +from ..evaluation.LangMapping import * +from .AbsTask import * +from .AbsTaskBitextMining import * +from .AbsTaskClassification import * +from .AbsTaskClustering import * +from .AbsTaskInstructionRetrieval import * +from .AbsTaskMultilabelClassification import * +from .AbsTaskPairClassification import * +from .AbsTaskReranking import * +from .AbsTaskRetrieval import * +from .AbsTaskSTS import * +from .AbsTaskSummarization import * +from .CrosslingualTask import * +from .MultilingualTask import * diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc3275800fe7a0d2cda10e0a7c70baec47a0bf8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/__init__.py @@ -0,0 +1,20 @@ +from __future__ import annotations + +from .dan.BornholmskBitextMining import * +from .kat.TbilisiCityHallBitextMining import * +from .multilingual.BibleNLPBitextMining import * +from .multilingual.BUCCBitextMining import * +from .multilingual.BUCCBitextMiningFast import * +from .multilingual.DiaBLaBitextMining import * +from .multilingual.FloresBitextMining import * +from .multilingual.IN22ConvBitextMining import * +from .multilingual.IN22GenBitextMining import * +from .multilingual.IndicGenBenchFloresBitextMining import * +from .multilingual.IWSLT2017BitextMinig import * +from .multilingual.norwegian_courts_bitext_mining import * +from .multilingual.NorwegianCourtsBitextMining import * +from .multilingual.NTREXBitextMining import * +from .multilingual.RomaTalesBitextMining import * +from .multilingual.TatoebaBitextMining import * +from .srn.SRNCorpusBitextMining import * +from .vie.VieMedEVBitextMining import * diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/dan/BornholmskBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/dan/BornholmskBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..8c9cfaa2297ee5d23640ca70af68f0535292b608 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/dan/BornholmskBitextMining.py @@ -0,0 +1,52 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskBitextMining +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class BornholmBitextMining(AbsTaskBitextMining): + metadata = TaskMetadata( + name="BornholmBitextMining", + dataset={ + "path": "strombergnlp/bornholmsk_parallel", + "revision": "3bc5cfb4ec514264fe2db5615fac9016f7251552", + "trust_remote_code": True, + }, + description="Danish Bornholmsk Parallel Corpus. Bornholmsk is a Danish dialect spoken on the island of Bornholm, Denmark. Historically it is a part of east Danish which was also spoken in Scania and Halland, Sweden.", + reference="https://aclanthology.org/W19-6138/", + type="BitextMining", + category="s2s", + eval_splits=["test"], + eval_langs=["dan-Latn"], + main_score="f1", + date=("2019-01-01", "2019-12-31"), + form=["written"], + domains=["Web", "Social", "Fiction"], + license="CC-BY-4.0", + task_subtypes=["Dialect pairing"], + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=["da-dan-bornholm"], + text_creation="created", + bibtex_citation=""" +@inproceedings{derczynskiBornholmskNaturalLanguage2019, + title = {Bornholmsk natural language processing: Resources and tools}, + url = {https://pure.itu.dk/ws/files/84551091/W19_6138.pdf}, + shorttitle = {Bornholmsk natural language processing}, + pages = {338--344}, + booktitle = {Proceedings of the Nordic Conference of Computational Linguistics (2019)}, + publisher = {Linköping University Electronic Press}, + author = {Derczynski, Leon and Kjeldsen, Alex Speed}, + urldate = {2024-04-24}, + date = {2019}, + file = {Available Version (via Google Scholar):/Users/au554730/Zotero/storage/FBQ73ZYN/Derczynski and Kjeldsen - 2019 - Bornholmsk natural language processing Resources .pdf:application/pdf}, +} +""", + avg_character_length={"test": 89.7}, + n_samples={"test": 500}, + ) + + def dataset_transform(self): + # Convert to standard format + self.dataset = self.dataset.rename_column("da", "sentence1") + self.dataset = self.dataset.rename_column("da_bornholm", "sentence2") diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/dan/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/dan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/kat/TbilisiCityHallBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/kat/TbilisiCityHallBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..2c2af40861af1798e7c5bb9b8d74eea8f993ca40 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/kat/TbilisiCityHallBitextMining.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from datasets import DatasetDict, load_dataset + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = { + "kat_Geor": "ka", + "eng_Latn": "en", +} + +_EVAL_LANGS = { + "kat_Geor-eng_Latn": ["kat-Geor", "eng-Latn"], + "eng_Latn-kat_Geor": ["eng-Latn", "kat-Geor"], +} +_EVAL_SPLIT = "test" + + +class TbilisiCityHallBitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="TbilisiCityHallBitextMining", + dataset={ + "path": "jupyterjazz/tbilisi-city-hall-titles", + "revision": "798bb599140565cca2dab8473035fa167e5ee602", + }, + description="Parallel news titles from the Tbilisi City Hall website (https://tbilisi.gov.ge/).", + type="BitextMining", + category="s2s", + eval_splits=[_EVAL_SPLIT], + eval_langs=_EVAL_LANGS, + main_score="f1", + domains=["News"], + text_creation="created", + n_samples={_EVAL_SPLIT: 1820}, + reference="https://huggingface.co/datasets/jupyterjazz/tbilisi-city-hall-titles", + date=("2024-05-02", "2024-05-03"), + form=["written"], + task_subtypes=[], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + bibtex_citation="", + avg_character_length={_EVAL_SPLIT: 78}, + ) + + def load_data(self, **kwargs) -> None: + if self.data_loaded: + return + self.dataset = {} + + for lang in self.hf_subsets: + l1, l2 = lang.split("-") + dataset = load_dataset( + self.metadata_dict["dataset"]["path"], + split=_EVAL_SPLIT, + cache_dir=kwargs.get("cache_dir", None), + revision=self.metadata_dict["dataset"]["revision"], + ) + dataset = dataset.rename_columns( + {_LANGUAGES[l1]: "sentence1", _LANGUAGES[l2]: "sentence2"} + ) + self.dataset[lang] = DatasetDict({_EVAL_SPLIT: dataset}) + + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/kat/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/kat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BUCCBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BUCCBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..34867962e0b4d43f804a916186585f97e908a3a5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BUCCBitextMining.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = { + "de-en": ["deu-Latn", "eng-Latn"], + "fr-en": ["fra-Latn", "eng-Latn"], + "ru-en": ["rus-Cyrl", "eng-Latn"], + "zh-en": ["cmn-Hans", "eng-Latn"], +} + + +_SPLITS = ["test"] + + +class BUCCBitextMining(AbsTaskBitextMining, CrosslingualTask): + superseeded_by = "BUCC.v2" + metadata = TaskMetadata( + name="BUCC", + dataset={ + "path": "mteb/bucc-bitext-mining", + "revision": "d51519689f32196a32af33b075a01d0e7c51e252", + }, + description="BUCC bitext mining dataset", + reference="https://comparable.limsi.fr/bucc2018/bucc2018-task.html", + type="BitextMining", + category="s2s", + eval_splits=_SPLITS, + eval_langs=_LANGUAGES, + main_score="f1", + date=("2017-01-01", "2018-12-31"), + form=["written"], + domains=[], + task_subtypes=[], + license="unknown", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="human-translated", + bibtex_citation="""@inproceedings{zweigenbaum-etal-2017-overview, + title = "Overview of the Second {BUCC} Shared Task: Spotting Parallel Sentences in Comparable Corpora", + author = "Zweigenbaum, Pierre and + Sharoff, Serge and + Rapp, Reinhard", + editor = "Sharoff, Serge and + Zweigenbaum, Pierre and + Rapp, Reinhard", + booktitle = "Proceedings of the 10th Workshop on Building and Using Comparable Corpora", + month = aug, + year = "2017", + address = "Vancouver, Canada", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/W17-2512", + doi = "10.18653/v1/W17-2512", + pages = "60--67", + abstract = "This paper presents the BUCC 2017 shared task on parallel sentence extraction from comparable corpora. It recalls the design of the datasets, presents their final construction and statistics and the methods used to evaluate system results. 13 runs were submitted to the shared task by 4 teams, covering three of the four proposed language pairs: French-English (7 runs), German-English (3 runs), and Chinese-English (3 runs). The best F-scores as measured against the gold standard were 0.84 (German-English), 0.80 (French-English), and 0.43 (Chinese-English). Because of the design of the dataset, in which not all gold parallel sentence pairs are known, these are only minimum values. We examined manually a small sample of the false negative sentence pairs for the most precise French-English runs and estimated the number of parallel sentence pairs not yet in the provided gold standard. Adding them to the gold standard leads to revised estimates for the French-English F-scores of at most +1.5pt. This suggests that the BUCC 2017 datasets provide a reasonable approximate evaluation of the parallel sentence spotting task.", +}""", + n_samples={"test": 641684}, + avg_character_length={"test": 101.3}, + ) + + def dataset_transform(self): + dataset = {} + for lang in self.dataset: + dataset[lang] = {} + for split in _SPLITS: + data = self.dataset[lang][split] + gold = data["gold"][0] + gold = [(i - 1, j - 1) for (i, j) in gold] + + sentence1 = data["sentence1"][0] + sentence2 = data["sentence2"][0] + sentence1 = [sentence1[i] for (i, j) in gold] + print(lang, len(gold)) + print(len(sentence1), len(sentence2)) + dataset[lang][split] = { + "sentence1": sentence1, + "sentence2": sentence2, + "gold": gold, + } + self.dataset = dataset diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BUCCBitextMiningFast.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BUCCBitextMiningFast.py new file mode 100644 index 0000000000000000000000000000000000000000..d914c44460fdf8d01b68642251085d9a7c12da19 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BUCCBitextMiningFast.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = { + "de-en": ["deu-Latn", "eng-Latn"], + "fr-en": ["fra-Latn", "eng-Latn"], + "ru-en": ["rus-Cyrl", "eng-Latn"], + "zh-en": ["cmn-Hans", "eng-Latn"], +} + + +_SPLITS = ["test"] + + +class BUCCBitextMiningFast(AbsTaskBitextMining, CrosslingualTask): + fast_loading = True + metadata = TaskMetadata( + name="BUCC.v2", + dataset={ + "path": "mteb/bucc-bitext-mining", + "revision": "1739dc11ffe9b7bfccd7f3d585aeb4c544fc6677", + }, + description="BUCC bitext mining dataset", + reference="https://comparable.limsi.fr/bucc2018/bucc2018-task.html", + type="BitextMining", + category="s2s", + eval_splits=_SPLITS, + eval_langs=_LANGUAGES, + main_score="f1", + date=("2017-01-01", "2018-12-31"), + form=["written"], + domains=[], + task_subtypes=[], + license="unknown", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="human-translated", + bibtex_citation="""@inproceedings{zweigenbaum-etal-2017-overview, + title = "Overview of the Second {BUCC} Shared Task: Spotting Parallel Sentences in Comparable Corpora", + author = "Zweigenbaum, Pierre and + Sharoff, Serge and + Rapp, Reinhard", + editor = "Sharoff, Serge and + Zweigenbaum, Pierre and + Rapp, Reinhard", + booktitle = "Proceedings of the 10th Workshop on Building and Using Comparable Corpora", + month = aug, + year = "2017", + address = "Vancouver, Canada", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/W17-2512", + doi = "10.18653/v1/W17-2512", + pages = "60--67", + abstract = "This paper presents the BUCC 2017 shared task on parallel sentence extraction from comparable corpora. It recalls the design of the datasets, presents their final construction and statistics and the methods used to evaluate system results. 13 runs were submitted to the shared task by 4 teams, covering three of the four proposed language pairs: French-English (7 runs), German-English (3 runs), and Chinese-English (3 runs). The best F-scores as measured against the gold standard were 0.84 (German-English), 0.80 (French-English), and 0.43 (Chinese-English). Because of the design of the dataset, in which not all gold parallel sentence pairs are known, these are only minimum values. We examined manually a small sample of the false negative sentence pairs for the most precise French-English runs and estimated the number of parallel sentence pairs not yet in the provided gold standard. Adding them to the gold standard leads to revised estimates for the French-English F-scores of at most +1.5pt. This suggests that the BUCC 2017 datasets provide a reasonable approximate evaluation of the parallel sentence spotting task.", +}""", + n_samples={"test": 641684}, + avg_character_length={"test": 101.3}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BibleNLPBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BibleNLPBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..cb6d68d70cfae0c90408c5c0f8871a1202bd85c5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/BibleNLPBitextMining.py @@ -0,0 +1,950 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = [ + "aai_Latn", # Apinayé + "aak_Arab", # Ankave + "aau_Latn", # Abau + "aaz_Latn", # Amarasi + "abt_Latn", # Ambulas + "abx_Latn", # Inabaknon + "aby_Latn", # Aneme Wake + "acf_Latn", # Saint Lucian Creole French + "acr_Latn", # Achi + "acu_Latn", # Achuar-Shiwiar + "adz_Latn", # Adzera + "aer_Latn", # Eastern Arrernte + "aey_Latn", # Amele + "agd_Latn", # Agarabi + "agg_Latn", # Angor + "agm_Latn", # Angaataha + "agn_Latn", # Agutaynen + "agr_Latn", # Aguaruna + "agt_Latn", # Central Cagayan Agta + "agu_Latn", # Aguacateco + "aia_Latn", # Arosi + "aii_Syrc", # Assyrian Neo-Aramaic + "aka_Latn", # Akan + "ake_Latn", # Akawaio + "alp_Latn", # Alune + "alq_Latn", # Algonquin + "als_Latn", # Tosk Albanian + "aly_Latn", # Alyawarr + "ame_Latn", # Yanesha' + "amf_Latn", # Hamer-Banna + "amk_Latn", # Ambai + "amm_Latn", # Ama (Papua New Guinea) + "amn_Latn", # Amanab + "amo_Latn", # Amo + "amp_Latn", # Alamblak + "amr_Latn", # Amarakaeri + "amu_Latn", # Amuzgo + "amx_Latn", # Anmatyerre + "anh_Latn", # Nend + "anv_Latn", # Denya + "aoi_Latn", # Anindilyakwa + "aoj_Latn", # Mufian + "aom_Latn", # Ömie + "aon_Latn", # Bumbita Arapesh + "apb_Latn", # Sa'a + "ape_Latn", # Bukiyip + "apn_Latn", # Apinayé + "apr_Latn", # Arop-Lokep + "apu_Latn", # Apurinã + "apw_Latn", # Western Apache + "apz_Latn", # Safeyoka + "arb_Arab", # Standard Arabic + "are_Latn", # Western Arrarnta + "arl_Latn", # Arabela + "arn_Latn", # Mapudungun + "arp_Latn", # Arapaho + "asm_Beng", # Assamese + "aso_Latn", # Dano + "ata_Latn", # Pele-Ata + "atb_Latn", # Zaiwa + "atd_Latn", # Ata Manobo + "atg_Latn", # Ivbie North-Okpela-Arhe + "att_Latn", # Pamplona Atta + "auc_Latn", # Waorani + "aui_Latn", # Anuki + "auy_Latn", # Awiyaana + "avt_Latn", # Au + "awb_Latn", # Awa (Papua New Guinea) + "awk_Latn", # Awabakal + "awx_Latn", # Awara + "azb_Arab", # South Azerbaijani + "azg_Latn", # San Pedro Amuzgos Amuzgo + "azz_Latn", # Highland Puebla Nahuatl + "bao_Latn", # Waimaha + "bba_Latn", # Baatonum + "bbb_Latn", # Barai + "bbr_Latn", # Girawa + "bch_Latn", # Bariai + "bco_Latn", # Kaluli + "bdd_Latn", # Bunama + "bea_Latn", # Beaver + "bef_Latn", # Benabena + "bel_Cyrl", # Belarusian + "ben_Beng", # Bengali + "beo_Latn", # Beami + "beu_Latn", # Blagar + "bgs_Latn", # Tagabawa + "bgt_Latn", # Bughotu + "bhg_Latn", # Binandere + "bhl_Latn", # Bimin + "big_Latn", # Biangai + "bjk_Latn", # Barok + "bjp_Latn", # Fanamaket + "bjr_Latn", # Binumarien + "bjv_Latn", # Bedjond + "bjz_Latn", # Baruga + "bkd_Latn", # Binukid + "bki_Latn", # Bikol + "bkq_Latn", # Bakairí + "bkx_Latn", # Baikeno + "blw_Latn", # Balangao + "blz_Latn", # Balantak + "bmh_Latn", # Kein + "bmk_Latn", # Ghayavi + "bmr_Latn", # Muinane + "bmu_Latn", # Somba-Siawari + "bnp_Latn", # Bola + "boa_Latn", # Bora + "boj_Latn", # Anjam + "bon_Latn", # Bine + "box_Latn", # Buamu + "bpr_Latn", # Koronadal Blaan + "bps_Latn", # Sarangani Blaan + "bqc_Latn", # Boko (Benin) + "bqp_Latn", # Busa + "bre_Latn", # Breton + "bsj_Latn", # Bangwinji + "bsn_Latn", # Barasana-Eduria + "bsp_Latn", # Baga Sitemu + "bss_Latn", # Akoose + "buk_Latn", # Bugawac + "bus_Latn", # Bokobaru + "bvd_Latn", # Baeggu + "bvr_Latn", # Burarra + "bxh_Latn", # Buhutu + "byr_Latn", # Baruya + "byx_Latn", # Qaqet + "bzd_Latn", # Bribri + "bzh_Latn", # Mapos Buang + "bzj_Latn", # Belize Kriol English + "caa_Latn", # Ch'orti' + "cab_Latn", # Garifuna + "cac_Latn", # Chuj + "caf_Latn", # Southern Carrier + "cak_Latn", # Kaqchikel + "cao_Latn", # Chácobo + "cap_Latn", # Chipaya + "car_Latn", # Galibi Carib + "cav_Latn", # Cavineña + "cax_Latn", # Chiquitano + "cbc_Latn", # Carapana + "cbi_Latn", # Chachi + "cbk_Latn", # Chavacano + "cbr_Latn", # Cashibo-Cacataibo + "cbs_Latn", # Cashinahua + "cbt_Latn", # Chayahuita + "cbu_Latn", # Candoshi-Shapra + "cbv_Latn", # Cacua + "cco_Latn", # Chamicuro + "ceb_Latn", # Cebuano + "cek_Latn", # Eastern Khumi Chin + "ces_Latn", # Czech + "cgc_Latn", # Kagayanen + "cha_Latn", # Chamorro + "chd_Latn", # Highland Oaxaca Chontal + "chf_Latn", # Tabasco Chontal + "chk_Latn", # Chuukese + "chq_Latn", # Quiotepec Chinantec + "chz_Latn", # Ozumacín Chinantec + "cjo_Latn", # Ashéninka Pajonal + "cjv_Latn", # Chuave + "ckb_Arab", # Central Kurdish + "cle_Latn", # Lealao Chinantec + "clu_Latn", # Caluyanun + "cme_Latn", # Cerma + "cmn_Hans", # Mandarin Chinese (Simplified) + "cni_Latn", # Asháninka + "cnl_Latn", # Lalana Chinantec + "cnt_Latn", # Tepetotutla Chinantec + "cof_Latn", # Colorado + "con_Latn", # Cofán + "cop_Copt", # Coptic + "cot_Latn", # Caquinte + "cpa_Latn", # Palantla Chinantec + "cpb_Latn", # Ucayali-Yurúa Ashéninka + "cpc_Latn", # Ajyíninka Apurucayali + "cpu_Latn", # Pichis Ashéninka + "cpy_Latn", # South Ucayali Ashéninka + "crn_Latn", # El Nayar Cora + "crx_Latn", # Carrier + "cso_Latn", # Sochiapam Chinantec + "csy_Latn", # Siyin Chin + "cta_Latn", # Tataltepec Chatino + "cth_Latn", # Thaiphum Chin + "ctp_Latn", # Western Highland Chatino + "ctu_Latn", # Chol + "cub_Latn", # Cubeo + "cuc_Latn", # Usila Chinantec + "cui_Latn", # Cuiba + "cuk_Latn", # San Blas Kuna + "cut_Latn", # Teutila Cuicatec + "cux_Latn", # Tepeuxila Cuicatec + "cwe_Latn", # Kwere + "cya_Latn", # Nopala Chatino + "daa_Latn", # Dangaléat + "dad_Latn", # Marik + "dah_Latn", # Gwahatike + "dan_Latn", # Danish + "ded_Latn", # Dedua + "deu_Latn", # German + "dgc_Latn", # Agta + "dgr_Latn", # Dogrib + "dgz_Latn", # Daga + "dhg_Latn", # Dhangu + "dif_Latn", # Dieri + "dik_Latn", # Southwestern Dinka + "dji_Latn", # Djinang + "djk_Latn", # Aukan + "djr_Latn", # Djambarrpuyngu + "dob_Latn", # Dobu + "dop_Latn", # Lukpa + "dov_Latn", # Dombe + "dwr_Latn", # Dawro + "dww_Latn", # Dawawa + "dwy_Latn", # Dhuwaya + "ebk_Latn", # Eastern Bontok + "eko_Latn", # Kota (Gabon) + "emi_Latn", # Mussau-Emira + "emp_Latn", # Northern Emberá + "enq_Latn", # Enga + "epo_Latn", # Esperanto + "eri_Latn", # Ogea + "ese_Latn", # Ese Ejja + "esk_Latn", # Northwest Alaska Inupiatun + "etr_Latn", # Edolo + "ewe_Latn", # Ewe + "faa_Latn", # Fasu + "fai_Latn", # Faiwol + "far_Latn", # Fataleka + "ffm_Latn", # Maasina Fulfulde + "for_Latn", # Fore + "fra_Latn", # French + "fue_Latn", # Borgu Fulfulde + "fuf_Latn", # Pular + "fuh_Latn", # Western Niger Fulfulde + "gah_Latn", # Alekano + "gai_Latn", # Borei + "gam_Latn", # Kandawo + "gaw_Latn", # Nobonob + "gdn_Latn", # Umanakaina + "gdr_Latn", # Wipi + "geb_Latn", # Kire + "gfk_Latn", # Patpatar + "ghs_Latn", # Guhu-Samane + "glk_Arab", # Gilaki + "gmv_Latn", # Gamo + "gng_Latn", # Ngangam + "gnn_Latn", # Gumatj + "gnw_Latn", # Western Bolivian Guaraní + "gof_Latn", # Gofa + "grc_Grek", # Ancient Greek + "gub_Latn", # Guajajára + "guh_Latn", # Guahibo + "gui_Latn", # Eastern Bolivian Guaraní + "guj_Gujr", # Gujarati + "gul_Latn", # Sea Island Creole English + "gum_Latn", # Guambiano + "gun_Latn", # Mbyá Guaraní + "guo_Latn", # Guayabero + "gup_Latn", # Gunwinggu + "gux_Latn", # Gourmanchéma + "gvc_Latn", # Guanano + "gvf_Latn", # Golin + "gvn_Latn", # Kuku-Yalanji + "gvs_Latn", # Gumawana + "gwi_Latn", # Gwichʼin + "gym_Latn", # Ngäbere + "gyr_Latn", # Guarayu + "hat_Latn", # Haitian Creole + "hau_Latn", # Hausa + "haw_Latn", # Hawaiian + "hbo_Hebr", # Ancient Hebrew + "hch_Latn", # Huichol + "heb_Hebr", # Hebrew + "heg_Latn", # Helong + "hin_Deva", # Hindi + "hix_Latn", # Hoocąk + "hla_Latn", # Halia + "hlt_Latn", # Matu Chin + "hmo_Latn", # Hiri Motu + "hns_Latn", # Caribbean Hindustani + "hop_Latn", # Hopi + "hot_Latn", # Hote + "hrv_Latn", # Croatian + "hto_Latn", # Minica Huitoto + "hub_Latn", # Huambisa + "hui_Latn", # Huli + "hun_Latn", # Hungarian + "hus_Latn", # Huastec + "huu_Latn", # Huitoto, Murui + "huv_Latn", # San Mateo Del Mar Huave + "hvn_Latn", # Sabu + "ian_Latn", # Iatmul + "ign_Latn", # Ignaciano + "ikk_Latn", # Ika + "ikw_Latn", # Ikwere + "ilo_Latn", # Iloko + "imo_Latn", # Imbongu + "inb_Latn", # Inga + "ind_Latn", # Indonesian + "ino_Latn", # Inoke-Yate + "iou_Latn", # Tuma-Irumu + "ipi_Latn", # Ipili + "isn_Latn", # Isanzu + "ita_Latn", # Italian + "iws_Latn", # Sepik Iwam + "ixl_Latn", # Ixil + "jac_Latn", # Popti' + "jae_Latn", # Yabem + "jao_Latn", # Yanyuwa + "jic_Latn", # Tol + "jid_Latn", # Bu + "jiv_Latn", # Shuar + "jni_Latn", # Janji + "jpn_Jpan", # Japanese + "jvn_Latn", # Caribbean Javanese + "kan_Knda", # Kannada + "kaq_Latn", # Capanahua + "kbc_Latn", # Kadiwéu + "kbh_Latn", # Camsá + "kbm_Latn", # Iwal + "kbq_Latn", # Kamano + "kdc_Latn", # Kutu + "kde_Latn", # Makonde + "kdl_Latn", # Tsikimba + "kek_Latn", # Kekchí + "ken_Latn", # Kenyang + "kew_Latn", # West Kewa + "kgf_Latn", # Kube + "kgk_Latn", # Kagoma + "kgp_Latn", # Kaingang + "khs_Latn", # Kasua + "khz_Latn", # Keapara + "kik_Latn", # Kikuyu + "kiw_Latn", # Northeast Kiwai + "kiz_Latn", # Kisi + "kje_Latn", # Kisar + "kjs_Latn", # East Kewa + "kkc_Latn", # Odoodee + "kkl_Latn", # Kokota + "klt_Latn", # Nukna + "klv_Latn", # Maskelynes + "kmg_Latn", # Kâte + "kmh_Latn", # Kalam + "kmk_Latn", # Limos Kalinga + "kmo_Latn", # Kwoma + "kms_Latn", # Kamasau + "kmu_Latn", # Kanite + "kne_Latn", # Kankanaey + "knf_Latn", # Mankanya + "knj_Latn", # Western Kanjobal + "knv_Latn", # Tabo + "kos_Latn", # Kosraean + "kpf_Latn", # Komba + "kpg_Latn", # Kapingamarangi + "kpj_Latn", # Karajá + "kpr_Latn", # Korafe-Yegha + "kpw_Latn", # Kobon + "kpx_Latn", # Mountain Koiali + "kqa_Latn", # Mum + "kqc_Latn", # Doromu-Koki + "kqf_Latn", # Kakabai + "kql_Latn", # Kyenele + "kqw_Latn", # Kandas + "ksd_Latn", # Kuanua + "ksj_Latn", # Uare + "ksr_Latn", # Borong + "ktm_Latn", # Kotan + "kto_Latn", # Kuot + "kud_Latn", # 'Auhelawa + "kue_Latn", # Kuman + "kup_Latn", # Kunimaipa + "kvg_Latn", # Kuria + "kvn_Latn", # Border Kuna + "kwd_Latn", # Kwaio + "kwf_Latn", # Kwara'ae + "kwi_Latn", # Awa-Cuaiquer + "kwj_Latn", # Kwanga + "kyc_Latn", # Kyaka + "kyf_Latn", # Kaiy + "kyg_Latn", # Keyagana + "kyq_Latn", # Kenga + "kyz_Latn", # Kayabí + "kze_Latn", # Kosena + "lac_Latn", # Lacandon + "lat_Latn", # Latin + "lbb_Latn", # Label + "lbk_Latn", # Central Bontok + "lcm_Latn", # Tungag + "leu_Latn", # Kara (Papua New Guinea) + "lex_Latn", # Luang + "lgl_Latn", # Wala + "lid_Latn", # Nyindrou + "lif_Deva", # Limbu + "lin_Latn", # Lingala + "lit_Latn", # Lithuanian + "llg_Latn", # Lole + "lug_Latn", # Ganda + "luo_Latn", # Luo (Kenya and Tanzania) + "lww_Latn", # Lewo Eleng + "maa_Latn", # San Jerónimo Tecóatl Mazatec + "maj_Latn", # Jalapa De Díaz Mazatec + "mal_Mlym", # Malayalam + "mam_Latn", # Mam + "maq_Latn", # Chiquihuitlán Mazatec + "mar_Deva", # Marathi + "mau_Latn", # Maumere + "mav_Latn", # Sateré-Mawé + "maz_Latn", # Central Mazahua + "mbb_Latn", # Manobo + "mbc_Latn", # Macushi + "mbh_Latn", # Mangseng + "mbj_Latn", # Nadëb + "mbl_Latn", # Maxakalí + "mbs_Latn", # Sarangani Manobo + "mbt_Latn", # Matigsalug Manobo + "mca_Latn", # Maca + "mcb_Latn", # Macushi + "mcd_Latn", # Sharanahua + "mcf_Latn", # Matsés + "mco_Latn", # Mixe, Coatlán + "mcp_Latn", # Maka (Chad) + "mcq_Latn", # Ese + "mcr_Latn", # Menya + "mdy_Latn", # Male (Ethiopia) + "med_Latn", # Melpa + "mee_Latn", # Mundurukú + "mek_Latn", # Mekeo + "meq_Latn", # Merey + "met_Latn", # Mato + "meu_Latn", # Motu + "mgc_Latn", # Morokodo + "mgh_Latn", # Makhuwa-Meetto + "mgw_Latn", # Matumbi + "mhl_Latn", # Mauwake + "mib_Latn", # Mixtepec Mixtec + "mic_Latn", # Mi'kmaq + "mie_Latn", # Mixtec, Ocotepec + "mig_Latn", # San Miguel El Grande Mixtec + "mih_Latn", # Mixtec, Chayuco + "mil_Latn", # Peñoles Mixtec + "mio_Latn", # Mixtec, Pinotepa Nacional + "mir_Latn", # Mixtec, Isthmus + "mit_Latn", # Mixtec, Southern Puebla + "miz_Latn", # Mixtec, Coatzospan + "mjc_Latn", # Mixtec, San Juan Colorado + "mkj_Latn", # Mokilko + "mkl_Latn", # Mokole + "mkn_Latn", # Kupang Malay + "mks_Latn", # Mixtec, Silacayoapan + "mle_Latn", # Manambu + "mlh_Latn", # Mape + "mlp_Latn", # Bargam + "mmo_Latn", # Mangga Buang + "mmx_Latn", # Madak + "mna_Latn", # Mbula + "mop_Latn", # Mopán Maya + "mox_Latn", # Molima + "mph_Latn", # Maung + "mpj_Latn", # Martu Wangka + "mpm_Latn", # Yosondúa Mixtec + "mpp_Latn", # Migabac + "mps_Latn", # Dadibi + "mpt_Latn", # Mian + "mpx_Latn", # Misima-Panaeati + "mqb_Latn", # Mbuko + "mqj_Latn", # Mamasa + "msb_Latn", # Masbatenyo + "msc_Latn", # Sankaran Maninka + "msk_Latn", # Mansaka + "msm_Latn", # Agusan Manobo + "msy_Latn", # Aruamu + "mti_Latn", # Maiwa (Papua New Guinea) + "mto_Latn", # Totontepec Mixe + "mux_Latn", # Bo-Ung + "muy_Latn", # Muyang + "mva_Latn", # Manam + "mvn_Latn", # Minaveha + "mwc_Latn", # Are + "mwe_Latn", # Mwera (Chimwera) + "mwf_Latn", # Murrinh-Patha + "mwp_Latn", # Kala Lagaw Ya + "mxb_Latn", # Tezoatlán Mixtec + "mxp_Latn", # Tlahuitoltepec Mixe + "mxq_Latn", # Juquila Mixe + "mxt_Latn", # Jamiltepec Mixtec + "mya_Latn", # Muya + "myk_Latn", # Mamara Senoufo + "myu_Latn", # Mundurukú + "myw_Latn", # Muyuw + "myy_Latn", # Macuna + "mzz_Latn", # Masimasi + "nab_Latn", # Southern Nambikuára + "naf_Latn", # Nabak + "nak_Latn", # Nakanai + "nas_Latn", # Naasioi + "nbq_Latn", # Nggem + "nca_Latn", # Iyo + "nch_Latn", # Central Huasteca Nahuatl + "ncj_Latn", # Northern Puebla Nahuatl + "ncl_Latn", # Michoacán Nahuatl + "ncu_Latn", # Chumburung + "ndg_Latn", # Ndengereko + "ndj_Latn", # Ndjem + "nfa_Latn", # Dhao + "ngp_Latn", # Ngulu + "ngu_Latn", # Guerrero Nahuatl + "nhe_Latn", # Eastern Huasteca Nahuatl + "nhg_Latn", # Tetelcingo Nahuatl + "nhi_Latn", # Zacatlán-Ahuacatlán-Tepetzintla Nahuatl + "nho_Latn", # Takuu + "nhr_Latn", # Naro + "nhu_Latn", # Noone + "nhw_Latn", # Western Huasteca Nahuatl + "nhy_Latn", # Northern Oaxaca Nahuatl + "nif_Latn", # Nek + "nii_Latn", # Nii + "nin_Latn", # Ninia Yali + "nko_Latn", # Nkonya + "nld_Latn", # Dutch + "nlg_Latn", # Gela + "nna_Latn", # North Ndebele + "nnq_Latn", # Ngindo + "noa_Latn", # Woun Meu + "nop_Latn", # Numanggang + "not_Latn", # Nomatsiguenga + "nou_Latn", # Ewage-Notu + "npi_Deva", # Nepali (individual language) + "npl_Latn", # Southeastern Puebla Nahuatl + "nsn_Latn", # Nehan + "nss_Latn", # Nali + "ntj_Latn", # Ngaanyatjarra + "ntp_Latn", # Tepehuan + "ntu_Latn", # Natügu + "nuy_Latn", # Nunggubuyu + "nvm_Latn", # Namiae + "nwi_Latn", # Southwest Tanna + "nya_Latn", # Nyanja + "nys_Latn", # Nyungar + "nyu_Latn", # Nyungwe + "obo_Latn", # Obo Manobo + "okv_Latn", # Orokaiva + "omw_Latn", # South Tairora + "ong_Latn", # Olo + "ons_Latn", # Ono + "ood_Latn", # Tohono O'odham + "opm_Latn", # Oksapmin + "ory_Orya", # Odia (Oriya) + "ote_Latn", # Mezquital Otomi + "otm_Latn", # Eastern Highland Otomi + "otn_Latn", # Tenango Otomi + "otq_Latn", # Querétaro Otomi + "ots_Latn", # Estado de México Otomi + "pab_Latn", # Parecís + "pad_Latn", # Paumarí + "pah_Latn", # Tenharim + "pan_Guru", # Panjabi + "pao_Latn", # Northern Paiute + "pes_Arab", # Iranian Persian + "pib_Latn", # Yine + "pio_Latn", # Piapoco + "pir_Latn", # Piratapuyo + "piu_Latn", # Pintupi-Luritja + "pjt_Latn", # Pitjantjatjara + "pls_Latn", # San Marcos Tlalcoyalco Popoloca + "plu_Latn", # Palikur + "pma_Latn", # Paama + "poe_Latn", # San Juan Atzingo Popoloca + "poh_Latn", # Poqomchi' + "poi_Latn", # Highland Popoluca + "pol_Latn", # Polish + "pon_Latn", # Pohnpeian + "por_Latn", # Portuguese + "poy_Latn", # Pogolo + "ppo_Latn", # Folopa + "prf_Latn", # Paranan + "pri_Latn", # Paicî + "ptp_Latn", # Patep + "ptu_Latn", # Bambam + "pwg_Latn", # Gapapaiwa + "qub_Latn", # Huallaga Huánuco Quechua + "quc_Latn", # K'iche' + "quf_Latn", # Lambayeque Quechua + "quh_Latn", # South Bolivian Quechua + "qul_Latn", # North Bolivian Quechua + "qup_Latn", # Southern Pastaza Quechua + "qvc_Latn", # Cajamarca Quechua + "qve_Latn", # Eastern Apurímac Quechua + "qvh_Latn", # Huamalíes-Dos de Mayo Huánuco Quechua + "qvm_Latn", # Margos-Yarowilca-Lauricocha Quechua + "qvn_Latn", # North Junín Quechua + "qvs_Latn", # San Martín Quechua + "qvw_Latn", # Huaylla Wanca Quechua + "qvz_Latn", # Northern Pastaza Quichua + "qwh_Latn", # Huaylas Ancash Quechua + "qxh_Latn", # Panao Huánuco Quechua + "qxn_Latn", # Northern Conchucos Ancash Quechua + "qxo_Latn", # Southern Conchucos Ancash Quechua + "rai_Latn", # Ramoaaina + "reg_Latn", # Kara (Papua New Guinea) + "rgu_Latn", # Ringgou + "rkb_Latn", # Rikbaktsa + "rmc_Latn", # Carpathian Romani + "rmy_Latn", # Vlax Romani + "ron_Latn", # Romanian + "roo_Latn", # Rotokas + "rop_Latn", # Kriol + "row_Latn", # Dela-Oenale + "rro_Latn", # Waima + "ruf_Latn", # Luguru + "rug_Latn", # Roviana + "rus_Cyrl", # Russian + "rwo_Latn", # Rawa + "sab_Latn", # Buglere + "san_Latn", # Sanskrit + "sbe_Latn", # Saliba + "sbk_Latn", # Safwa + "sbs_Latn", # Subiya + "seh_Latn", # Sena + "sey_Latn", # Secoya + "sgb_Latn", # Ayta Mag-antsi + "sgz_Latn", # Sursurunga + "shj_Latn", # Shatt + "shp_Latn", # Shipibo-Conibo + "sim_Latn", # Mende (Papua New Guinea) + "sja_Latn", # Epena + "sll_Latn", # Salt-Yui + "smk_Latn", # Bolinao + "snc_Latn", # Sinaugoro + "snn_Latn", # Siona + "snp_Latn", # Siane + "snx_Latn", # Sam + "sny_Latn", # Saniyo-Hiyewe + "som_Latn", # Somali + "soq_Latn", # Kanasi + "soy_Latn", # Miyobe + "spa_Latn", # Spanish + "spl_Latn", # Selepet + "spm_Latn", # Akukem + "spp_Latn", # Supyire Senoufo + "sps_Latn", # Saposa + "spy_Latn", # Sabaot + "sri_Latn", # Siriano + "srm_Latn", # Saramaccan + "srn_Latn", # Sranan Tongo + "srp_Latn", # Serbian + "srq_Latn", # Sirionó + "ssd_Latn", # Siroi + "ssg_Latn", # Seimat + "ssx_Latn", # Samberigi + "stp_Latn", # Southeastern Tepehuan + "sua_Latn", # Sulka + "sue_Latn", # Suena + "sus_Arab", # Susu + "suz_Latn", # Sunwar + "swe_Latn", # Swedish + "swh_Latn", # Swahili (Kiswahili) + "swp_Latn", # Suau + "sxb_Latn", # Suba + "tac_Latn", # Lowland Tarahumara + "taj_Deva", # Tajik + "tam_Taml", # Tamil + "tav_Latn", # Tatuyo + "taw_Latn", # Tai + "tbc_Latn", # Takia + "tbf_Latn", # Mandara + "tbg_Latn", # North Tairora + "tbo_Latn", # Tawala + "tbz_Latn", # Ditammari + "tca_Latn", # Ticuna + "tcs_Latn", # Torres Strait Creole + "tcz_Latn", # Thado Chin + "tdt_Latn", # Tetun Dili + "tee_Latn", # Huehuetla Tepehua + "tel_Telu", # Telugu + "ter_Latn", # Terêna + "tet_Latn", # Tetum + "tew_Latn", # Tewa (USA) + "tfr_Latn", # Me'phaa + "tgk_Cyrl", # Tajik + "tgl_Latn", # Tagalog + "tgo_Latn", # Sudest + "tgp_Latn", # Tangoa + "tha_Thai", # Thai + "tif_Latn", # Tifal + "tim_Latn", # Timbe + "tiw_Latn", # Tiwi + "tiy_Latn", # Tiruray + "tke_Latn", # Tsikimba + "tku_Latn", # Upper Necaxa Totonac + "tlf_Latn", # Telefol + "tmd_Latn", # Haruai + "tna_Latn", # Tacana + "tnc_Latn", # Tanimuca-Retuarã + "tnk_Latn", # Kwamera + "tnn_Latn", # North Tanna + "tnp_Latn", # Whitesands + "toc_Latn", # Coyutla Totonac + "tod_Latn", # Toma + "tof_Latn", # Columbia-Wenatchi + "toj_Latn", # Tojolabal + "ton_Latn", # Tonga (Tonga Islands) + "too_Latn", # Xicotepec De Juárez Totonac + "top_Latn", # Papantla Totonac + "tos_Latn", # Highland Totonac + "tpa_Latn", # Taupota + "tpi_Latn", # Tok Pisin + "tpt_Latn", # Tlachichilco Tepehua + "tpz_Latn", # Tinputz + "trc_Latn", # Copala Triqui + "tsw_Latn", # Tsishingini + "ttc_Latn", # Tektiteko + "tte_Latn", # Bwanabwana + "tuc_Latn", # Mutu + "tue_Latn", # Tuyuca + "tuf_Latn", # Central Tunebo + "tuo_Latn", # Tucano + "tur_Latn", # Turkish + "tvk_Latn", # Southeast Ambrym + "twi_Latn", # Twi + "txq_Latn", # Tii + "txu_Latn", # Kayapó + "tzj_Latn", # Tz'utujil + "tzo_Latn", # Tzotzil + "ubr_Latn", # Ubir + "ubu_Latn", # Umbu-Ungu + "udu_Latn", # Uduk + "uig_Latn", # Uighur + "ukr_Cyrl", # Ukrainian + "uli_Latn", # Ulithian + "ulk_Latn", # Meriam + "upv_Latn", # Uripiv-Wala-Rano-Atchin + "ura_Latn", # Urarina + "urb_Latn", # Kaapor + "urd_Arab", # Urdu + "uri_Latn", # Urim + "urt_Latn", # Urartian + "urw_Latn", # Sop + "usa_Latn", # Usarufa + "usp_Latn", # Uspanteco + "uvh_Latn", # Uri + "uvl_Latn", # Lote + "vid_Latn", # Vidunda + "vie_Latn", # Vietnamese + "viv_Latn", # Iduna + "vmy_Latn", # Mixtec, many Mixtec languages use Latin script, though there are multiple variants of Mixtec. + "waj_Latn", # Waffa + "wal_Ethi", # Wolaytta, uses the Ethiopic script + "wap_Latn", # Wapishana + "wat_Latn", # Kaninuwa + "wbi_Latn", # Vwanji + "wbp_Latn", # Warlpiri + "wed_Latn", # Wedau + "wer_Latn", # Weri + "wim_Latn", # Wik-Mungkan + "wiu_Latn", # Wiru + "wiv_Latn", # Vitu + "wmt_Latn", # Mwani + "wmw_Latn", # Mwani + "wnc_Latn", # Wantoat + "wnu_Latn", # Usan + "wol_Latn", # Wolof, primarily uses Latin script but also uses Arabic in some contexts + "wos_Latn", # Hanga Hundi + "wrk_Latn", # Garrwa + "wro_Latn", # Worrorra + "wrs_Latn", # Waris + "wsk_Latn", # Waskia + "wuv_Latn", # Wuvulu-Aua + "xav_Latn", # Xavante + "xbi_Latn", # Kombio + "xed_Latn", # Hdi + "xla_Latn", # Kamula + "xnn_Latn", # Northern Kankanay + "xon_Latn", # Konkomba + "xsi_Latn", # Sio + "xtd_Latn", # Diuxi-Tilantongo Mixtec + "xtm_Latn", # Magdalena Peñasco Mixtec + "yaa_Latn", # Yaminahua + "yad_Latn", # Yagua + "yal_Latn", # Yalunka + "yap_Latn", # Yapese + "yaq_Latn", # Yaqui + "yby_Latn", # Yawalapití + "ycn_Latn", # Yucuna + "yka_Latn", # Yakan + "yle_Latn", # Yele + "yml_Latn", # Iamalele + "yon_Latn", # Yongkom + "yor_Latn", # Yoruba, primarily uses the Latin script + "yrb_Latn", # Yareba + "yre_Latn", # Yaouré + "yss_Latn", # Yessan-Mayo + "yuj_Latn", # Karkar-Yuri + "yut_Latn", # Yopno + "yuw_Latn", # Yau (Morobe Province) + "yva_Latn", # Yawa + "zaa_Latn", # Sierra de Juárez Zapotec + "zab_Latn", # San Juan Guelavía Zapotec + "zac_Latn", # Ocotlán Zapotec + "zad_Latn", # Cajonos Zapotec + "zai_Latn", # Isthmus Zapotec + "zaj_Latn", # Zaramo + "zam_Latn", # Miahuatlán Zapotec + "zao_Latn", # Ozolotepec Zapotec + "zap_Latn", # Zapotec, uses Latin script across many varieties + "zar_Latn", # Rincón Zapotec + "zas_Latn", # Santo Domingo Albarradas Zapotec + "zat_Latn", # Tabaa Zapotec + "zav_Latn", # Yatzachi Zapotec + "zaw_Latn", # Mitla Zapotec + "zca_Latn", # Coatecas Altas Zapotec + "zga_Latn", # Ganza + "zia_Latn", # Zia + "ziw_Latn", # Zigula + "zlm_Latn", # Malay (individual language), Latin script + "zos_Latn", # Francisco León Zoque + "zpc_Latn", # Choapan Zapotec + "zpl_Latn", # Lachixío Zapotec + "zpm_Latn", # Mixtepec Zapotec + "zpo_Latn", # Amatlán Zapotec + "zpq_Latn", # Zoogocho Zapotec + "zpu_Latn", # Yalálag Zapotec + "zpv_Latn", # Chichicapan Zapotec + "zpz_Latn", # Texmelucan Zapotec + "zsr_Latn", # Southern Rincon Zapotec + "ztq_Latn", # Quioquitani-Quierí Zapotec + "zty_Latn", # Yatee Zapotec + "zyp_Latn", # Zyphe Chin +] + +# train split because validation/test splits are extremely small in a lot of cases +_SPLIT = ["train"] + +_N = 256 + + +def extend_lang_pairs_english_centric() -> dict[str, list[str]]: + # add all language pairs with english as source or target + hf_lang_subset2isolang = {} + for lang in _LANGUAGES: + pair = f"eng_Latn-{lang}" + hf_lang_subset2isolang[pair] = ["eng-Latn", lang.replace("_", "-")] + pair = f"{lang}-eng_Latn" + hf_lang_subset2isolang[pair] = [lang.replace("_", "-"), "eng-Latn"] + return hf_lang_subset2isolang + + +_LANGUAGES_MAPPING = extend_lang_pairs_english_centric() + + +class BibleNLPBitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="BibleNLPBitextMining", + dataset={ + "path": "davidstap/biblenlp-corpus-mmteb", + "revision": "264a18480c529d9e922483839b4b9758e690b762", + "split": f"train[:{_N}]", + "trust_remote_code": True, + }, + description="Partial Bible translations in 829 languages, aligned by verse.", + reference="https://arxiv.org/abs/2304.09919", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_LANGUAGES_MAPPING, + main_score="f1", + # World English Bible (WEB) first draft 1997, finished 2020 + date=("1997-01-01", "2020-12-31"), + form=["written"], + domains=["Religious"], + task_subtypes=[], + license="CC-BY-SA-4.0", + socioeconomic_status="medium", + annotations_creators="expert-annotated", + dialect=[], + text_creation="created", + n_samples={"train": _N}, + avg_character_length={"train": 120}, + bibtex_citation="""@article{akerman2023ebible, + title={The eBible Corpus: Data and Model Benchmarks for Bible Translation for Low-Resource Languages}, + author={Akerman, Vesa and Baines, David and Daspit, Damien and Hermjakob, Ulf and Jang, Taeho and Leong, Colin and Martin, Michael and Mathew, Joel and Robie, Jonathan and Schwarting, Marcus}, + journal={arXiv preprint arXiv:2304.09919}, + year={2023} + }""", + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + + self.dataset = {} + seen_pairs = [] + for lang in self.hf_subsets: + # e.g. 'aai_Latn-eng_Latn' -> 'eng-aai' + hf_lang_name = self._transform_lang_name_hf(lang) + + if hf_lang_name in seen_pairs: + self.dataset[lang] = self.dataset[self._swap_substrings(lang)] + else: + dataset = datasets.load_dataset( + name=self._transform_lang_name_hf(lang), + **self.metadata_dict["dataset"], + ) + self.dataset[lang] = datasets.DatasetDict({"train": dataset}) + seen_pairs.append(hf_lang_name) + + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self) -> None: + # Convert to standard format + for lang in self.hf_subsets: + l1, l2 = [l.split("_")[0] for l in lang.split("-")] + + self.dataset[lang] = self.dataset[lang].rename_columns( + {l1: "sentence1", l2: "sentence2"} + ) + + @staticmethod + def _transform_lang_name_hf(lang): + # Transform language name to match huggingface configuration + langs = [l.split("_")[0] for l in lang.split("-")] + if langs[1] == "eng": + langs[0], langs[1] = langs[1], langs[0] + return "-".join(langs) + + @staticmethod + def _swap_substrings(string): + substring1, substring2 = string.split("-") + parts = string.split("-") + if substring1 in parts and substring2 in parts: + index1 = parts.index(substring1) + index2 = parts.index(substring2) + parts[index1], parts[index2] = parts[index2], parts[index1] + new_string = "-".join(parts) + return new_string + else: + return string diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/DiaBLaBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/DiaBLaBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..28745ca9e13534574fe96b5359bc013413b4374d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/DiaBLaBitextMining.py @@ -0,0 +1,76 @@ +from __future__ import annotations + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + + +class DiaBLaBitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="DiaBlaBitextMining", + dataset={ + "path": "rbawden/DiaBLa", + "revision": "5345895c56a601afe1a98519ce3199be60a27dba", + }, + description="English-French Parallel Corpus. DiaBLa is an English-French dataset for the evaluation of Machine Translation (MT) for informal, written bilingual dialogue.", + reference="https://inria.hal.science/hal-03021633", + type="BitextMining", + category="s2s", + eval_splits=["test"], + eval_langs={ + "fr-en": ["fra-Latn", "eng-Latn"], + "en-fr": ["eng-Latn", "fra-Latn"], + }, + main_score="f1", + date=("2016-01-01", "2017-12-31"), + form=["written"], + domains=["Social"], + task_subtypes=[], + license="CC BY-NC-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="created", + bibtex_citation=""" + @inproceedings{gonzalez2019diabla, + title={DiaBLa: A Corpus of Bilingual Spontaneous Written Dialogues for Machine Translation}, + author={González, Matilde and García, Clara and Sánchez, Lucía}, + booktitle={Proceedings of the 12th Language Resources and Evaluation Conference}, + pages={4192--4198}, + year={2019} + } + """, + n_samples={}, + avg_character_length={}, + ) + + def load_data(self, **kwargs): + """Load dataset from HuggingFace hub and convert it to the standard format.""" + if self.data_loaded: + return + + self.dataset = {} + + for lang in self.hf_subsets: + self.dataset[lang] = datasets.load_dataset(**self.metadata_dict["dataset"]) + + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self): + def create_columns(row): + """Put all French texts in column 'sentence1' and English texts in 'sentence2' column""" + row["orig_lang"] = row["utterance_meta"]["lang"] + row["sentence1"] = ( + row["orig"] if row["orig_lang"] == "french" else row["ref"] + ) + row["sentence2"] = ( + row["orig"] if not row["orig_lang"] == "french" else row["ref"] + ) + return row + + # Convert to standard format + for lang in self.hf_subsets: + self.dataset[lang] = self.dataset[lang].map(create_columns) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/FloresBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/FloresBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..9bf42b79e4e73ef36c280b02f0eff0c8637b88b7 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/FloresBitextMining.py @@ -0,0 +1,281 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = [ + "ace_Arab", + "bam_Latn", + "dzo_Tibt", + "hin_Deva", + "khm_Khmr", + "mag_Deva", + "pap_Latn", + "sot_Latn", + "tur_Latn", + "ace_Latn", + "ban_Latn", + "ell_Grek", + "hne_Deva", + "kik_Latn", + "mai_Deva", + "pbt_Arab", + "spa_Latn", + "twi_Latn", + "acm_Arab", + "bel_Cyrl", + "eng_Latn", + "hrv_Latn", + "kin_Latn", + "mal_Mlym", + "pes_Arab", + "srd_Latn", + "tzm_Tfng", + "acq_Arab", + "bem_Latn", + "epo_Latn", + "hun_Latn", + "kir_Cyrl", + "mar_Deva", + "plt_Latn", + "srp_Cyrl", + "uig_Arab", + "aeb_Arab", + "ben_Beng", + "est_Latn", + "hye_Armn", + "kmb_Latn", + "min_Arab", + "pol_Latn", + "ssw_Latn", + "ukr_Cyrl", + "afr_Latn", + "bho_Deva", + "eus_Latn", + "ibo_Latn", + "kmr_Latn", + "min_Latn", + "por_Latn", + "sun_Latn", + "umb_Latn", + "ajp_Arab", + "bjn_Arab", + "ewe_Latn", + "ilo_Latn", + "knc_Arab", + "mkd_Cyrl", + "prs_Arab", + "swe_Latn", + "urd_Arab", + "aka_Latn", + "bjn_Latn", + "fao_Latn", + "ind_Latn", + "knc_Latn", + "mlt_Latn", + "quy_Latn", + "swh_Latn", + "uzn_Latn", + "als_Latn", + "bod_Tibt", + "fij_Latn", + "isl_Latn", + "kon_Latn", + "mni_Beng", + "ron_Latn", + "szl_Latn", + "vec_Latn", + "amh_Ethi", + "bos_Latn", + "fin_Latn", + "ita_Latn", + "kor_Hang", + "mos_Latn", + "run_Latn", + "tam_Taml", + "vie_Latn", + "apc_Arab", + "bug_Latn", + "fon_Latn", + "jav_Latn", + "lao_Laoo", + "mri_Latn", + "rus_Cyrl", + "taq_Latn", + "war_Latn", + "arb_Arab", + "bul_Cyrl", + "fra_Latn", + "jpn_Jpan", + "lij_Latn", + "mya_Mymr", + "sag_Latn", + "taq_Tfng", + "wol_Latn", + "arb_Latn", + "cat_Latn", + "fur_Latn", + "kab_Latn", + "lim_Latn", + "nld_Latn", + "san_Deva", + "tat_Cyrl", + "xho_Latn", + "ars_Arab", + "ceb_Latn", + "fuv_Latn", + "kac_Latn", + "lin_Latn", + "nno_Latn", + "sat_Olck", + "tel_Telu", + "ydd_Hebr", + "ary_Arab", + "ces_Latn", + "gaz_Latn", + "kam_Latn", + "lit_Latn", + "nob_Latn", + "scn_Latn", + "tgk_Cyrl", + "yor_Latn", + "arz_Arab", + "cjk_Latn", + "gla_Latn", + "kan_Knda", + "lmo_Latn", + "npi_Deva", + "shn_Mymr", + "tgl_Latn", + "yue_Hant", + "asm_Beng", + "ckb_Arab", + "gle_Latn", + "kas_Arab", + "ltg_Latn", + "nso_Latn", + "sin_Sinh", + "tha_Thai", + "zho_Hans", + "ast_Latn", + "crh_Latn", + "glg_Latn", + "kas_Deva", + "ltz_Latn", + "nus_Latn", + "slk_Latn", + "tir_Ethi", + "zho_Hant", + "awa_Deva", + "cym_Latn", + "grn_Latn", + "kat_Geor", + "lua_Latn", + "nya_Latn", + "slv_Latn", + "tpi_Latn", + "zsm_Latn", + "ayr_Latn", + "dan_Latn", + "guj_Gujr", + "kaz_Cyrl", + "lug_Latn", + "oci_Latn", + "smo_Latn", + "tsn_Latn", + "zul_Latn", + "azb_Arab", + "deu_Latn", + "hat_Latn", + "kbp_Latn", + "luo_Latn", + "ory_Orya", + "sna_Latn", + "tso_Latn", + "azj_Latn", + "dik_Latn", + "hau_Latn", + "kea_Latn", + "lus_Latn", + "pag_Latn", + "snd_Arab", + "tuk_Latn", + "bak_Cyrl", + "dyu_Latn", + "heb_Hebr", + "khk_Cyrl", + "lvs_Latn", + "pan_Guru", + "som_Latn", + "tum_Latn", +] +_SPLIT = ["dev", "devtest"] + + +def extend_lang_pairs() -> dict[str, list[str]]: + # add all possible language pairs + hf_lang_subset2isolang = {} + for x in _LANGUAGES: + if "-" not in x: + for y in _LANGUAGES: + if x != y: + pair = f"{x}-{y}" + hf_lang_subset2isolang[pair] = [ + x.replace("_", "-"), + y.replace("_", "-"), + ] + return hf_lang_subset2isolang + + +_LANGUAGES_MAPPING = extend_lang_pairs() + + +class FloresBitextMining(AbsTaskBitextMining, CrosslingualTask): + parallel_subsets = True + metadata = TaskMetadata( + name="FloresBitextMining", + dataset={ + "path": "mteb/flores", + "revision": "e6b647fcb6299a2f686f742f4d4c023e553ea67e", + "trust_remote_code": True, + }, + description="FLORES is a benchmark dataset for machine translation between English and low-resource languages.", + reference="https://huggingface.co/datasets/facebook/flores", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_LANGUAGES_MAPPING, + main_score="f1", + date=("2022-01-01", "2022-12-31"), + form=["written"], + domains=["Non-fiction", "Encyclopaedic"], + task_subtypes=[], + license="CC BY-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="created", + bibtex_citation=""" + @inproceedings{goyal2022flores, + title={The FLORES-101 Evaluation Benchmark for Low-Resource and Multilingual Machine Translation}, + author={Goyal, Naman and Gao, Cynthia and Chaudhary, Vishrav and Chen, Peng-Jen and Wenzek, Guillaume and Ju, Da and Krishnan, Sanjana and Ranzato, Marc'Aurelio and Guzm{\'a}n, Francisco}, + booktitle={Proceedings of the 2022 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies}, + pages={19--35}, + year={2022} + } + """, + n_samples={"dev": 997, "devtest": 1012}, + avg_character_length={}, + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = datasets.load_dataset(**self.metadata_dict["dataset"]) + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IN22ConvBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IN22ConvBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..7cfcb6840e43ece89d77bbe502e3902a02d63265 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IN22ConvBitextMining.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = [ + "asm_Beng", + "ben_Beng", + "brx_Deva", + "doi_Deva", + "eng_Latn", + "gom_Deva", + "guj_Gujr", + "hin_Deva", + "kan_Knda", + "kas_Arab", + "mai_Deva", + "mal_Mlym", + "mar_Deva", + "mni_Mtei", + "npi_Deva", + "ory_Orya", + "pan_Guru", + "san_Deva", + "sat_Olck", + "snd_Deva", + "tam_Taml", + "tel_Telu", + "urd_Arab", +] +_SPLIT = ["test"] + + +def extend_lang_pairs() -> dict[str, list[str]]: + # add all possible language pairs + hf_lang_subset2isolang = {} + for x in _LANGUAGES: + for y in _LANGUAGES: + if x != y: + pair = f"{x}-{y}" + hf_lang_subset2isolang[pair] = [ + x.replace("_", "-"), + y.replace("_", "-"), + ] + return hf_lang_subset2isolang + + +_LANGUAGES_MAPPING = extend_lang_pairs() + + +def get_hash(text): + """Get hash of text field.""" + return {"hash": hash(text)} + + +def check_uniques(example, uniques): + """Check if current hash is still in set of unique hashes and remove if true.""" + if example["hash"] in uniques: + uniques.remove(example["hash"]) + return True + else: + return False + + +class IN22ConvBitextMining(AbsTaskBitextMining, CrosslingualTask): + parallel_subsets = True + metadata = TaskMetadata( + name="IN22ConvBitextMining", + dataset={ + "path": "mteb/IN22-Conv", + "revision": "16f46f059d56eac7c65c3c9581a45e40199eb140", + "trust_remote_code": True, + }, + description="IN22-Conv is a n-way parallel conversation domain benchmark dataset for machine translation spanning English and 22 Indic languages.", + reference="https://huggingface.co/datasets/ai4bharat/IN22-Conv", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_LANGUAGES_MAPPING, + main_score="f1", + date=("2022-10-01", "2023-03-01"), + form=["spoken"], + domains=["Social", "Spoken", "Fiction"], + task_subtypes=[], + license="CC-BY-4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="created", + bibtex_citation="""@article{gala2023indictrans, +title={IndicTrans2: Towards High-Quality and Accessible Machine Translation Models for all 22 Scheduled Indian Languages}, +author={Jay Gala and Pranjal A Chitale and A K Raghavan and Varun Gumma and Sumanth Doddapaneni and Aswanth Kumar M and Janki Atul Nawale and Anupama Sujatha and Ratish Puduppully and Vivek Raghavan and Pratyush Kumar and Mitesh M Khapra and Raj Dabre and Anoop Kunchukuttan}, +journal={Transactions on Machine Learning Research}, +issn={2835-8856}, +year={2023}, +url={https://openreview.net/forum?id=vfT4YuzAYA}, +note={} +}""", + n_samples={"test": 1503}, + avg_character_length={"test": 54.3}, + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = datasets.load_dataset(**self.metadata_dict["dataset"]) + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IN22GenBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IN22GenBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..7af06dbc9f64aa2df16d0792c2eb940751786571 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IN22GenBitextMining.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = [ + "asm_Beng", + "ben_Beng", + "brx_Deva", + "doi_Deva", + "eng_Latn", + "gom_Deva", + "guj_Gujr", + "hin_Deva", + "kan_Knda", + "kas_Arab", + "mai_Deva", + "mal_Mlym", + "mar_Deva", + "mni_Mtei", + "npi_Deva", + "ory_Orya", + "pan_Guru", + "san_Deva", + "sat_Olck", + "snd_Deva", + "tam_Taml", + "tel_Telu", + "urd_Arab", +] +_SPLIT = ["test"] + + +def extend_lang_pairs() -> dict[str, list[str]]: + # add all possible language pairs + hf_lang_subset2isolang = {} + for x in _LANGUAGES: + for y in _LANGUAGES: + if x != y: + pair = f"{x}-{y}" + hf_lang_subset2isolang[pair] = [ + x.replace("_", "-"), + y.replace("_", "-"), + ] + return hf_lang_subset2isolang + + +_LANGUAGES_MAPPING = extend_lang_pairs() + + +class IN22GenBitextMining(AbsTaskBitextMining, CrosslingualTask): + parallel_subsets = True + metadata = TaskMetadata( + name="IN22GenBitextMining", + dataset={ + "path": "mteb/IN22-Gen", + "revision": "ec381535fe3ddf699297a023bcecaa548096ed68", + "trust_remote_code": True, + }, + description="IN22-Gen is a n-way parallel general-purpose multi-domain benchmark dataset for machine translation spanning English and 22 Indic languages.", + reference="https://huggingface.co/datasets/ai4bharat/IN22-Gen", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_LANGUAGES_MAPPING, + main_score="f1", + date=("2022-10-01", "2023-03-01"), + form=["written"], + domains=["Web", "Legal", "Government", "News", "Religious", "Non-fiction"], + task_subtypes=[], + license="CC-BY-4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="created", + bibtex_citation="""@article{gala2023indictrans, +title={IndicTrans2: Towards High-Quality and Accessible Machine Translation Models for all 22 Scheduled Indian Languages}, +author={Jay Gala and Pranjal A Chitale and A K Raghavan and Varun Gumma and Sumanth Doddapaneni and Aswanth Kumar M and Janki Atul Nawale and Anupama Sujatha and Ratish Puduppully and Vivek Raghavan and Pratyush Kumar and Mitesh M Khapra and Raj Dabre and Anoop Kunchukuttan}, +journal={Transactions on Machine Learning Research}, +issn={2835-8856}, +year={2023}, +url={https://openreview.net/forum?id=vfT4YuzAYA}, +note={} +}""", + n_samples={"test": 1024}, + avg_character_length={"test": 156.7}, + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = datasets.load_dataset(**self.metadata_dict["dataset"]) + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IWSLT2017BitextMinig.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IWSLT2017BitextMinig.py new file mode 100644 index 0000000000000000000000000000000000000000..4fdf02f1213e9e2b9ec274d24e43ff2c8cdfe6b0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IWSLT2017BitextMinig.py @@ -0,0 +1,115 @@ +from __future__ import annotations + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = { + "ar-en": ["ara-Arab", "eng-Latn"], + "de-en": ["deu-Latn", "eng-Latn"], + "en-ar": ["eng-Latn", "ara-Arab"], + "en-de": ["eng-Latn", "deu-Latn"], + "en-fr": ["eng-Latn", "fra-Latn"], + "en-it": ["eng-Latn", "ita-Latn"], + "en-ja": ["eng-Latn", "jpn-Jpan"], + "en-ko": ["eng-Latn", "kor-Hang"], + "en-nl": ["eng-Latn", "nld-Latn"], + "en-ro": ["eng-Latn", "ron-Latn"], + "en-zh": ["eng-Latn", "cmn-Hans"], + "fr-en": ["fra-Latn", "eng-Latn"], + "it-en": ["ita-Latn", "eng-Latn"], + "it-nl": ["ita-Latn", "nld-Latn"], + "it-ro": ["ita-Latn", "ron-Latn"], + "ja-en": ["jpn-Jpan", "eng-Latn"], + "ko-en": ["kor-Hang", "eng-Latn"], + "nl-en": ["nld-Latn", "eng-Latn"], + "nl-it": ["nld-Latn", "ita-Latn"], + "nl-ro": ["nld-Latn", "ron-Latn"], + "ro-en": ["ron-Latn", "eng-Latn"], + "ro-it": ["ron-Latn", "ita-Latn"], + "ro-nl": ["ron-Latn", "nld-Latn"], + "zh-en": ["cmn-Hans", "eng-Latn"], +} + +_SPLITS = ["validation"] + + +class IWSLT2017BitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="IWSLT2017BitextMining", + dataset={ + "path": "IWSLT/iwslt2017", + "revision": "c18a4f81a47ae6fa079fe9d32db288ddde38451d", + }, + description="The IWSLT 2017 Multilingual Task addresses text translation, including zero-shot translation, with a single MT system across all directions including English, German, Dutch, Italian and Romanian.", + reference="https://aclanthology.org/2017.iwslt-1.1/", + type="BitextMining", + category="s2s", + eval_splits=_SPLITS, + eval_langs=_LANGUAGES, + main_score="f1", + date=("2007-01-01", "2017-12-14"), # rough estimate + form=["written"], + domains=["Non-fiction", "Fiction"], + task_subtypes=[], + license="CC-BY-NC-ND-4.0", + socioeconomic_status="medium", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" +@inproceedings{cettolo-etal-2017-overview, + title = "Overview of the {IWSLT} 2017 Evaluation Campaign", + author = {Cettolo, Mauro and + Federico, Marcello and + Bentivogli, Luisa and + Niehues, Jan and + St{\"u}ker, Sebastian and + Sudoh, Katsuhito and + Yoshino, Koichiro and + Federmann, Christian}, + editor = "Sakti, Sakriani and + Utiyama, Masao", + booktitle = "Proceedings of the 14th International Conference on Spoken Language Translation", + month = dec # " 14-15", + year = "2017", + address = "Tokyo, Japan", + publisher = "International Workshop on Spoken Language Translation", + url = "https://aclanthology.org/2017.iwslt-1.1", + pages = "2--14", +} +""", + n_samples={"validation": 21928}, + avg_character_length={"validation": 95.4}, + ) + + def load_data(self, **kwargs): + """Load dataset from HuggingFace hub and convert it to the standard format.""" + if self.data_loaded: + return + + self.dataset = {} + for lang in self.hf_subsets: + self.dataset[lang] = datasets.load_dataset( + split=_SPLITS, + name=f"iwslt2017-{lang}", + **self.metadata_dict["dataset"], + ) + + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self): + def create_columns(row, lang): + l1, l2 = lang.split("-") + row["sentence1"] = row["translation"][l1] + row["sentence2"] = row["translation"][l2] + return row + + # Convert to standard format + for lang in self.hf_subsets: + self.dataset[lang] = self.dataset[lang].map( + lambda x: create_columns(x, lang=lang) + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IndicGenBenchFloresBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IndicGenBenchFloresBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..69890e51cb10625ace3b97375d18499af56581d1 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/IndicGenBenchFloresBitextMining.py @@ -0,0 +1,171 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = [ + "ben-Beng", + "guj_Gujr", + "hin_Deva", + "kan_Knda", + "mal_Mlym", + "mar_Deva", + "tam_Taml", + "tel_Telu", + "urd_Arab", + "asm_Beng", + "bho_Deva", + "nep_Deva", + "ory_Orya", + "pan_Guru", + "pus_Arab", + "san-Deva", + "awa_Deva", + "bgc_Deva", + "bod_Tibt", + "boy_Deva", + "gbm_Deva", + "gom_Deva", + "hne_Deva", + "raj_Deva", + "mai_Deva", + "mni_Mtei", + "mup_Deva", + "mwr_Deva", + "sat_Olck", +] + +_ENG_LANGUAGE = ["eng-Latn"] + +_CODE_MAPPING = { + "ben": "bn", + "guj": "gu", + "hin": "hi", + "kan": "kn", + "mal": "ml", + "mar": "mr", + "tam": "ta", + "tel": "te", + "urd": "ur", + "asm": "as", + "bho": "bho", + "nep": "ne", + "ory": "or", + "pan": "pa", + "pus": "ps", + "san": "sa", + "awa": "awa", + "bgc": "bgc", + "bod": "bo", + "boy": "brx", + "gbm": "gbm", + "gom": "gom", + "hne": "hne", + "raj": "hoj", + "mai": "mai", + "mni": "mni", + "mup": "mup", + "mwr": "mwr", + "sat": "sat", +} + +_SPLIT = ["validation", "test"] + + +def get_lang_pairs() -> dict[str, list[str]]: + # add eng-> xx and xx -> eng lang pairs + # Normalize language codes + normalized_languages = [lang.replace("_", "-") for lang in _LANGUAGES] + + # Create dictionary for language pairs + language_pairs = {} + for lang in normalized_languages: + lang_code = lang.split("-")[0] + lang_to_eng_key = f"{lang_code}-eng" + eng_to_lang_key = f"eng-{lang_code}" + language_pairs[lang_to_eng_key] = [lang, _ENG_LANGUAGE[0]] + language_pairs[eng_to_lang_key] = [_ENG_LANGUAGE[0], lang] + + return language_pairs + + +_LANGUAGES_MAPPING = get_lang_pairs() + + +class IndicGenBenchFloresBitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="IndicGenBenchFloresBitextMining", + dataset={ + "path": "google/IndicGenBench_flores_in", + "revision": "f8650438298df086750ff4973661bb58a201a5ee", + "trust_remote_code": True, + }, + description="Flores-IN dataset is an extension of Flores dataset released as a part of the IndicGenBench by Google", + reference="https://github.com/google-research-datasets/indic-gen-bench/", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_LANGUAGES_MAPPING, + main_score="f1", + date=("2023-10-01", "2024-05-01"), + form=["written"], + domains=["Web", "News"], + task_subtypes=[], + license="CC-BY-SA-4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="human-translated and localized", + bibtex_citation="""@misc{singh2024indicgenbench, + title={IndicGenBench: A Multilingual Benchmark to Evaluate Generation Capabilities of LLMs on Indic Languages}, + author={Harman Singh and Nitish Gupta and Shikhar Bharadwaj and Dinesh Tewari and Partha Talukdar}, + year={2024}, + eprint={2404.16816}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +}""", + n_samples={"validation": 997, "test": 1012}, + avg_character_length={"validation": 126.25, "test": 130.84}, + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + + self.dataset = {} + for lang in self.hf_subsets: + langs = lang.split("-") + source_lang = langs[0] + target_lang = langs[1] + if source_lang == "eng": + coded_target_language = _CODE_MAPPING[target_lang] + language = f"en_{coded_target_language}" + + else: + coded_source_language = _CODE_MAPPING[source_lang] + language = f"{coded_source_language}_en" + + self.dataset[lang] = datasets.load_dataset( + **self.metadata_dict["dataset"], + field="examples", + data_files={ + "validation": f"flores_{language}_dev.json", + "test": f"flores_{language}_test.json", + }, + ) + + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self) -> None: + for lang in self.hf_subsets: + for split in _SPLIT: + self.dataset[lang][split] = self.dataset[lang][split].rename_columns( + {"source": "sentence1", "target": "sentence2"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/NTREXBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/NTREXBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..91cc04196bd6a16ba2457f9623879c87d3e0ec51 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/NTREXBitextMining.py @@ -0,0 +1,294 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks import AbsTaskBitextMining, CrosslingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + +_BRIDGE_LANGUAGES = ( + "arb_Arab", + "ben_Beng", + "deu_Latn", + "ell_Grek", + "eng_Latn", + "fas_Arab", + "fin_Latn", + "fra_Latn", + "heb_Hebr", + "hin_Deva", + "hun_Latn", + "ind_Latn", + "jpn_Jpan", + "kor_Hang", + "lit_Latn", + "nld_Latn", + "pol_Latn", + "por_Latn", + "rus_Cyrl", + "spa_Latn", + "swa_Latn", + "swe_Latn", + "tam_Taml", + "tur_Latn", + "vie_Latn", + "zho_Hant", + "zul_Latn", +) + +# Mapping from ISO 639-3 + script to ISO 639-1 used in NTREX +_LANGUAGES = { + "afr_Latn": {"group": "Germanic"}, + "amh_Ethi": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "arb_Arab": {"group": "Arabic/Semitic/Iranian"}, + "aze_Latn": {"group": "Turkic"}, + "bak_Cyrl": {"group": "Turkic"}, + "bel_Cyrl": {"group": "Slavic"}, + # Manually added to group (not in M2M100 languages) + "bem_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + "ben_Beng": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "bod_Tibt": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + "bos_Latn": {"group": "Slavic"}, + "bul_Cyrl": {"group": "Slavic"}, + "cat_Latn": {"group": "Romance"}, + # Manually added to group (not in M2M100 languages) + "ces_Latn": {"group": "Slavic"}, + # Manually added to group (not in M2M100 languages) + "ckb_Arab": {"group": "Arabic/Semitic/Iranian"}, + "cym_Latn": {"group": "Celtic/Irish"}, + "dan_Latn": {"group": "Germanic"}, + "deu_Latn": {"group": "Germanic"}, + # Manually added to group (not in M2M100 languages) + "div_Thaa": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "dzo_Tibt": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + "ell_Grek": {"group": "Albanian/Armenian/Kartvelian/Hellenic"}, + "eng_Latn": {"group": "Germanic"}, + # Manually added to group (not in M2M100 languages), Basque closest to Indo-European + "eus_Latn": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "ewe_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "fao_Latn": {"group": "Germanic"}, + # new BitextMining language + "fas_Arab": {"group": "Arabic/Semitic/Iranian"}, + # Manually added to group (not in M2M100 languages) + "fij_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "fil_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + "fin_Latn": {"group": "Uralic/Baltic"}, + "fra_Latn": {"group": "Romance"}, + # Manually added to group (not in M2M100 languages) + "fuc_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "gle_Latn": {"group": "Celtic/Irish"}, + "glg_Latn": {"group": "Romance"}, + "guj_Gujr": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "hau_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "heb_Hebr": {"group": "Arabic/Semitic/Iranian"}, + "hin_Deva": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "hmn_Latn": {"group": "Hmong-Mien"}, + "hrv_Latn": {"group": "Slavic"}, + "hun_Latn": {"group": "Uralic/Baltic"}, + "hye_Armn": {"group": "Albanian/Armenian/Kartvelian/Hellenic"}, + "ibo_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "ind_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + "isl_Latn": {"group": "Germanic"}, + "ita_Latn": {"group": "Romance"}, + "jpn_Jpan": {"group": "Japonic/Koreanic/Vietic/Chinese"}, + "kan_Knda": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "kat_Geor": {"group": "Albanian/Armenian/Kartvelian/Hellenic"}, + "kaz_Cyrl": {"group": "Turkic"}, + "khm_Khmr": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + # Manually added to group (not in M2M100 languages) + "kin_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "kir_Cyrl": {"group": "Turkic"}, + # Manually added to group (not in M2M100 languages) + "kmr_Latn": {"group": "Arabic/Semitic/Iranian"}, + "kor_Hang": {"group": "Japonic/Koreanic/Vietic/Chinese"}, + "lao_Laoo": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + # new BitextMining language + "lav_Latn": {"group": "Uralic/Baltic"}, + "lit_Latn": {"group": "Uralic/Baltic"}, + # Manually added to group (not in M2M100 languages) + "ltz_Latn": {"group": "Germanic"}, + "mal_Mlym": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + "mar_Deva": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "mey_Arab": {"group": "Arabic/Semitic/Iranian"}, + "mkd_Cyrl": {"group": "Slavic"}, + # new BitextMining language + "mlg_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "mlt_Latn": {"group": "Romance"}, + "mon_Mong": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + # Manually added to group (not in M2M100 languages) + "mri_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + # new BitextMining language + "msa_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + "mya_Mymr": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + # Manually added to group (not in M2M100 languages) + "nde_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + # new BitextMining language + "nep_Deva": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "nld_Latn": {"group": "Germanic"}, + # Manually added to group (not in M2M100 languages) + "nno_Latn": {"group": "Germanic"}, + "nob_Latn": {"group": "Germanic"}, + "nso_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "nya_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "orm_Ethi": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "pan_Guru": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "pol_Latn": {"group": "Slavic"}, + "por_Latn": {"group": "Romance"}, + # Manually added to group (not in M2M100 languages) + "prs_Arab": {"group": "Arabic/Semitic/Iranian"}, + # new BitextMining language + "pus_Arab": {"group": "Arabic/Semitic/Iranian"}, + "ron_Latn": {"group": "Romance"}, + "rus_Cyrl": {"group": "Slavic"}, + # Manually added to group (not in M2M100 languages) + "shi_Arab": {"group": "Arabic/Semitic/Iranian"}, + "sin_Sinh": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "slk_Latn": {"group": "Slavic"}, + "slv_Latn": {"group": "Slavic"}, + # Manually added to group (not in M2M100 languages) + "smo_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "sna_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "snd_Arab": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "som_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "spa_Latn": {"group": "Romance"}, + "sqi_Latn": {"group": "Albanian/Armenian/Kartvelian/Hellenic"}, + # new BitextMining language (only srp_Latn available) + "srp_Cyrl": {"group": "Slavic"}, + # Manually added to group (not in M2M100 languages) + "srp_Latn": {"group": "Slavic"}, + "ssw_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + # new BitextMining language + "swa_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "swe_Latn": {"group": "Germanic"}, + # Manually added to group (not in M2M100 languages) + "tah_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + "tam_Taml": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "tat_Cyrl": {"group": "Turkic"}, + # Manually added to group (not in M2M100 languages) + "tel_Telu": {"group": "Indo-Aryan/Tamil/Dravidian"}, + # Manually added to group (not in M2M100 languages) + "tgk_Cyrl": {"group": "Arabic/Semitic/Iranian"}, + "tha_Thai": {"group": "Sino-Tibetan/Khmer/Kra-Dai/Mongolic"}, + # Manually added to group (not in M2M100 languages) + "tir_Ethi": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "ton_Latn": {"group": "Malayo-Polyn/Philippine/Dravidian"}, + "tsn_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "tuk_Latn": {"group": "Turkic"}, + "tur_Latn": {"group": "Turkic"}, + # Manually added to group (not in M2M100 languages) + "uig_Arab": {"group": "Turkic"}, + "ukr_Cyrl": {"group": "Slavic"}, + "urd_Arab": {"group": "Indo-Aryan/Tamil/Dravidian"}, + "uzb_Latn": {"group": "Turkic"}, + # Manually added to group (not in M2M100 languages) + "ven_Latn": {"group": "Niger-Congo/Afro-Asiatic/Cushitic"}, + "vie_Latn": {"group": "Japonic/Koreanic/Vietic/Chinese"}, + "wol_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "xho_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + "yor_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, + # Manually added to group (not in M2M100 languages) + "yue_Hant": {"group": "Japonic/Koreanic/Vietic/Chinese"}, + "zho_Hans": {"group": "Japonic/Koreanic/Vietic/Chinese"}, + "zho_Hant": {"group": "Japonic/Koreanic/Vietic/Chinese"}, + "zul_Latn": {"group": "Ethiopian/Niger-Congo/Afro-Asiatic/Cushitic"}, +} + +_SPLIT = ["test"] + +# number of sentences to use for evaluation +_N = 1997 + + +def extend_lang_pairs() -> dict[str, list[str]]: + """Add language pairs according to M2M-100 language grouping strategy. A pair is only included if: + - source or target is English; or + - source or target is a bridge language; or + - source and target are from same language grouping + """ + hf_lang_subset2isolang = {} + for x in _LANGUAGES.keys(): + for y in _LANGUAGES.keys(): + if x != y: + if ( + ("eng_Latn" in (x, y)) + or (all(var in _BRIDGE_LANGUAGES for var in (x, y))) + or (_LANGUAGES[x]["group"] == _LANGUAGES[y]["group"]) + ): + pair = f"{x}-{y}" + hf_lang_subset2isolang[pair] = [ + x.replace("_", "-"), + y.replace("_", "-"), + ] + return hf_lang_subset2isolang + + +_EVAL_LANGS = extend_lang_pairs() + + +class NTREXBitextMining(AbsTaskBitextMining, CrosslingualTask): + parallel_subsets = True + metadata = TaskMetadata( + name="NTREXBitextMining", + dataset={ + "path": "mteb/NTREX", + "revision": "ed9a4403ed4adbfaf4aab56d5b2709e9f6c3ba33", + "trust_remote_code": True, + }, + description="NTREX is a News Test References dataset for Machine Translation Evaluation, covering translation from English into 128 languages. We select language pairs according to the M2M-100 language grouping strategy, resulting in 1916 directions.", + reference="https://huggingface.co/datasets/davidstap/NTREX", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_EVAL_LANGS, + main_score="f1", + # publication date newstest19 until publication date NTREX paper + date=("2019-08-01", "2022-11-01"), + form=["written"], + domains=["News"], + task_subtypes=[], + license="CC-BY-SA-4.0", + socioeconomic_status="medium", + annotations_creators="expert-annotated", + dialect=[], + text_creation="human-translated and localized", + n_samples={"test": _N * len(_EVAL_LANGS)}, + avg_character_length={"test": 120}, + bibtex_citation=""" +@inproceedings{federmann-etal-2022-ntrex, + title = "{NTREX}-128 {--} News Test References for {MT} Evaluation of 128 Languages", + author = "Federmann, Christian and Kocmi, Tom and Xin, Ying", + booktitle = "Proceedings of the First Workshop on Scaling Up Multilingual Evaluation", + month = "nov", + year = "2022", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2022.sumeval-1.4", + pages = "21--24", +} +""", + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = datasets.load_dataset(**self.metadata_dict["dataset"]) + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/RomaTalesBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/RomaTalesBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..dd6d7a74f7f1022596fa670d171f4f603a161494 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/RomaTalesBitextMining.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +import datasets + +from mteb.abstasks import AbsTaskBitextMining, CrosslingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class RomaTalesBitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="RomaTalesBitextMining", + dataset={ + "path": "kardosdrur/roma-tales", + "revision": "f4394dbca6845743cd33eba77431767b232ef489", + }, + description="Parallel corpus of Roma Tales in Lovari with Hungarian translations.", + reference="https://idoc.pub/documents/idocpub-zpnxm9g35ylv", + type="BitextMining", + category="s2s", + eval_splits=["test"], + eval_langs={"rom-hun": ["rom-Latn", "hun-Latn"]}, + main_score="f1", + date=( + "1800-01-01", + "1950-12-31", + ), # Broad historical range for the creation of folk tales + form=["written"], + domains=["Fiction"], + task_subtypes=[], + license="Not specified", + socioeconomic_status="low", + annotations_creators="expert-annotated", + dialect=["Lovari"], + text_creation="created", + bibtex_citation="", + n_samples={"test": 215}, + avg_character_length={"test": 316.8046511627907}, + ) + + def load_data(self, **kwargs): + """Load dataset from HuggingFace hub and convert it to the standard format.""" + if self.data_loaded: + return + + self.dataset = {} + for lang in self.hf_subsets: + self.dataset[lang] = datasets.load_dataset(**self.metadata_dict["dataset"]) + + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self): + for lang in self.hf_subsets: + self.dataset[lang] = self.dataset[lang].rename_columns( + {"romani": "sentence1", "hungarian": "sentence2"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/TatoebaBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/TatoebaBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..46445f7110c1c1320a26cfc138666d29e6ad8651 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/TatoebaBitextMining.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskBitextMining, CrosslingualTask + +_LANGUAGES = { + "sqi-eng": ["sqi-Latn", "eng-Latn"], + "fry-eng": ["fry-Latn", "eng-Latn"], + "kur-eng": ["kur-Latn", "eng-Latn"], + "tur-eng": ["tur-Latn", "eng-Latn"], + "deu-eng": ["deu-Latn", "eng-Latn"], + "nld-eng": ["nld-Latn", "eng-Latn"], + "ron-eng": ["ron-Latn", "eng-Latn"], + "ang-eng": ["ang-Latn", "eng-Latn"], + "ido-eng": ["ido-Latn", "eng-Latn"], + "jav-eng": ["jav-Latn", "eng-Latn"], + "isl-eng": ["isl-Latn", "eng-Latn"], + "slv-eng": ["slv-Latn", "eng-Latn"], + "cym-eng": ["cym-Latn", "eng-Latn"], + "kaz-eng": ["kaz-Cyrl", "eng-Latn"], + "est-eng": ["est-Latn", "eng-Latn"], + "heb-eng": ["heb-Hebr", "eng-Latn"], + "gla-eng": ["gla-Latn", "eng-Latn"], + "mar-eng": ["mar-Deva", "eng-Latn"], + "lat-eng": ["lat-Latn", "eng-Latn"], + "bel-eng": ["bel-Cyrl", "eng-Latn"], + "pms-eng": ["pms-Latn", "eng-Latn"], + "gle-eng": ["gle-Latn", "eng-Latn"], + "pes-eng": ["pes-Arab", "eng-Latn"], + "nob-eng": ["nob-Latn", "eng-Latn"], + "bul-eng": ["bul-Cyrl", "eng-Latn"], + "cbk-eng": ["cbk-Latn", "eng-Latn"], + "hun-eng": ["hun-Latn", "eng-Latn"], + "uig-eng": ["uig-Arab", "eng-Latn"], + "rus-eng": ["rus-Cyrl", "eng-Latn"], + "spa-eng": ["spa-Latn", "eng-Latn"], + "hye-eng": ["hye-Armn", "eng-Latn"], + "tel-eng": ["tel-Telu", "eng-Latn"], + "afr-eng": ["afr-Latn", "eng-Latn"], + "mon-eng": ["mon-Cyrl", "eng-Latn"], + "arz-eng": ["arz-Arab", "eng-Latn"], + "hrv-eng": ["hrv-Latn", "eng-Latn"], + "nov-eng": ["nov-Latn", "eng-Latn"], + "gsw-eng": ["gsw-Latn", "eng-Latn"], + "nds-eng": ["nds-Latn", "eng-Latn"], + "ukr-eng": ["ukr-Cyrl", "eng-Latn"], + "uzb-eng": ["uzb-Latn", "eng-Latn"], + "lit-eng": ["lit-Latn", "eng-Latn"], + "ina-eng": ["ina-Latn", "eng-Latn"], + "lfn-eng": ["lfn-Latn", "eng-Latn"], + "zsm-eng": ["zsm-Latn", "eng-Latn"], + "ita-eng": ["ita-Latn", "eng-Latn"], + "cmn-eng": ["cmn-Hans", "eng-Latn"], + "lvs-eng": ["lvs-Latn", "eng-Latn"], + "glg-eng": ["glg-Latn", "eng-Latn"], + "ceb-eng": ["ceb-Latn", "eng-Latn"], + "bre-eng": ["bre-Latn", "eng-Latn"], + "ben-eng": ["ben-Beng", "eng-Latn"], + "swg-eng": ["swg-Latn", "eng-Latn"], + "arq-eng": ["arq-Arab", "eng-Latn"], + "kab-eng": ["kab-Latn", "eng-Latn"], + "fra-eng": ["fra-Latn", "eng-Latn"], + "por-eng": ["por-Latn", "eng-Latn"], + "tat-eng": ["tat-Cyrl", "eng-Latn"], + "oci-eng": ["oci-Latn", "eng-Latn"], + "pol-eng": ["pol-Latn", "eng-Latn"], + "war-eng": ["war-Latn", "eng-Latn"], + "aze-eng": ["aze-Latn", "eng-Latn"], + "vie-eng": ["vie-Latn", "eng-Latn"], + "nno-eng": ["nno-Latn", "eng-Latn"], + "cha-eng": ["cha-Latn", "eng-Latn"], + "mhr-eng": ["mhr-Cyrl", "eng-Latn"], + "dan-eng": ["dan-Latn", "eng-Latn"], + "ell-eng": ["ell-Grek", "eng-Latn"], + "amh-eng": ["amh-Ethi", "eng-Latn"], + "pam-eng": ["pam-Latn", "eng-Latn"], + "hsb-eng": ["hsb-Latn", "eng-Latn"], + "srp-eng": ["srp-Cyrl", "eng-Latn"], + "epo-eng": ["epo-Latn", "eng-Latn"], + "kzj-eng": ["kzj-Latn", "eng-Latn"], + "awa-eng": ["awa-Deva", "eng-Latn"], + "fao-eng": ["fao-Latn", "eng-Latn"], + "mal-eng": ["mal-Mlym", "eng-Latn"], + "ile-eng": ["ile-Latn", "eng-Latn"], + "bos-eng": ["bos-Latn", "eng-Latn"], + "cor-eng": ["cor-Latn", "eng-Latn"], + "cat-eng": ["cat-Latn", "eng-Latn"], + "eus-eng": ["eus-Latn", "eng-Latn"], + "yue-eng": ["yue-Hant", "eng-Latn"], + "swe-eng": ["swe-Latn", "eng-Latn"], + "dtp-eng": ["dtp-Latn", "eng-Latn"], + "kat-eng": ["kat-Geor", "eng-Latn"], + "jpn-eng": ["jpn-Jpan", "eng-Latn"], + "csb-eng": ["csb-Latn", "eng-Latn"], + "xho-eng": ["xho-Latn", "eng-Latn"], + "orv-eng": ["orv-Cyrl", "eng-Latn"], + "ind-eng": ["ind-Latn", "eng-Latn"], + "tuk-eng": ["tuk-Latn", "eng-Latn"], + "max-eng": ["max-Deva", "eng-Latn"], + "swh-eng": ["swh-Latn", "eng-Latn"], + "hin-eng": ["hin-Deva", "eng-Latn"], + "dsb-eng": ["dsb-Latn", "eng-Latn"], + "ber-eng": ["ber-Tfng", "eng-Latn"], + "tam-eng": ["tam-Taml", "eng-Latn"], + "slk-eng": ["slk-Latn", "eng-Latn"], + "tgl-eng": ["tgl-Latn", "eng-Latn"], + "ast-eng": ["ast-Latn", "eng-Latn"], + "mkd-eng": ["mkd-Cyrl", "eng-Latn"], + "khm-eng": ["khm-Khmr", "eng-Latn"], + "ces-eng": ["ces-Latn", "eng-Latn"], + "tzl-eng": ["tzl-Latn", "eng-Latn"], + "urd-eng": ["urd-Arab", "eng-Latn"], + "ara-eng": ["ara-Arab", "eng-Latn"], + "kor-eng": ["kor-Hang", "eng-Latn"], + "yid-eng": ["yid-Hebr", "eng-Latn"], + "fin-eng": ["fin-Latn", "eng-Latn"], + "tha-eng": ["tha-Thai", "eng-Latn"], + "wuu-eng": ["wuu-Hans", "eng-Latn"], +} + + +class TatoebaBitextMining(AbsTaskBitextMining, CrosslingualTask): + fast_loading = True + metadata = TaskMetadata( + name="Tatoeba", + dataset={ + "path": "mteb/tatoeba-bitext-mining", + "revision": "69e8f12da6e31d59addadda9a9c8a2e601a0e282", + }, + description="1,000 English-aligned sentence pairs for each language based on the Tatoeba corpus", + reference="https://github.com/facebookresearch/LASER/tree/main/data/tatoeba/v1", + type="BitextMining", + category="s2s", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="f1", + date=("2006-01-01", "2021-12-31"), # Estimated range + form=["written"], + domains=[], # Tatoeba corpus includes a wide range of topics and domains + task_subtypes=[], + license="CC BY 2.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], # No specific dialect mentioned + text_creation="found", + bibtex_citation=""" + @misc{tatoeba, + author = {Tatoeba community}, + title = {Tatoeba: Collection of sentences and translations}, + year = {2021}, + } + """, + n_samples={"test": 2000}, + avg_character_length={"test": 39.4}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/multilingual/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/srn/SRNCorpusBitextMining.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/srn/SRNCorpusBitextMining.py new file mode 100644 index 0000000000000000000000000000000000000000..367b1ec28f11c91c82f73b6ba21d03bf43b05790 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/BitextMining/srn/SRNCorpusBitextMining.py @@ -0,0 +1,83 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks import AbsTaskBitextMining, CrosslingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + +_LANGUAGES = { + "nld_Latn": "nl", + "srn_Latn": "srn", +} +_SPLIT = ["test"] + +# number of sentences to use for evaluation (256 is full test set) +_N = 256 + +_EVAL_LANGS = { + "srn_Latn-nld_Latn": ["srn-Latn", "nld-Latn"], + "nld_Latn-srn_Latn": ["nld-Latn", "srn-Latn"], +} + + +class SRNCorpusBitextMining(AbsTaskBitextMining, CrosslingualTask): + metadata = TaskMetadata( + name="SRNCorpusBitextMining", + dataset={ + "path": "davidstap/sranantongo", + "revision": "2903226ff89ca0b15221a75d32b6355248295119", + "trust_remote_code": True, + }, + description="SRNCorpus is a machine translation corpus for creole language Sranantongo and Dutch.", + reference="https://arxiv.org/abs/2212.06383", + type="BitextMining", + category="s2s", + eval_splits=_SPLIT, + eval_langs=_EVAL_LANGS, + main_score="f1", + date=("2022-04-01", "2022-07-31"), + form=["written"], + domains=["Social", "Web"], + task_subtypes=[], + license="CC-BY-SA-4.0", + socioeconomic_status="medium", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + n_samples={"test": _N}, + avg_character_length={"test": 55}, + bibtex_citation=""" +@article{zwennicker2022towards, + title={Towards a general purpose machine translation system for Sranantongo}, + author={Zwennicker, Just and Stap, David}, + journal={arXiv preprint arXiv:2212.06383}, + year={2022} +} +""", + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = {} + + def _clean_columns(batch, keys): + """Clean dataset features""" + return {key: [s.strip("\r") for s in batch[key]] for key in keys} + + for lang in self.hf_subsets: + l1, l2 = lang.split("-") + dataset = datasets.load_dataset( + name="srn-nl_other", + split="test", + **self.metadata_dict["dataset"], + ).map(lambda batch: _clean_columns(batch, ["nl", "srn"]), batched=True) + dataset = dataset.rename_columns( + {_LANGUAGES[l1]: "sentence1", _LANGUAGES[l2]: "sentence2"} + ) + self.dataset[lang] = datasets.DatasetDict({"test": dataset}) + + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/OnlineStoreReviewSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/OnlineStoreReviewSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..13b3c34f04ae287cc4b4f2bb637e5bdd829c58fc --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/OnlineStoreReviewSentimentClassification.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +N_SAMPLES = 2048 + + +class OnlineStoreReviewSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="OnlineStoreReviewSentimentClassification", + dataset={ + "path": "Ruqiya/Arabic_Reviews_of_SHEIN", + "revision": "8ea114aa27b82a52373203830dc2f5b540b6fcac", + }, + description="This dataset contains Arabic reviews of products from the SHEIN online store.", + reference="https://huggingface.co/datasets/Ruqiya/Arabic_Reviews_of_SHEIN", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["ara-Arab"], + main_score="accuracy", + date=("2024-05-01", "2024-05-15"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=["ara-Arab-SA"], + text_creation="found", + bibtex_citation="", + n_samples={"train": N_SAMPLES}, + avg_character_length={"train": 137.2}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/RestaurantReviewSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/RestaurantReviewSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..01dc8a0bc512728e6aa04a3e353d4b505379499d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/RestaurantReviewSentimentClassification.py @@ -0,0 +1,51 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +N_SAMPLES = 2048 + + +class RestaurantReviewSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="RestaurantReviewSentimentClassification", + dataset={ + "path": "hadyelsahar/ar_res_reviews", + "revision": "d51bf2435d030e0041344f576c5e8d7154828977", + }, + description="Dataset of 8364 restaurant reviews from qaym.com in Arabic for sentiment analysis", + reference="https://link.springer.com/chapter/10.1007/978-3-319-18117-2_2", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["ara-Arab"], + main_score="accuracy", + date=("2014-01-01", "2015-01-01"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="None specified", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=["ara-arab-EG", "ara-arab-JO", "ara-arab-SA"], + text_creation="found", + bibtex_citation=""" +@inproceedings{elsahar2015building, + title={Building large arabic multi-domain resources for sentiment analysis}, + author={ElSahar, Hady and El-Beltagy, Samhaa R}, + booktitle={International conference on intelligent text processing and computational linguistics}, + pages={23--34}, + year={2015}, + organization={Springer} +} +""", + n_samples={"train": N_SAMPLES}, + avg_character_length={"train": 231.4}, + ) + + def dataset_transform(self): + # labels: 0 negative, 1 positive + self.dataset = self.dataset.rename_column("polarity", "label") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/TweetEmotionClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/TweetEmotionClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..1a85e285d24e71b7f676790b21942fd06bdfce47 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ara/TweetEmotionClassification.py @@ -0,0 +1,50 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +N_SAMPLES = 2048 + + +class TweetEmotionClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="TweetEmotionClassification", + dataset={ + "path": "emotone_ar", + "revision": "0ded8ff72cc68cbb7bb5c01b0a9157982b73ddaf", + }, + description="A dataset of 10,000 tweets that was created with the aim of covering the most frequently used emotion categories in Arabic tweets.", + reference="https://link.springer.com/chapter/10.1007/978-3-319-77116-8_8", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["ara-Arab"], + main_score="accuracy", + date=("2014-01-01", "2016-08-31"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=["ara-arab-EG", "ara-arab-LB", "ara-arab-JO", "ara-arab-SA"], + text_creation="found", + bibtex_citation=""" +@inproceedings{al2018emotional, + title={Emotional tone detection in arabic tweets}, + author={Al-Khatib, Amr and El-Beltagy, Samhaa R}, + booktitle={Computational Linguistics and Intelligent Text Processing: 18th International Conference, CICLing 2017, Budapest, Hungary, April 17--23, 2017, Revised Selected Papers, Part II 18}, + pages={105--114}, + year={2018}, + organization={Springer} +} +""", + n_samples={"train": N_SAMPLES}, + avg_character_length={"train": 78.8}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("tweet", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ell/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ell/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/PoemSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/PoemSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..b9599ff95300657c5b324f4fa13d11e411d19ea8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/PoemSentimentClassification.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class PoemSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="PoemSentimentClassification", + description="Poem Sentiment is a sentiment dataset of poem verses from Project Gutenberg.", + reference="https://arxiv.org/abs/2011.02686", + dataset={ + "path": "google-research-datasets/poem_sentiment", + "revision": "329d529d875a00c47ec71954a1a96ae167584770", + }, + type="Classification", + category="s2s", + eval_splits=["validation", "test"], + eval_langs=["eng-Latn"], + main_score="accuracy", + date=("1700-01-01", "1900-01-01"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="CC-BY-4.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=["eng-Latn-US", "en-Latn-GB"], + text_creation="found", + bibtex_citation=""" +@misc{sheng2020investigating, + title={Investigating Societal Biases in a Poetry Composition System}, + author={Emily Sheng and David Uthus}, + year={2020}, + eprint={2011.02686}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +} +""", + n_samples={"validation": 105, "test": 104}, + avg_character_length={"validation": 45.3, "test": 42.4}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("verse_text", "text") diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/YahooAnswersTopicsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/YahooAnswersTopicsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..a6b4076c2814dbb3bb9e6f8766f774b42ddcfc9d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/YahooAnswersTopicsClassification.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + + +class YahooAnswersTopicsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="YahooAnswersTopicsClassification", + description="Dataset composed of questions and answers from Yahoo Answers, categorized into topics.", + reference="https://huggingface.co/datasets/yahoo_answers_topics", + dataset={ + "path": "yahoo_answers_topics", + "revision": "78fccffa043240c80e17a6b1da724f5a1057e8e5", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["eng-Latn"], + main_score="accuracy", + date=("2022-01-25", "2022-01-25"), + form=["written"], + domains=["Web"], + task_subtypes=["Topic classification"], + license="Not specified", + socioeconomic_status="low", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation="", + n_samples={"test": 60000}, + avg_character_length={"test": 346.35}, + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = dict(self.metadata) + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 32 + return metadata_dict + + def dataset_transform(self): + self.dataset = self.dataset.remove_columns( + ["id", "question_title", "question_content"] + ) + + self.dataset = self.dataset.rename_columns( + {"topic": "label", "best_answer": "text"} + ) + + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train", "test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/YelpReviewFullClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/YelpReviewFullClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..7727b81bb6e21a223fc6e1c2f850f9c1598dc16a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/YelpReviewFullClassification.py @@ -0,0 +1,58 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + + +class YelpReviewFullClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="YelpReviewFullClassification", + description="Yelp Review Full is a dataset for sentiment analysis, containing 5 classes corresponding to ratings 1-5.", + reference="https://arxiv.org/abs/1509.01626", + dataset={ + "path": "yelp_review_full", + "revision": "c1f9ee939b7d05667af864ee1cb066393154bf85", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["eng-Latn"], + main_score="accuracy", + date=("2015-01-01", "2015-12-31"), # reviews from 2015 + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="Other", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{NIPS2015_250cf8b5, + author = {Zhang, Xiang and Zhao, Junbo and LeCun, Yann}, + booktitle = {Advances in Neural Information Processing Systems}, + editor = {C. Cortes and N. Lawrence and D. Lee and M. Sugiyama and R. Garnett}, + pages = {}, + publisher = {Curran Associates, Inc.}, + title = {Character-level Convolutional Networks for Text Classification}, + url = {https://proceedings.neurips.cc/paper_files/paper/2015/file/250cf8b51c773f3f8dc8b4be867a9a02-Paper.pdf}, + volume = {28}, + year = {2015} + } + """, + n_samples={"test": 50000}, + avg_character_length={}, + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = dict(self.metadata) + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 128 + return metadata_dict + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/eng/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/est/estonian_valence.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/est/estonian_valence.py new file mode 100644 index 0000000000000000000000000000000000000000..f176c6d2246b9dbe194d6325a819c289bea80749 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/est/estonian_valence.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class EstonianValenceClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="EstonianValenceClassification", + dataset={ + "path": "kardosdrur/estonian-valence", + "revision": "9157397f05a127b3ac93b93dd88abf1bdf710c22", + }, + description="Dataset containing annotated Estonian news data from the Postimees and Õhtuleht newspapers.", + reference="https://figshare.com/articles/dataset/Estonian_Valence_Corpus_Eesti_valentsikorpus/24517054", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["est-Latn"], + main_score="accuracy", + date=( + "1857-01-01", # Inception of Postimees + "2023-11-08", # dataset publication + ), + form=["written"], + domains=["News"], + task_subtypes=["Sentiment/Hate speech"], + dialect=[], + license="CC BY 4.0", + socioeconomic_status="high", + annotations_creators="human-annotated", + text_creation="found", + bibtex_citation=""" +@article{Pajupuu2023, + author = "Hille Pajupuu and Jaan Pajupuu and Rene Altrov and Kairi Tamuri", + title = "{Estonian Valence Corpus / Eesti valentsikorpus}", + year = "2023", + month = "11", + url = "https://figshare.com/articles/dataset/Estonian_Valence_Corpus_Eesti_valentsikorpus/24517054", + doi = "10.6084/m9.figshare.24517054.v1" +}""", + n_samples={"train": 3270, "test": 818}, + avg_character_length={"train": 226.70642201834863, "test": 231.5085574572127}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("paragraph", "text").rename_column( + "valence", "label" + ) + # convert label to a numbers + labels = self.dataset["train"]["label"] # type: ignore + lab2idx = {lab: idx for idx, lab in enumerate(set(labels))} + self.dataset = self.dataset.map( + lambda x: {"label": lab2idx[x["label"]]}, remove_columns=["label"] + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = dict(self.metadata) + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 16 + return metadata_dict diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fas/PersianFoodSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fas/PersianFoodSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..9568575455fd4aaa98b1d652c3fd2a4e4b0d3ab9 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fas/PersianFoodSentimentClassification.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +TEST_SAMPLES = 2048 + + +class PersianFoodSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="PersianFoodSentimentClassification", + description="Persian Food Review Dataset", + reference="https://hooshvare.github.io/docs/datasets/sa", + dataset={ + "path": "asparius/Persian-Food-Sentiment", + "revision": "92ba517dfd22f6334111ad84154d16a2890f5b1d", + }, + type="Classification", + category="s2s", + eval_splits=["validation", "test"], + eval_langs=["fas-Arab"], + main_score="accuracy", + date=("2020-01-01", "2020-05-31"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @article{ParsBERT, + title={ParsBERT: Transformer-based Model for Persian Language Understanding}, + author={Mehrdad Farahani, Mohammad Gharachorloo, Marzieh Farahani, Mohammad Manthouri}, + journal={ArXiv}, + year={2020}, + volume={abs/2005.12515} + } + """, + n_samples={"validation": TEST_SAMPLES, "test": TEST_SAMPLES}, + avg_character_length={"validation": 90.37, "test": 90.58}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["validation", "test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fil/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fil/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fin/FinToxicityClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fin/FinToxicityClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..2d79bf5442ed87f23d672aff589937bff6379b6f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fin/FinToxicityClassification.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class FinToxicityClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="FinToxicityClassification", + description=""" + This dataset is a DeepL -based machine translated version of the Jigsaw toxicity dataset for Finnish. The dataset is originally from a Kaggle competition https://www.kaggle.com/c/jigsaw-toxic-comment-classification-challenge/data. + The original dataset poses a multi-label text classification problem and includes the labels identity_attack, insult, obscene, severe_toxicity, threat and toxicity. + Here adapted for toxicity classification, which is the most represented class. + """, + dataset={ + "path": "TurkuNLP/jigsaw_toxicity_pred_fi", + "revision": "6e7340e6be87124f319e25290778760c14df64d3", + }, + reference="https://aclanthology.org/2023.nodalida-1.68", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["fin-Latn"], + main_score="f1", + date=("2023-03-13", "2023-09-25"), + form=["written"], + domains=["News"], + task_subtypes=["Sentiment/Hate speech"], + license="ccy-by-sa-4.0", + socioeconomic_status="high", + annotations_creators="derived", + dialect=[], + text_creation="machine-translated", + bibtex_citation=""" + @inproceedings{eskelinen-etal-2023-toxicity, + title = "Toxicity Detection in {F}innish Using Machine Translation", + author = "Eskelinen, Anni and + Silvala, Laura and + Ginter, Filip and + Pyysalo, Sampo and + Laippala, Veronika", + booktitle = "Proceedings of the 24th Nordic Conference on Computational Linguistics (NoDaLiDa)", + month = may, + year = "2023", + }""", + n_samples={"train": 2048, "test": 2048}, + avg_character_length={"train": 432.63, "test": 401.03}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("label_toxicity", "label") + remove_cols = [ + col + for col in self.dataset["test"].column_names + if col not in ["text", "label"] + ] + self.dataset = self.dataset.remove_columns(remove_cols) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train", "test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fin/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/FrenchBookReviews.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/FrenchBookReviews.py new file mode 100644 index 0000000000000000000000000000000000000000..e434190c6898ee4645bcf3c618a4577e186b49b5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/FrenchBookReviews.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class FrenchBookReviews(AbsTaskClassification): + metadata = TaskMetadata( + name="FrenchBookReviews", + dataset={ + "path": "Abirate/french_book_reviews", + "revision": "534725e03fec6f560dbe8166e8ae3825314a6290", + }, + description="It is a French book reviews dataset containing a huge number of reader reviews on French books. Each review is pared with a rating that ranges from 0.5 to 5 (with 0.5 increment).", + reference="https://huggingface.co/datasets/Abirate/french_book_reviews", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["fra-Latn"], + main_score="accuracy", + date=("2022-01-01", "2023-01-01"), + form=["written"], + domains=["Reviews"], + task_subtypes=[], + license="CC0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + """, + n_samples={"train": 2048}, + avg_character_length={"train": 311.5}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"reader_review": "text"}) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/MovieReviewSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/MovieReviewSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..6c34233431c7a7f28cccdb652a14b53e1eb59ed8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/MovieReviewSentimentClassification.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +N_SAMPLES = 1024 + + +class MovieReviewSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="MovieReviewSentimentClassification", + dataset={ + "path": "tblard/allocine", + "revision": "a4654f4896408912913a62ace89614879a549287", + }, + description="The Allociné dataset is a French-language dataset for sentiment analysis that contains movie reviews produced by the online community of the Allociné.fr website.", + reference="https://github.com/TheophileBlard/french-sentiment-analysis-with-bert", + type="Classification", + category="s2s", + eval_splits=["validation", "test"], + eval_langs=["fra-Latn"], + main_score="accuracy", + date=("2006-01-01", "2020-01-01"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" +@software{blard2020, + title = {French sentiment analysis with BERT}, + author = {Théophile Blard}, + url = {https://github.com/TheophileBlard/french-sentiment-analysis-with-bert}, + year = {2020}, +} +""", + n_samples={"validation": N_SAMPLES, "test": N_SAMPLES}, + avg_character_length={"validation": 550.3, "test": 558.1}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("review", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["validation", "test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/fra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/guj/GujaratiNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/guj/GujaratiNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..c09a536884c958cd24f17b5740090bb3197e5e6b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/guj/GujaratiNewsClassification.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class GujaratiNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="GujaratiNewsClassification", + description="A Gujarati dataset for 3-class classification of Gujarati news articles", + reference="https://github.com/goru001/nlp-for-gujarati", + dataset={ + "path": "mlexplorer008/gujarati_news_classification", + "revision": "1a5f2fa2914bfeff4fcdc6fff4194fa8ec8fa19e", + }, + type="Classification", + category="s2s", + date=("2014-01-01", "2018-01-01"), + eval_splits=["test"], + eval_langs=["guj-Gujr"], + main_score="accuracy", + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="", # none found + n_samples={"train": 5269, "test": 1318}, + avg_character_length={"train": 61.95, "test": 61.91}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("headline", "text") diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/guj/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/guj/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/heb/HebrewSentimentAnalysis.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/heb/HebrewSentimentAnalysis.py new file mode 100644 index 0000000000000000000000000000000000000000..8dcaf647940c21cb0d0d573a70270a228e3b6a71 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/heb/HebrewSentimentAnalysis.py @@ -0,0 +1,49 @@ +from mteb.abstasks import AbsTaskClassification # type: ignore +from mteb.abstasks.TaskMetadata import TaskMetadata # type: ignore + + +class HebrewSentimentAnalysis(AbsTaskClassification): + metadata = TaskMetadata( + name="HebrewSentimentAnalysis", + dataset={ + "path": "hebrew_sentiment", + "revision": "952c9525954c1dac50d5f95945eb5585bb6464e7", + "name": "morph", + }, + description="HebrewSentiment is a data set consists of 12,804 user comments to posts on the official Facebook page of Israel’s president, Mr. Reuven Rivlin. In October 2015, we used the open software application Netvizz (Rieder, 2013) to scrape all the comments to all of the president’s posts in the period of June – August 2014, the first three months of Rivlin’s presidency.2 While the president’s posts aimed at reconciling tensions and called for tolerance and empathy, the sentiment expressed in the comments to the president’s posts was polarized between citizens who warmly thanked the president, and citizens that fiercely critiqued his policy.", + reference="https://huggingface.co/datasets/hebrew_sentiment", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["heb-Hebr"], + main_score="accuracy", + date=("2015-10-01", "2015-10-31"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="MIT License", + socioeconomic_status="low", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""" + @inproceedings{amram-etal-2018-representations, + title = "Representations and Architectures in Neural Sentiment Analysis for Morphologically Rich Languages: A Case Study from {M}odern {H}ebrew", + author = "Amram, Adam and Ben David, Anat and Tsarfaty, Reut", + booktitle = "Proceedings of the 27th International Conference on Computational Linguistics", + month = aug, + year = "2018", + address = "Santa Fe, New Mexico, USA", + publisher = "Association for Computational Linguistics", + url = "https://www.aclweb.org/anthology/C18-1190", + pages = "2242--2252" + } + """, + n_samples={"test": 2048}, + avg_character_length={"test": 113.57}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/heb/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/heb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/HindiDiscourseClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/HindiDiscourseClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..ebeede335cebb56f50812eed2acbf78dd906ee3e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/HindiDiscourseClassification.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from mteb.abstasks.AbsTaskClassification import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class HindiDiscourseClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="HindiDiscourseClassification", + dataset={ + "path": "midas/hindi_discourse", + "revision": "218ce687943a0da435d6d62751a4ab216be6cd40", + }, + description="A Hindi Discourse dataset in Hindi with values for coherence.", + reference="https://aclanthology.org/2020.lrec-1.149/", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["hin-Deva"], + main_score="accuracy", + date=("2019-12-01", "2020-04-09"), + form=["written"], + domains=["Fiction", "Social"], + dialect=[], + task_subtypes=["Discourse coherence"], + license="MIT", + socioeconomic_status="medium", + annotations_creators="expert-annotated", + text_creation="found", + bibtex_citation=""" + @inproceedings{dhanwal-etal-2020-annotated, + title = "An Annotated Dataset of Discourse Modes in {H}indi Stories", + author = "Dhanwal, Swapnil and + Dutta, Hritwik and + Nankani, Hitesh and + Shrivastava, Nilay and + Kumar, Yaman and + Li, Junyi Jessy and + Mahata, Debanjan and + Gosangi, Rakesh and + Zhang, Haimin and + Shah, Rajiv Ratn and + Stent, Amanda", + booktitle = "Proceedings of the 12th Language Resources and Evaluation Conference", + month = may, + year = "2020", + address = "Marseille, France", + publisher = "European Language Resources Association", + url = "https://www.aclweb.org/anthology/2020.lrec-1.149", + language = "English", + ISBN = "979-10-95546-34-4", +}""", + n_samples={"train": 2048}, + avg_character_length={"train": 79.23828125}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns( + {"Sentence": "text", "Discourse Mode": "label"} + ).remove_columns(["Story_no"]) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/SentimentAnalysisHindi.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/SentimentAnalysisHindi.py new file mode 100644 index 0000000000000000000000000000000000000000..6ee5376e090d3e62a31742b56507bb4ad461d08b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/SentimentAnalysisHindi.py @@ -0,0 +1,44 @@ +from __future__ import annotations + +from mteb.abstasks.AbsTaskClassification import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class SentimentAnalysisHindi(AbsTaskClassification): + metadata = TaskMetadata( + name="SentimentAnalysisHindi", + description="Hindi Sentiment Analysis Dataset", + reference="https://huggingface.co/datasets/OdiaGenAI/sentiment_analysis_hindi", + dataset={ + "path": "OdiaGenAI/sentiment_analysis_hindi", + "revision": "1beac1b941da76a9c51e3e5b39d230fde9a80983", + }, + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["hin-Deva"], + main_score="f1", + date=("2023-09-15", "2023-10-16"), + form=["written"], + dialect=[], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="CC BY-NC-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + text_creation="found", + bibtex_citation="""@misc{OdiaGenAI, + author = {Shantipriya Parida and Sambit Sekhar and Soumendra Kumar Sahoo and Swateek Jena and Abhijeet Parida and Satya Ranjan Dash and Guneet Singh Kohli}, + title = {OdiaGenAI: Generative AI and LLM Initiative for the Odia Language}, + year = {2023}, + publisher = {Hugging Face}, + journal = {Hugging Face repository}, + howpublished = {{https://huggingface.co/OdiaGenAI}}, } """, + n_samples={"train": 2497}, + avg_character_length={"train": 81.29}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hrv/FrenkHrClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hrv/FrenkHrClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..8867f14bc5b023387dcb3ca2fb1aefa0398dc2c3 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hrv/FrenkHrClassification.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class FrenkHrClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="FrenkHrClassification", + description="Croatian subset of the FRENK dataset", + dataset={ + "path": "classla/FRENK-hate-hr", + "revision": "e7fc9f3d8d6c5640a26679d8a50b1666b02cc41f", + }, + reference="https://arxiv.org/abs/1906.02045", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["hrv-Latn"], + main_score="accuracy", + date=("2021-05-28", "2021-05-28"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="""@misc{ljubešić2019frenk, + title={The FRENK Datasets of Socially Unacceptable Discourse in Slovene and English}, + author={Nikola Ljubešić and Darja Fišer and Tomaž Erjavec}, + year={2019}, + eprint={1906.02045}, + archivePrefix={arXiv}, + primaryClass={cs.CL}, + url={https://arxiv.org/abs/1906.02045} + }""", + n_samples={"test": 2120}, + avg_character_length={"test": 89.86}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hrv/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/hrv/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/IndonesianIdClickbaitClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/IndonesianIdClickbaitClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..7d89b7fa99f72ab938180db07643b68902aac2db --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/IndonesianIdClickbaitClassification.py @@ -0,0 +1,57 @@ +from __future__ import annotations + +from mteb.abstasks.AbsTaskClassification import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +N_SAMPLES = 2048 + + +class IndonesianIdClickbaitClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="IndonesianIdClickbaitClassification", + dataset={ + "path": "manandey/id_clickbait", + "revision": "9fa4d0824015fe537ae2c8166781f5c79873da2c", + }, + description="The CLICK-ID dataset is a collection of Indonesian news headlines that was collected from 12 local online news publishers.", + reference="http://www.sciencedirect.com/science/article/pii/S2352340920311252", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["ind-Latn"], + main_score="f1", + date=("2020-10-01", "2020-10-01"), + form=["written"], + domains=["News"], + dialect=[], + task_subtypes=["Claim verification"], + license="cc-by-4.0", + socioeconomic_status="medium", + annotations_creators="expert-annotated", + text_creation="found", + bibtex_citation=""" + @article{WILLIAM2020106231, +title = "CLICK-ID: A novel dataset for Indonesian clickbait headlines", +journal = "Data in Brief", +volume = "32", +pages = "106231", +year = "2020", +issn = "2352-3409", +doi = "https://doi.org/10.1016/j.dib.2020.106231", +url = "http://www.sciencedirect.com/science/article/pii/S2352340920311252", +author = "Andika William and Yunita Sari", +keywords = "Indonesian, Natural Language Processing, News articles, Clickbait, Text-classification", +abstract = "News analysis is a popular task in Natural Language Processing (NLP). In particular, the problem of clickbait in news analysis has gained attention in recent years [1, 2]. However, the majority of the tasks has been focused on English news, in which there is already a rich representative resource. For other languages, such as Indonesian, there is still a lack of resource for clickbait tasks. Therefore, we introduce the CLICK-ID dataset of Indonesian news headlines extracted from 12 Indonesian online news publishers. It is comprised of 15,000 annotated headlines with clickbait and non-clickbait labels. Using the CLICK-ID dataset, we then developed an Indonesian clickbait classification model achieving favourable performance. We believe that this corpus will be useful for replicable experiments in clickbait detection or other experiments in NLP areas." +} +""", + n_samples={"train": N_SAMPLES}, + avg_character_length={"train": 64.28}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.remove_columns(["label"]).rename_columns( + {"title": "text", "label_score": "label"} + ) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/IndonesianMongabayConservationClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/IndonesianMongabayConservationClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..745343f7e286a1160fdf8e026abc7238d7d39a71 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/IndonesianMongabayConservationClassification.py @@ -0,0 +1,105 @@ +from __future__ import annotations + +import ast + +import datasets +import numpy as np + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class IndonesianMongabayConservationClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="IndonesianMongabayConservationClassification", + description="Conservation dataset that was collected from mongabay.co.id contains topic-classification task (multi-label format) and sentiment classification. This task only covers sentiment analysis (positive, neutral negative)", + reference="https://aclanthology.org/2023.sealp-1.4/", + dataset={ + "path": "Datasaur/mongabay-experiment", + "revision": "c9e9f2c09836bfec57c543ab65983f3398e9657a", + }, + type="Classification", + category="s2s", + date=("2012-01-01", "2023-12-31"), + eval_splits=["validation", "test"], + eval_langs=["ind-Latn"], + main_score="f1", + form=["written"], + domains=["Web"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="medium", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{fransiska-etal-2023-utilizing, + title = "Utilizing Weak Supervision to Generate {I}ndonesian Conservation Datasets", + author = "Fransiska, Mega and + Pitaloka, Diah and + Saripudin, Saripudin and + Putra, Satrio and + Sutawika*, Lintang", + editor = "Wijaya, Derry and + Aji, Alham Fikri and + Vania, Clara and + Winata, Genta Indra and + Purwarianti, Ayu", + booktitle = "Proceedings of the First Workshop in South East Asian Language Processing", + month = nov, + year = "2023", + address = "Nusa Dua, Bali, Indonesia", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2023.sealp-1.4", + doi = "10.18653/v1/2023.sealp-1.4", + pages = "30--54", + } + """, + n_samples={"validation": 984, "test": 970}, + avg_character_length={"validation": 1675.8, "test": 1675.5}, + ) + + def dataset_transform(self): + splits = self.metadata_dict["eval_splits"] + class_labels = ["positif", "netral", "negatif"] + + ds = {} + + # Include training because the classification task requires it + train_split = self.dataset["train"] + train_docs: list = [] + train_labels: list = [] + for text, label in zip(train_split["text"], train_split["softlabel"]): + soft_label = ast.literal_eval(label) + if len(soft_label) == len(class_labels): + train_docs.append(text) + hard_label = np.argmax(soft_label) + train_labels.append(hard_label) + + ds["train"] = datasets.Dataset.from_dict( + { + "text": train_docs, + "label": train_labels, + } + ) + + documents: list = [] + labels: list = [] + # For evaluation + for split in splits: + ds_split = self.dataset[split] + for text, label in zip(ds_split["text"], ds_split["softlabel"]): + if label in class_labels: + documents.append(text) + labels.append(class_labels.index(label)) + + assert len(documents) == len(labels) + + ds[split] = datasets.Dataset.from_dict( + { + "text": documents, + "label": labels, + } + ) + + self.dataset = datasets.DatasetDict(ds) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ind/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/ItaCaseholdClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/ItaCaseholdClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..095472be4e4b0b73b5223be39b0782858642a429 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/ItaCaseholdClassification.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from mteb.abstasks.AbsTaskClassification import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class ItaCaseholdClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="ItaCaseholdClassification", + dataset={ + "path": "itacasehold/itacasehold", + "revision": "fafcfc4fee815f7017848e54b26c47ece8ff1626", + }, + description="An Italian Dataset consisting of 1101 pairs of judgments and their official holdings between the years 2019 and 2022 from the archives of Italian Administrative Justice categorized with 64 subjects.", + reference="https://doi.org/10.1145/3594536.3595177", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["ita-Latn"], + main_score="accuracy", + date=("2019-01-01", "2022-12-31"), + form=["written"], + domains=["Legal", "Government"], + dialect=[], + task_subtypes=[], + license="Apache 2.0", + socioeconomic_status="high", + annotations_creators="expert-annotated", + text_creation="found", + bibtex_citation=""" + @inproceedings{10.1145/3594536.3595177, + author = {Licari, Daniele and Bushipaka, Praveen and Marino, Gabriele and Comand\'{e}, Giovanni and Cucinotta, Tommaso}, + title = {Legal Holding Extraction from Italian Case Documents using Italian-LEGAL-BERT Text Summarization}, + year = {2023}, + isbn = {9798400701979}, + publisher = {Association for Computing Machinery}, + address = {New York, NY, USA}, + url = {https://doi.org/10.1145/3594536.3595177}, + doi = {10.1145/3594536.3595177}, + abstract = {Legal holdings are used in Italy as a critical component of the legal system, serving to establish legal precedents, provide guidance for future legal decisions, and ensure consistency and predictability in the interpretation and application of the law. They are written by domain experts who describe in a clear and concise manner the principle of law applied in the judgments.We introduce a legal holding extraction method based on Italian-LEGAL-BERT to automatically extract legal holdings from Italian cases. In addition, we present ITA-CaseHold, a benchmark dataset for Italian legal summarization. We conducted several experiments using this dataset, as a valuable baseline for future research on this topic.}, + booktitle = {Proceedings of the Nineteenth International Conference on Artificial Intelligence and Law}, + pages = {148–156}, + numpages = {9}, + keywords = {Italian-LEGAL-BERT, Holding Extraction, Extractive Text Summarization, Benchmark Dataset}, + location = {, Braga, Portugal, }, + series = {ICAIL '23} + } + """, + n_samples={"test": 221}, + avg_character_length={"test": 4207.9}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns( + {"summary": "text", "materia": "label"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/ItalianLinguistAcceptabilityClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/ItalianLinguistAcceptabilityClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..281494e6dedbc345babf96f7b185e0de77378c05 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/ItalianLinguistAcceptabilityClassification.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from mteb.abstasks.AbsTaskClassification import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class ItalianLinguisticAcceptabilityClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="Itacola", + dataset={ + "path": "gsarti/itacola", + "revision": "f8f98e5c4d3059cf1a00c8eb3d70aa271423f636", + }, + description="An Italian Corpus of Linguistic Acceptability taken from linguistic literature with a binary annotation made by the original authors themselves.", + reference="https://aclanthology.org/2021.findings-emnlp.250/", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["ita-Latn"], + main_score="accuracy", + date=("2021-01-01", "2021-12-31"), + form=["written"], + domains=["Non-fiction", "Spoken"], + dialect=[], + task_subtypes=["Linguistic acceptability"], + license="unknown", + socioeconomic_status="high", + annotations_creators="expert-annotated", + text_creation="found", + bibtex_citation=""" + @inproceedings{trotta-etal-2021-monolingual-cross, + title = "Monolingual and Cross-Lingual Acceptability Judgments with the {I}talian {C}o{LA} corpus", + author = "Trotta, Daniela and + Guarasci, Raffaele and + Leonardelli, Elisa and + Tonelli, Sara", + booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2021", + month = nov, + year = "2021", + address = "Punta Cana, Dominican Republic", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2021.findings-emnlp.250", + doi = "10.18653/v1/2021.findings-emnlp.250", + pages = "2929--2940" +} + """, + n_samples={"train": 7801, "test": 975}, + avg_character_length={"train": 35.95, "test": 36.67}, + ) + + def dataset_transform(self): + self.dataset = ( + self.dataset.rename_columns({"acceptability": "label"}) + .rename_columns({"sentence": "text"}) + .remove_columns(["unique_id", "source"]) + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ita/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jav/JavaneseIMDBClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jav/JavaneseIMDBClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..9233381176da4422cc14be52f7af82042fd5273f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jav/JavaneseIMDBClassification.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class JavaneseIMDBClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="JavaneseIMDBClassification", + description="Large Movie Review Dataset translated to Javanese. This is a dataset for binary sentiment classification containing substantially more data than previous benchmark datasets.", + reference="https://github.com/w11wo/nlp-datasets#javanese-imdb", + dataset={ + "path": "w11wo/imdb-javanese", + "revision": "11bef3dfce0ce107eb5e276373dcd28759ce85ee", + }, + type="Classification", + category="s2s", + date=("2021-06-24", "2021-06-24"), + eval_splits=["test"], + eval_langs=["jav-Latn"], + main_score="accuracy", + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{wongso2021causal, + title={Causal and Masked Language Modeling of Javanese Language using Transformer-based Architectures}, + author={Wongso, Wilson and Setiawan, David Samuel and Suhartono, Derwin}, + booktitle={2021 International Conference on Advanced Computer Science and Information Systems (ICACSIS)}, + pages={1--7}, + year={2021}, + organization={IEEE} + } + """, + n_samples={"test": 25_000}, + avg_character_length={"test": 481.83}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jav/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jav/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jpn/WRIMEClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jpn/WRIMEClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..9d93de88c23a626c5152450b3d968023b4792c4b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/jpn/WRIMEClassification.py @@ -0,0 +1,70 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class WRIMEClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="WRIMEClassification", + dataset={ + "path": "shunk031/wrime", + "revision": "3fb7212c389d7818b8e6179e2cdac762f2e081d9", + "name": "ver2", + }, + description="A dataset of Japanese social network rated for sentiment", + reference="https://aclanthology.org/2021.naacl-main.169/", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["jpn-Jpan"], + main_score="accuracy", + date=("2011-06-01", "2020-05-31"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="The dataset is available for research purposes only. Redistribution of the dataset is prohibited.", + socioeconomic_status="high", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""@inproceedings{kajiwara-etal-2021-wrime, + title = "{WRIME}: A New Dataset for Emotional Intensity Estimation with Subjective and Objective Annotations", + author = "Kajiwara, Tomoyuki and + Chu, Chenhui and + Takemura, Noriko and + Nakashima, Yuta and + Nagahara, Hajime", + editor = "Toutanova, Kristina and + Rumshisky, Anna and + Zettlemoyer, Luke and + Hakkani-Tur, Dilek and + Beltagy, Iz and + Bethard, Steven and + Cotterell, Ryan and + Chakraborty, Tanmoy and + Zhou, Yichao", + booktitle = "Proceedings of the 2021 Conference of the North American Chapter of the Association for Computational Linguistics: Human Language Technologies", + month = jun, + year = "2021", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2021.naacl-main.169", + doi = "10.18653/v1/2021.naacl-main.169", + pages = "2095--2104", + abstract = "We annotate 17,000 SNS posts with both the writer{'}s subjective emotional intensity and the reader{'}s objective one to construct a Japanese emotion analysis dataset. In this study, we explore the difference between the emotional intensity of the writer and that of the readers with this dataset. We found that the reader cannot fully detect the emotions of the writer, especially anger and trust. In addition, experimental results in estimating the emotional intensity show that it is more difficult to estimate the writer{'}s subjective labels than the readers{'}. The large gap between the subjective and objective emotions imply the complexity of the mapping from a post to the subjective emotion intensities, which also leads to a lower performance with machine learning models.", +}""", + n_samples={"test": 2048}, + avg_character_length={"test": 47.78}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.flatten().select_columns( + ["sentence", "avg_readers.sentiment"] + ) + self.dataset = self.dataset.rename_columns( + {"sentence": "text", "avg_readers.sentiment": "label"} + ) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kan/KannadaNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kan/KannadaNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..3fa59d3ad4c8e8eb057ddf013216a0f3a281c67b --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kan/KannadaNewsClassification.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + + +class KannadaNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="KannadaNewsClassification", + description="The Kannada news dataset contains only the headlines of news article in three categories: Entertainment, Tech, and Sports. The data set contains around 6300 news article headlines which are collected from Kannada news websites. The data set has been cleaned and contains train and test set using which can be used to benchmark topic classification models in Kannada.", + dataset={ + "path": "Akash190104/kannada_news_classification", + "revision": "a470711069906ac0a559defec3b89cb3725601bd", + }, + reference="https://github.com/goru001/nlp-for-kannada", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["kan-Knda"], + main_score="accuracy", + date=("2019-03-17", "2020-08-06"), + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="CC-BY-SA-4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="", + n_samples={"train": 6460}, + avg_character_length={"train": 65.88}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("headline", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kan/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kan/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kat/GeorgianSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kat/GeorgianSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..dba86699d48eedd92da915e2cee57099556e30b2 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kat/GeorgianSentimentClassification.py @@ -0,0 +1,61 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class GeorgianSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="GeorgianSentimentClassification", + description="Goergian Sentiment Dataset", + reference="https://aclanthology.org/2022.lrec-1.173", + dataset={ + "path": "asparius/Georgian-Sentiment", + "revision": "d4fb68dff38e89c42406080737b8431ea48fa866", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["kat-Geor"], + main_score="accuracy", + date=("2022-01-01", "2022-06-25"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="CC BY 4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{stefanovitch-etal-2022-resources, + title = "Resources and Experiments on Sentiment Classification for {G}eorgian", + author = "Stefanovitch, Nicolas and + Piskorski, Jakub and + Kharazi, Sopho", + editor = "Calzolari, Nicoletta and + B{\'e}chet, Fr{\'e}d{\'e}ric and + Blache, Philippe and + Choukri, Khalid and + Cieri, Christopher and + Declerck, Thierry and + Goggi, Sara and + Isahara, Hitoshi and + Maegaard, Bente and + Mariani, Joseph and + Mazo, H{\'e}l{\`e}ne and + Odijk, Jan and + Piperidis, Stelios", + booktitle = "Proceedings of the Thirteenth Language Resources and Evaluation Conference", + month = jun, + year = "2022", + address = "Marseille, France", + publisher = "European Language Resources Association", + url = "https://aclanthology.org/2022.lrec-1.173", + pages = "1613--1621", + abstract = "This paper presents, to the best of our knowledge, the first ever publicly available annotated dataset for sentiment classification and semantic polarity dictionary for Georgian. The characteristics of these resources and the process of their creation are described in detail. The results of various experiments on the performance of both lexicon- and machine learning-based models for Georgian sentiment classification are also reported. Both 3-label (positive, neutral, negative) and 4-label settings (same labels + mixed) are considered. The machine learning models explored include, i.a., logistic regression, SVMs, and transformed-based models. We also explore transfer learning- and translation-based (to a well-supported language) approaches. The obtained results for Georgian are on par with the state-of-the-art results in sentiment classification for well studied languages when using training data of comparable size.", +} + """, + n_samples={"train": 330, "test": 1200}, + avg_character_length={"train": 114.26, "test": 118.06}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kat/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KlueTC.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KlueTC.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4eb4eecb9fc5cde3a57a0aa12736af4e3b369f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KlueTC.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class KlueTC(AbsTaskClassification): + metadata = TaskMetadata( + name="KLUE-TC", + dataset={ + "path": "klue", + "name": "ynat", + "revision": "349481ec73fff722f88e0453ca05c77a447d967c", + }, + description="Topic classification dataset of human-annotated news headlines. Part of the Korean Language Understanding Evaluation (KLUE).", + reference="https://arxiv.org/abs/2105.09680", + type="Classification", + category="s2s", + eval_splits=["validation"], + eval_langs=["kor-Hang"], + main_score="accuracy", + date=("2016-01-01", "2020-12-31"), # from 2016 to 2020 + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="CC-BY-SA-4.0", + socioeconomic_status="high", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""@misc{park2021klue, + title={KLUE: Korean Language Understanding Evaluation}, + author={Sungjoon Park and Jihyung Moon and Sungdong Kim and Won Ik Cho and Jiyoon Han and Jangwon Park and Chisung Song and Junseong Kim and Yongsook Song and Taehwan Oh and Joohong Lee and Juhyun Oh and Sungwon Lyu and Younghoon Jeong and Inkwon Lee and Sangwoo Seo and Dongjun Lee and Hyunwoo Kim and Myeonghwa Lee and Seongbo Jang and Seungwon Do and Sunkyoung Kim and Kyungtae Lim and Jongwon Lee and Kyumin Park and Jamin Shin and Seonghyun Kim and Lucy Park and Alice Oh and Jungwoo Ha and Kyunghyun Cho}, + year={2021}, + eprint={2105.09680}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +}""", + n_samples={"validation": 2048}, + avg_character_length={"validation": 27.079609091907326}, + ) + + def dataset_transform(self): + def id2str(example): + return {"label": label_feature.int2str(example["label_id"])} + + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["validation"] + ) + + label_feature = self.dataset[self.metadata.eval_splits[0]].features["label"] + + self.dataset = self.dataset.rename_columns( + {"title": "text", "label": "label_id"} + ) + self.dataset = self.dataset.map(id2str) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorFin.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorFin.py new file mode 100644 index 0000000000000000000000000000000000000000..5938da788da50c44cd8e99e39270bf4e5a695515 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorFin.py @@ -0,0 +1,49 @@ +from mteb.abstasks import AbsTaskClassification # type: ignore +from mteb.abstasks.TaskMetadata import TaskMetadata # type: ignore + + +class KorFin(AbsTaskClassification): + metadata = TaskMetadata( + name="KorFin", + dataset={ + "path": "amphora/korfin-asc", + "revision": "07cc4a29341ef26e8614ae1139847f4d4888727d", + }, + description="The KorFin-ASC is an extension of KorFin-ABSA, which is a financial sentiment analysis dataset including 8818 samples with (aspect, polarity) pairs annotated. The samples were collected from KLUE-TC and analyst reports from Naver Finance.", + reference="https://huggingface.co/datasets/amphora/korfin-asc", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["kor-Hang"], + main_score="accuracy", + date=( + "2022-01-01", + "2022-12-31", + ), # Assumed date based on the citations in the paper + form=["written"], + domains=["News"], + task_subtypes=["Sentiment/Hate speech"], + license="CC BY-SA 4.0", + socioeconomic_status="high", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""" + @article{son2023removing, + title={Removing Non-Stationary Knowledge From Pre-Trained Language Models for Entity-Level Sentiment Classification in Finance}, + author={Son, Guijin and Lee, Hanwool and Kang, Nahyeon and Hahm, Moonjeong}, + journal={arXiv preprint arXiv:2301.03136}, + year={2023} + } + """, + n_samples={"test": 2048}, + avg_character_length={"test": 75.28}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns( + {"SRC": "text", "SENTIMENT": "label"} + ).remove_columns(["SID", "TYPE", "ASPECT"]) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorHateClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorHateClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..f74e079626b6934b2308f823ab7d8570d1fbc82a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorHateClassification.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class KorHateClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="KorHateClassification", + description="""The dataset was created to provide the first human-labeled Korean corpus for + toxic speech detection from a Korean online entertainment news aggregator. Recently, + two young Korean celebrities suffered from a series of tragic incidents that led to two + major Korean web portals to close the comments section on their platform. However, this only + serves as a temporary solution, and the fundamental issue has not been solved yet. This dataset + hopes to improve Korean hate speech detection. Annotation was performed by 32 annotators, + consisting of 29 annotators from the crowdsourcing platform DeepNatural AI and three NLP researchers. + """, + dataset={ + "path": "inmoonlight/kor_hate", + "revision": "bd1a7370caf712125fac1fda375834ca8ddefaca", + }, + reference="https://paperswithcode.com/dataset/korean-hatespeech-dataset", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["kor-Hang"], + main_score="accuracy", + date=("2018-01-01", "2020-01-01"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="cc-by-sa-4.0", + socioeconomic_status="high", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @misc{moon2020beep, + title={BEEP! Korean Corpus of Online News Comments for Toxic Speech Detection}, + author={Jihyung Moon and Won Ik Cho and Junbum Lee}, + year={2020}, + eprint={2005.12503}, + archivePrefix={arXiv}, + primaryClass={cs.CL} + }""", + n_samples={"train": 2048, "test": 471}, + avg_character_length={"train": 38.57, "test": 38.86}, + ) + + def dataset_transform(self): + keep_cols = ["comments", "hate"] + rename_dict = dict(zip(keep_cols, ["text", "label"])) + remove_cols = [ + col for col in self.dataset["test"].column_names if col not in keep_cols + ] + self.dataset = self.dataset.rename_columns(rename_dict) + self.dataset = self.dataset.remove_columns(remove_cols) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorSarcasmClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorSarcasmClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4349bf8fb72e6a6ec3f602478c3e97293c2c5d --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/KorSarcasmClassification.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class KorSarcasmClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="KorSarcasmClassification", + description=""" + The Korean Sarcasm Dataset was created to detect sarcasm in text, which can significantly alter the original + meaning of a sentence. 9319 tweets were collected from Twitter and labeled for sarcasm or not_sarcasm. These + tweets were gathered by querying for: irony sarcastic, and + sarcasm. + The dataset was created by gathering HTML data from Twitter. Queries for hashtags that include sarcasm + and variants of it were used to return tweets. It was preprocessed by removing the keyword + hashtag, urls and mentions of the user to preserve anonymity. + """, + dataset={ + "path": "kor_sarcasm", + "revision": "8079d24b9f1278c6fbc992921c1271457a1064ff", + }, + reference="https://github.com/SpellOnYou/korean-sarcasm", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["kor-Hang"], + main_score="accuracy", + date=("2018-10-31", "2019-09-28"), # estimated based on git history + form=["written"], + domains=["Social"], + task_subtypes=["Topic classification"], + license="MIT", + socioeconomic_status="high", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @misc{kim2019kocasm, + author = {Kim, Jiwon and Cho, Won Ik}, + title = {Kocasm: Korean Automatic Sarcasm Detection}, + year = {2019}, + publisher = {GitHub}, + journal = {GitHub repository}, + howpublished = {https://github.com/SpellOnYou/korean-sarcasm} + } + """, + n_samples={"train": 2048, "test": 301}, + avg_character_length={"train": 48.45, "test": 46.77}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"tokens": "text"}) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kur/KurdishSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kur/KurdishSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..13110a881d189539228ad58a823224dcaecd2c2a --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kur/KurdishSentimentClassification.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class KurdishSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="KurdishSentimentClassification", + description="Kurdish Sentiment Dataset", + reference="https://link.springer.com/article/10.1007/s10579-023-09716-6", + dataset={ + "path": "asparius/Kurdish-Sentiment", + "revision": "f334d90a9f68cc3af78cc2a2ece6a3b69408124c", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["kur-Arab"], + main_score="accuracy", + date=("2023-01-01", "2024-01-02"), + form=["written"], + domains=["Web"], + task_subtypes=["Sentiment/Hate speech"], + license="CC BY 4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=["Sorani"], + text_creation="found", + bibtex_citation=""" + @article{article, + author = {Badawi, Soran and Kazemi, Arefeh and Rezaie, Vali}, + year = {2024}, + month = {01}, + pages = {1-20}, + title = {KurdiSent: a corpus for kurdish sentiment analysis}, + journal = {Language Resources and Evaluation}, + doi = {10.1007/s10579-023-09716-6} + } + """, + n_samples={"train": 6000, "test": 1987}, + avg_character_length={"train": 59.38, "test": 56.11}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kur/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/kur/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mal/MalayalamNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mal/MalayalamNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..d0750ca683ad70ee119a643acd2c1a40330af900 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mal/MalayalamNewsClassification.py @@ -0,0 +1,36 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class MalayalamNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="MalayalamNewsClassification", + description="A Malayalam dataset for 3-class classification of Malayalam news articles", + reference="https://github.com/goru001/nlp-for-malyalam", + dataset={ + "path": "mlexplorer008/malayalam_news_classification", + "revision": "666f63bba2387456d8f846ea4d0565181bd47b81", + }, + type="Classification", + category="s2s", + date=("2014-01-01", "2018-01-01"), + eval_splits=["test"], + eval_langs=["mal-Mlym"], + main_score="accuracy", + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=None, + n_samples={"train": 5036, "test": 1260}, + avg_character_length={"train": 79.48, "test": 80.44}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"headings": "text"}) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mal/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mal/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mar/MarathiNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mar/MarathiNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c01b01abdee8305a04b0eee116a82de3b8a8b7 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mar/MarathiNewsClassification.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class MarathiNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="MarathiNewsClassification", + description="A Marathi dataset for 3-class classification of Marathi news articles", + reference="https://github.com/goru001/nlp-for-marathi", + dataset={ + "path": "mlexplorer008/marathi_news_classification", + "revision": "7640cf8132cca1f99995ac71512a670e3c965cf1", + }, + type="Classification", + category="s2s", + date=("2014-01-01", "2018-01-01"), + eval_splits=["test"], + eval_langs=["mar-Deva"], + main_score="f1", + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="""""", + n_samples={"test": 2048}, + avg_character_length={"test": 52.37}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"headline": "text"}) + self.dataset = self.stratified_subsampling(self.dataset, seed=self.seed) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mar/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mar/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mkd/MacedonianTweetSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mkd/MacedonianTweetSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..ec9e749bd43e4331a1a84b8300b27f80543b23a1 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mkd/MacedonianTweetSentimentClassification.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class MacedonianTweetSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="MacedonianTweetSentimentClassification", + description="An Macedonian dataset for tweet sentiment classification.", + reference="https://aclanthology.org/R15-1034/", + dataset={ + "path": "isaacchung/macedonian-tweet-sentiment-classification", + "revision": "957e075ba35e4417ba7837987fd7053a6533a1a2", + }, + type="Classification", + category="s2s", + date=["2014-11-01", "2015-04-01"], + eval_splits=["test"], + eval_langs=["mkd-Cyrl"], + main_score="accuracy", + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="CC BY-NC-SA 3.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""@inproceedings{jovanoski-etal-2015-sentiment, + title = "Sentiment Analysis in {T}witter for {M}acedonian", + author = "Jovanoski, Dame and + Pachovski, Veno and + Nakov, Preslav", + editor = "Mitkov, Ruslan and + Angelova, Galia and + Bontcheva, Kalina", + booktitle = "Proceedings of the International Conference Recent Advances in Natural Language Processing", + month = sep, + year = "2015", + address = "Hissar, Bulgaria", + publisher = "INCOMA Ltd. Shoumen, BULGARIA", + url = "https://aclanthology.org/R15-1034", + pages = "249--257", +}""", + n_samples={"test": 1139}, + avg_character_length={"test": 67.6}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mkd/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mkd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AfriSentiClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AfriSentiClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4a4511de9b2177e7f0d4784a44fd2e7f51545e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AfriSentiClassification.py @@ -0,0 +1,73 @@ +from __future__ import annotations + +import datasets + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + + +def _transform(dataset, lang): + dataset = dataset.rename_columns({"tweet": "text"}) + sample_size = min(2048, len(dataset["test"])) + dataset["test"] = dataset["test"].select(range(sample_size)) + return dataset + + +class AfriSentiClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="AfriSentiClassification", + description="AfriSenti is the largest sentiment analysis dataset for under-represented African languages.", + dataset={ + "path": "shmuhammad/AfriSenti-twitter-sentiment", + "revision": "b52e930385cf5ed7f063072c3f7bd17b599a16cf", + }, + reference="https://arxiv.org/abs/2302.08956", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs={ + "amh": ["amh-Ethi"], # Amharic (Ethiopic script) + "arq": ["arq-Arab"], + "ary": ["ary-Arab"], # Moroccan Arabic, Standard Arabic (Arabic script) + "hau": [ + "hau-Latn" + ], # Hausa (Latin script), additional script if written in Ajami (Arabic script) + "ibo": ["ibo-Latn"], # Igbo (Latin script) + "kin": ["kin-Latn"], # Kinyarwanda (Latin script) + "por": ["por-Latn"], # Portuguese (Latin script) + "pcm": ["pcm-Latn"], # Nigerian Pidgin (Latin script) + "swa": ["swa-Latn"], # Swahili (macrolanguage) (Latin script) + "twi": ["twi-Latn"], # Twi (Latin script) + "tso": ["tso-Latn"], # Tsonga (Latin script) + "yor": ["yor-Latn"], # Yoruba (Latin script) + }, + main_score="accuracy", + date=("2023-02-16", "2023-09-03"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="Creative Commons Attribution 4.0 International License", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="""@inproceedings{Muhammad2023AfriSentiAT, + title=AfriSenti: A Twitter Sentiment Analysis Benchmark for African Languages, + author=Shamsuddeen Hassan Muhammad and Idris Abdulmumin and Abinew Ali Ayele and Nedjma Ousidhoum and David Ifeoluwa Adelani and Seid Muhie Yimam and Ibrahim Sa'id Ahmad and Meriem Beloucif and Saif Mohammad and Sebastian Ruder and Oumaima Hourrane and Pavel Brazdil and Felermino D'ario M'ario Ant'onio Ali and Davis Davis and Salomey Osei and Bello Shehu Bello and Falalu Ibrahim and Tajuddeen Gwadabe and Samuel Rutunda and Tadesse Belay and Wendimu Baye Messelle and Hailu Beshada Balcha and Sisay Adugna Chala and Hagos Tesfahun Gebremichael and Bernard Opoku and Steven Arthur, + year=2023 + }""", + n_samples={"test": 2048}, + avg_character_length={"test": 74.77}, + ) + + def load_data(self, **kwargs): + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = {} + for lang in self.langs: + metadata = self.metadata_dict.get("dataset", None) + dataset = datasets.load_dataset(name=lang, **metadata) + self.dataset[lang] = _transform(dataset, lang) + self.dataset_transform() + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AfriSentiLangClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AfriSentiLangClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..fd61efbb1def4518de154410d438281252810a8e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AfriSentiLangClassification.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class AfriSentiLangClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="AfriSentiLangClassification", + description="AfriSentiLID is the largest LID classification dataset for African Languages.", + dataset={ + "path": "HausaNLP/afrisenti-lid-data", + "revision": "f17cb5f3ec522ac604601fd09db9fd644ac66ca5", + }, + reference="https://huggingface.co/datasets/HausaNLP/afrisenti-lid-data/", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=[ + "amh-Ethi", # Amharic (Ethiopic script) + "arq-Arab", + "ary-Arab", # Moroccan Arabic, Standard Arabic (Arabic script) + "hau-Latn", # Hausa (Latin script), additional script if written in Ajami (Arabic script) + "ibo-Latn", # Igbo (Latin script) + "kin-Latn", # Kinyarwanda (Latin script) + "por-Latn", # Portuguese (Latin script) + "pcm-Latn", # Nigerian Pidgin (Latin script) + "swa-Latn", # Swahili (macrolanguage) (Latin script) + "twi-Latn", # Twi (Latin script) + "tso-Latn", # Tsonga (Latin script) + "yor-Latn", # Yoruba (Latin script) + ], + main_score="accuracy", + date=("2023-07-04", "2023-08-04"), + form=["written"], + domains=["Social"], + task_subtypes=["Language identification"], + license="cc-by-nc-sa-4.0", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + """, + n_samples={"test": 5754}, + avg_character_length={"test": 77.84}, + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = super().metadata_dict + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 32 + return metadata_dict + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("tweet", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AmazonCounterfactualClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AmazonCounterfactualClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..ccfdbedb27cd539a2e7ed9a444a1c0ef057349df --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AmazonCounterfactualClassification.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + + +class AmazonCounterfactualClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="AmazonCounterfactualClassification", + dataset={ + "path": "mteb/amazon_counterfactual", + "revision": "e8379541af4e31359cca9fbcf4b00f2671dba205", + }, + description=( + "A collection of Amazon customer reviews annotated for counterfactual detection pair classification." + ), + reference="https://arxiv.org/abs/2104.06893", + category="s2s", + type="Classification", + eval_splits=["validation", "test"], + eval_langs={ + "en-ext": ["eng-Latn"], + "en": ["eng-Latn"], + "de": ["deu-Latn"], + "ja": ["jpn-Jpan"], + }, + main_score="accuracy", + date=( + "2018-01-01", + "2021-12-31", + ), # Estimated range for the collection of Amazon reviews + form=["written"], + domains=["Reviews"], + task_subtypes=["Counterfactual Detection"], + license="CC BY 4.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""@inproceedings{oneill-etal-2021-wish, + title = "{I} Wish {I} Would Have Loved This One, But {I} Didn{'}t {--} A Multilingual Dataset for Counterfactual Detection in Product Review", + author = "O{'}Neill, James and + Rozenshtein, Polina and + Kiryo, Ryuichi and + Kubota, Motoko and + Bollegala, Danushka", + editor = "Moens, Marie-Francine and + Huang, Xuanjing and + Specia, Lucia and + Yih, Scott Wen-tau", + booktitle = "Proceedings of the 2021 Conference on Empirical Methods in Natural Language Processing", + month = nov, + year = "2021", + address = "Online and Punta Cana, Dominican Republic", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2021.emnlp-main.568", + doi = "10.18653/v1/2021.emnlp-main.568", + pages = "7092--7108", + abstract = "Counterfactual statements describe events that did not or cannot take place. We consider the problem of counterfactual detection (CFD) in product reviews. For this purpose, we annotate a multilingual CFD dataset from Amazon product reviews covering counterfactual statements written in English, German, and Japanese languages. The dataset is unique as it contains counterfactuals in multiple languages, covers a new application area of e-commerce reviews, and provides high quality professional annotations. We train CFD models using different text representation methods and classifiers. We find that these models are robust against the selectional biases introduced due to cue phrase-based sentence selection. Moreover, our CFD dataset is compatible with prior datasets and can be merged to learn accurate CFD models. Applying machine translation on English counterfactual examples to create multilingual data performs poorly, demonstrating the language-specificity of this problem, which has been ignored so far.", +}""", + n_samples={"validation": 335, "test": 670}, + avg_character_length={"validation": 109.2, "test": 106.1}, + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = super().metadata_dict + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 32 + return metadata_dict diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AmazonReviewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AmazonReviewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..56494bea8572d43db7509a1da18bfb45e097e401 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/AmazonReviewsClassification.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + + +class AmazonReviewsClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="AmazonReviewsClassification", + dataset={ + "path": "mteb/amazon_reviews_multi", + "revision": "1399c76144fd37290681b995c656ef9b2e06e26d", + }, + description="A collection of Amazon reviews specifically designed to aid research in multilingual text classification.", + reference="https://arxiv.org/abs/2010.02573", + category="s2s", + type="Classification", + eval_splits=["validation", "test"], + eval_langs={ + "en": ["eng-Latn"], + "de": ["deu-Latn"], + "es": ["spa-Latn"], + "fr": ["fra-Latn"], + "ja": ["jpn-Jpan"], + "zh": ["cmn-Hans"], + }, + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"validation": 30000, "test": 30000}, + avg_character_length={"validation": 159.2, "test": 160.4}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/CataloniaTweetClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/CataloniaTweetClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..76e2ad7da4de65cfd1e969312cc1d47de7cd1c04 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/CataloniaTweetClassification.py @@ -0,0 +1,82 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + +_LANGS = { + "spanish": ["spa-Latn"], + "catalan": ["cat-Latn"], +} + + +class CataloniaTweetClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="CataloniaTweetClassification", + description="""This dataset contains two corpora in Spanish and Catalan that consist of annotated Twitter + messages for automatic stance detection. The data was collected over 12 days during February and March + of 2019 from tweets posted in Barcelona, and during September of 2018 from tweets posted in the town of Terrassa, Catalonia. + Each corpus is annotated with three classes: AGAINST, FAVOR and NEUTRAL, which express the stance + towards the target - independence of Catalonia. + """, + reference="https://aclanthology.org/2020.lrec-1.171/", + dataset={ + "path": "catalonia_independence", + "revision": "cf24d44e517efa534f048e5fc5981f399ed25bee", + }, + type="Classification", + category="s2s", + eval_splits=["validation", "test"], + eval_langs=_LANGS, + main_score="accuracy", + date=("2018-09-01", "2029-03-30"), + form=["written"], + domains=["Social", "Government"], + task_subtypes=["Political classification"], + license="cc-by-sa-4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="created", + bibtex_citation="""@inproceedings{zotova-etal-2020-multilingual, + title = "Multilingual Stance Detection in Tweets: The {C}atalonia Independence Corpus", + author = "Zotova, Elena and + Agerri, Rodrigo and + Nu{\~n}ez, Manuel and + Rigau, German", + editor = "Calzolari, Nicoletta and + B{\'e}chet, Fr{\'e}d{\'e}ric and + Blache, Philippe and + Choukri, Khalid and + Cieri, Christopher and + Declerck, Thierry and + Goggi, Sara and + Isahara, Hitoshi and + Maegaard, Bente and + Mariani, Joseph and + Mazo, H{\'e}l{\`e}ne and + Moreno, Asuncion and + Odijk, Jan and + Piperidis, Stelios", + booktitle = "Proceedings of the Twelfth Language Resources and Evaluation Conference", + month = may, + year = "2020", + publisher = "European Language Resources Association", + pages = "1368--1375", + ISBN = "979-10-95546-34-4", + }""", + n_samples={"validation": 2000, "test": 2000}, + avg_character_length={"validation": 202.61, "test": 200.49}, + ) + + def dataset_transform(self): + for lang in self.dataset.keys(): + self.dataset[lang] = self.dataset[lang].rename_columns( + {"TWEET": "text", "LABEL": "label"} + ) + self.dataset[lang] = self.stratified_subsampling( + self.dataset[lang], + seed=self.seed, + splits=["validation", "test"], + n_samples=2000, + ) + self.dataset[lang] = self.dataset[lang].remove_columns(["id_str"]) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/CyrillicTurkicLangClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/CyrillicTurkicLangClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..579f6b324381722a1c47e361709d26a7c809993c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/CyrillicTurkicLangClassification.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class CyrillicTurkicLangClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="CyrillicTurkicLangClassification", + description="Cyrillic dataset of 8 Turkic languages spoken in Russia and former USSR", + dataset={ + "path": "tatiana-merz/cyrillic_turkic_langs", + "revision": "e42d330f33d65b7b72dfd408883daf1661f06f18", + }, + reference="https://huggingface.co/datasets/tatiana-merz/cyrillic_turkic_langs", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=[ + "bak-Cyrl", # Bashkir + "chv-Cyrl", # Chuvash + "tat-Cyrl", # Tatar + "kir-Cyrl", # Kyrgyz + "rus-Cyrl", # Russian + "kaz-Cyrl", # Kazakh + "tyv-Cyrl", # Tuvinian + "krc-Cyrl", # Karachay-Balkar + "sah-Cyrl", # Yakut + ], + main_score="accuracy", + date=("1998-01-01", "2012-05-01"), + form=["written"], + domains=["Web"], + task_subtypes=["Language identification"], + license="CC BY-NC 4.0 DEED", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{goldhahn2012building, + title={Building Large Monolingual Dictionaries at the Leipzig Corpora Collection: From 100 to 200 Languages}, + author={Goldhahn, Dirk and Eckart, Thomas and Quasthoff, Uwe}, + booktitle={Proceedings of the Eighth International Conference on Language Resources and Evaluation (LREC'12)}, + year={2012} + } + """, + n_samples={"test": 2048}, + avg_character_length={"test": 92.22}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/HinDialectClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/HinDialectClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..bb2200763be21243de87bf6534384c744181fa03 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/HinDialectClassification.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + +_LANGUAGES = { + "pan": ["pan-Guru"], + "bgc": ["bgc-Deva"], + "mag": ["mag-Deva"], + "bns": ["bns-Deva"], + "kfq": ["kfg-Deva"], + "noe": ["noe-Deva"], + "bhb": ["bhb-Deva"], + "bho": ["bho-Deva"], + "gbm": ["gbm-Deva"], + "mup": ["mup-Deva"], + "anp": ["anp-Deva"], + "hne": ["hne-Deva"], + "bra": ["bra-Deva"], + "raj": ["raj-Deva"], + "awa": ["awa-Deva"], + "guj": ["guj-Gujr"], + "ben": ["ben-Beng"], + "bhd": ["bhd-Deva"], + "kfy": ["kfy-Deva"], + "mar": ["mar-Deva"], + "bjj": ["bjj-Deva"], +} + + +class HinDialectClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="HinDialectClassification", + dataset={ + "path": "mlexplorer008/hin_dialect_classification", + "revision": "944a44cf93932ce62b51e7c07d44d8cc03d6bcae", + }, + description="HinDialect: 26 Hindi-related languages and dialects of the Indic Continuum in North India", + reference="https://lindat.mff.cuni.cz/repository/xmlui/handle/11234/1-4839", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="f1", + date=("2010-01-01", "2023-01-01"), + form=["written"], + domains=["Social", "Spoken"], + task_subtypes=["Language identification"], + license="CC-BY-SA-4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @misc{11234/1-4839, + title = {{HinDialect} 1.1: 26 Hindi-related languages and dialects of the Indic Continuum in North India}, + author = {Bafna, Niyati and {\v Z}abokrtsk{\'y}, Zden{\v e}k and Espa{\~n}a-Bonet, Cristina and van Genabith, Josef and Kumar, Lalit "Samyak Lalit" and Suman, Sharda and Shivay, Rahul}, + url = {http://hdl.handle.net/11234/1-4839}, + note = {{LINDAT}/{CLARIAH}-{CZ} digital library at the Institute of Formal and Applied Linguistics ({{\'U}FAL}), Faculty of Mathematics and Physics, Charles University}, + copyright = {Creative Commons - Attribution-{NonCommercial}-{ShareAlike} 4.0 International ({CC} {BY}-{NC}-{SA} 4.0)}, + year = {2022} } + """, + n_samples={"test": 1152}, + avg_character_length={"test": 583.82}, + ) + + def dataset_transform(self) -> None: + self.dataset = self.dataset.rename_columns( + {"folksong": "text", "language": "label"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicLangClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicLangClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..bf0338ec5d43e211b838a59f37383be8ace5610c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicLangClassification.py @@ -0,0 +1,148 @@ +from __future__ import annotations + +from typing import Any + +import datasets + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + +_LANGUAGES = { + "asm_Beng": ["asm-Beng"], + "brx_Deva": ["brx-Deva"], + "ben_Beng": ["ben-Beng"], + "doi_Deva": ["doi-Deva"], + "gom_Deva": ["gom-Deva"], + "guj_Gujr": ["guj-Gujr"], + "hin_Deva": ["hin-Deva"], + "kan_Knda": ["kan-Knda"], + "kas_Arab": ["kas-Arab"], + "kas_Deva": ["kas-Deva"], + "mai_Deva": ["mai-Deva"], + "mal_Mlym": ["mal-Mlym"], + "mar_Deva": ["mar-Deva"], + "mni_Beng": ["mni-Beng"], + "mni_Mtei": ["mni-Mtei"], + "npi_Deva": ["npi-Deva"], + "ory_Orya": ["ory-Orya"], + "pan_Guru": ["pan-Guru"], + "san_Deva": ["san-Deva"], + "sat_Olck": ["sat-Olck"], + "snd_Arab": ["snd-Arab"], + "tam_Taml": ["tam-Taml"], + "tel_Telu": ["tel-Telu"], + "urd_Arab": ["urd-Arab"], +} + +LANG_MAP = { + ("Assamese", "Bengali"): "asm_Beng", + ("Bodo", "Devanagari"): "brx_Deva", + ("Bangla", "Bengali"): "ben_Beng", + ("Konkani", "Devanagari"): "gom_Deva", + ("Gujarati", "Gujarati"): "guj_Gujr", + ("Hindi", "Devanagari"): "hin_Deva", + ("Kannada", "Kannada"): "kan_Knda", + ("Maithili", "Devanagari"): "mai_Deva", + ("Malayalam", "Malayalam"): "mal_Mlym", + ("Marathi", "Devanagari"): "mar_Deva", + ("Nepali", "Devanagari"): "npi_Deva", + ("Oriya", "Oriya"): "ory_Orya", + ("Punjabi", "Gurmukhi"): "pan_Guru", + ("Sanskrit", "Devanagari"): "san_Deva", + ("Sindhi", "Perso - Arabic"): "snd_Arab", + ("Tamil", "Tamil"): "tam_Taml", + ("Telugu", "Telugu"): "tel_Telu", + ("Urdu", "Perso - Arabic"): "urd_Arab", + ("Kashmiri", "Perso - Arabic"): "kas_Arab", + ("Kashmiri", "Devanagari"): "kas_Deva", + ("Manipuri", "Meetei - Mayek"): "mni_Mtei", + ("Manipuri", "Bengali"): "mni_Beng", + ("Dogri", "Devanagari"): "doi_Deva", + ("Santali", "Ol - Chiki"): "sat_Olck", +} + + +class IndicLangClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="IndicLangClassification", + dataset={ + "path": "ai4bharat/Bhasha-Abhijnaanam", + "revision": "c54a95d9b9d62c891a03bd5da60715df7176b097", + }, + description="A language identification test set for native-script as well as Romanized text which spans 22 Indic languages.", + reference="https://arxiv.org/abs/2305.15814", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=[l for langs in _LANGUAGES.values() for l in langs], + main_score="accuracy", + date=("2022-08-01", "2023-01-01"), + form=["written"], + domains=["Web", "Non-fiction"], + task_subtypes=["Language identification"], + license="CC0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="created", + bibtex_citation="""@inproceedings{madhani-etal-2023-bhasa, + title = "Bhasa-Abhijnaanam: Native-script and romanized Language Identification for 22 {I}ndic languages", + author = "Madhani, Yash and + Khapra, Mitesh M. and + Kunchukuttan, Anoop", + editor = "Rogers, Anna and + Boyd-Graber, Jordan and + Okazaki, Naoaki", + booktitle = "Proceedings of the 61st Annual Meeting of the Association for Computational Linguistics (Volume 2: Short Papers)", + month = jul, + year = "2023", + address = "Toronto, Canada", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2023.acl-short.71", + doi = "10.18653/v1/2023.acl-short.71", + pages = "816--826" +}""", + n_samples={"test": 30418}, + avg_character_length={"test": 106.5}, + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + + labels = sorted(list(_LANGUAGES.keys())) + + data = datasets.load_dataset(**self.metadata_dict["dataset"])["train"]["data"][ + 0 + ] + + dataset = {"train": [], "test": []} + for lang, lang_code in LANG_MAP.items(): + subset = [ + item for item in data if (item["language"], item["script"]) == lang + ] + num_test_examples = min(2048, int(len(subset) * 0.7)) + subset = datasets.Dataset.from_list(subset).train_test_split( + test_size=num_test_examples, seed=42 + ) + subset = subset.map( + lambda x: {"lang_code": lang_code, "label": labels.index(lang_code)} + ) + + dataset["train"].append(subset["train"]) + dataset["test"].append(subset["test"]) + + self.dataset = datasets.DatasetDict( + { + "train": datasets.concatenate_datasets(dataset["train"]), + "test": datasets.concatenate_datasets(dataset["test"]), + } + ) + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self) -> None: + self.dataset = self.dataset.remove_columns(["language", "script"]) + self.dataset = self.dataset.rename_columns({"native sentence": "text"}) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicNLPNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicNLPNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..e08f711b1906965292d5a37b96883f8d0307d8d5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicNLPNewsClassification.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "gu": ["guj-Gujr"], + "kn": ["kan-Knda"], + "mal": ["mal-Mlym"], + "mr": ["mar-Deva"], + "tel": ["tel-Telu"], + "ori": ["ori-Orya"], + "pa": ["pan-Guru"], + "ta": ["tam-Taml"], +} + + +class IndicNLPNewsClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="IndicNLPNewsClassification", + dataset={ + "path": "Sakshamrzt/IndicNLP-Multilingual", + "revision": "3f23bd4a622a462adfb6989419cfadf7dc778f25", + }, + description="A News classification dataset in multiple Indian regional languages.", + reference="https://github.com/AI4Bharat/indicnlp_corpus#indicnlp-news-article-classification-dataset", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2020-09-01", "2022-04-09"), + form=["written"], + domains=["News"], + dialect=[], + task_subtypes=["Topic classification"], + license="cc-by-nc-4.0", + socioeconomic_status="medium", + annotations_creators="expert-annotated", + text_creation="found", + bibtex_citation=""" + @article{kunchukuttan2020indicnlpcorpus, + title={AI4Bharat-IndicNLP Corpus: Monolingual Corpora and Word Embeddings for Indic Languages}, + author={Anoop Kunchukuttan and Divyanshu Kakwani and Satish Golla and Gokul N.C. and Avik Bhattacharyya and Mitesh M. Khapra and Pratyush Kumar}, + year={2020}, + journal={arXiv preprint arXiv:2005.00085} +}""", + n_samples={"test": 2048}, + avg_character_length={"test": 1169.053974484789}, + ) + + def dataset_transform(self): + for lang in self.langs: + self.dataset[lang] = self.dataset[lang].rename_columns( + {"news": "text", "class": "label"} + ) + if lang == "pa": + self.dataset[lang] = self.dataset[lang].remove_columns("headline") + if self.dataset[lang]["test"].num_rows > 2048: + self.dataset[lang] = self.stratified_subsampling( + self.dataset[lang], + n_samples=2048, + seed=self.seed, + splits=["test"], + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..1610e603c340708e82ff897a2e05794fb2ed7cbe --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/IndicSentimentClassification.py @@ -0,0 +1,71 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "as": ["asm-Beng"], + "bd": ["brx-Deva"], + "bn": ["ben-Beng"], + "gu": ["guj-Gujr"], + "hi": ["hin-Deva"], + "kn": ["kan-Knda"], + "ml": ["mal-Mlym"], + "mr": ["mar-Deva"], + "or": ["ory-Orya"], + "pa": ["pan-Guru"], + "ta": ["tam-Taml"], + "te": ["tel-Telu"], + "ur": ["urd-Arab"], +} + + +class IndicSentimentClassification(MultilingualTask, AbsTaskClassification): + fast_loading = True + metadata = TaskMetadata( + name="IndicSentimentClassification", + dataset={ + "path": "mteb/IndicSentiment", + "revision": "3389cc78b2ffcbd33639e91dfc57e6b6b6496241", + }, + description="A new, multilingual, and n-way parallel dataset for sentiment analysis in 13 Indic languages.", + reference="https://arxiv.org/abs/2212.05409", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2022-08-01", "2022-12-20"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="CC0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="machine-translated and verified", + bibtex_citation="""@article{doddapaneni2022towards, + title = {Towards Leaving No Indic Language Behind: Building Monolingual Corpora, Benchmark and Models for Indic Languages}, + author = {Sumanth Doddapaneni and Rahul Aralikatte and Gowtham Ramesh and Shreyansh Goyal and Mitesh M. Khapra and Anoop Kunchukuttan and Pratyush Kumar}, + journal = {Annual Meeting of the Association for Computational Linguistics}, + year = {2022}, + doi = {10.18653/v1/2023.acl-long.693} +}""", + n_samples={"test": 1000}, + avg_character_length={"test": 137.6}, + ) + + def dataset_transform(self) -> None: + label_map = {"Negative": 0, "Positive": 1} + # Convert to standard format + for lang in self.hf_subsets: + self.dataset[lang] = self.dataset[lang].filter( + lambda x: x["LABEL"] is not None + ) + self.dataset[lang] = self.dataset[lang].rename_columns( + {"INDIC REVIEW": "text", "LABEL": "label_text"} + ) + self.dataset[lang] = self.dataset[lang].map( + lambda x: {"label": label_map[x["label_text"]]} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/LanguageClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/LanguageClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..58a88102556b9289fcda5a2814a958f9d565a8f8 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/LanguageClassification.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + +_LANGUAGES = { + "ar": ["ara-Arab"], + "bg": ["bul-Cyrl"], + "de": ["deu-Latn"], + "el": ["ell-Grek"], + "en": ["eng-Latn"], + "es": ["spa-Latn"], + "fr": ["fra-Latn"], + "hi": ["hin-Deva"], + "it": ["ita-Latn"], + "ja": ["jpn-Jpan"], + "nl": ["nld-Latn"], + "pl": ["pol-Latn"], + "pt": ["por-Latn"], + "ru": ["rus-Cyrl"], + "sw": ["swa-Latn"], + "th": ["tha-Thai"], + "tr": ["tur-Latn"], + "ur": ["urd-Arab"], + "vi": ["vie-Latn"], + "zh": ["cmn-Hans"], +} + + +class LanguageClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="LanguageClassification", + dataset={ + "path": "papluca/language-identification", + "revision": "aa56583bf2bc52b0565770607d6fc3faebecf9e2", + }, + description="A language identification dataset for 20 languages.", + reference="https://huggingface.co/datasets/papluca/language-identification", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2021-11-01", "2021-11-30"), + form=["written"], + domains=["Reviews", "Web", "Non-fiction", "Fiction", "Government"], + task_subtypes=["Language identification"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="", + n_samples={"test": 2048}, + avg_character_length={"test": 107.8}, + ) + + def dataset_transform(self) -> None: + self.dataset = self.dataset.rename_columns({"labels": "label"}) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MTOPDomainClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MTOPDomainClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..01ad23aaf2ef101cf541052ac5a5285455cd9346 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MTOPDomainClassification.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "en": ["eng-Latn"], + "de": ["deu-Latn"], + "es": ["spa-Latn"], + "fr": ["fra-Latn"], + "hi": ["hin-Deva"], + "th": ["tha-Thai"], +} + + +class MTOPDomainClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="MTOPDomainClassification", + dataset={ + "path": "mteb/mtop_domain", + "revision": "d80d48c1eb48d3562165c59d59d0034df9fff0bf", + }, + description="MTOP: Multilingual Task-Oriented Semantic Parsing", + reference="https://arxiv.org/pdf/2008.09335.pdf", + category="s2s", + type="Classification", + eval_splits=["validation", "test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"validation": 2235, "test": 4386}, + avg_character_length={"validation": 36.5, "test": 36.8}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MTOPIntentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MTOPIntentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..f301754d7a079cc1df2d27d4428330e92229e200 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MTOPIntentClassification.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "en": ["eng-Latn"], + "de": ["deu-Latn"], + "es": ["spa-Latn"], + "fr": ["fra-Latn"], + "hi": ["hin-Deva"], + "th": ["tha-Thai"], +} + + +class MTOPIntentClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="MTOPIntentClassification", + dataset={ + "path": "mteb/mtop_intent", + "revision": "ae001d0e6b1228650b7bd1c2c65fb50ad11a8aba", + }, + description="MTOP: Multilingual Task-Oriented Semantic Parsing", + reference="https://arxiv.org/pdf/2008.09335.pdf", + category="s2s", + type="Classification", + eval_splits=["validation", "test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"validation": 2235, "test": 4386}, + avg_character_length={"validation": 36.5, "test": 36.8}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MasakhaNEWSClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MasakhaNEWSClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..990deb832a66ca7b1fd3b5c00e2be282b30f8f28 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MasakhaNEWSClassification.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "amh": ["amh-Ethi"], + "eng": ["eng-Latn"], + "fra": ["fra-Latn"], + "hau": ["hau-Latn"], + "ibo": ["ibo-Latn"], + "lin": ["lin-Latn"], + "lug": ["lug-Latn"], + "orm": ["orm-Ethi"], + "pcm": ["pcm-Latn"], + "run": ["run-Latn"], + "sna": ["sna-Latn"], + "som": ["som-Latn"], + "swa": ["swa-Latn"], + "tir": ["tir-Ethi"], + "xho": ["xho-Latn"], + "yor": ["yor-Latn"], +} + + +class MasakhaNEWSClassification(AbsTaskClassification, MultilingualTask): + metadata = TaskMetadata( + name="MasakhaNEWSClassification", + dataset={ + "path": "mteb/masakhanews", + "revision": "18193f187b92da67168c655c9973a165ed9593dd", + }, + description="MasakhaNEWS is the largest publicly available dataset for news topic classification in 16 languages widely spoken in Africa. The train/validation/test sets are available for all the 16 languages.", + reference="https://arxiv.org/abs/2304.09972", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 422}, + avg_character_length={"test": 5116.6}, + ) + + def dataset_transform(self): + for lang in self.dataset.keys(): + self.dataset[lang] = self.dataset[lang].rename_columns( + {"category": "label"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MassiveIntentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MassiveIntentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..6ac3e76df73f436e5633264a217b9d8f4d752eeb --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MassiveIntentClassification.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "af": ["afr-Latn"], + "am": ["amh-Ethi"], + "ar": ["ara-Arab"], + "az": ["aze-Latn"], + "bn": ["ben-Beng"], + "cy": ["cym-Latn"], + "da": ["dan-Latn"], + "de": ["deu-Latn"], + "el": ["ell-Grek"], + "en": ["eng-Latn"], + "es": ["spa-Latn"], + "fa": ["fas-Arab"], + "fi": ["fin-Latn"], + "fr": ["fra-Latn"], + "he": ["heb-Hebr"], + "hi": ["hin-Deva"], + "hu": ["hun-Latn"], + "hy": ["hye-Armn"], + "id": ["ind-Latn"], + "is": ["isl-Latn"], + "it": ["ita-Latn"], + "ja": ["jpn-Jpan"], + "jv": ["jav-Latn"], + "ka": ["kat-Geor"], + "km": ["khm-Khmr"], + "kn": ["kan-Knda"], + "ko": ["kor-Kore"], + "lv": ["lav-Latn"], + "ml": ["mal-Mlym"], + "mn": ["mon-Cyrl"], + "ms": ["msa-Latn"], + "my": ["mya-Mymr"], + "nb": ["nob-Latn"], + "nl": ["nld-Latn"], + "pl": ["pol-Latn"], + "pt": ["por-Latn"], + "ro": ["ron-Latn"], + "ru": ["rus-Cyrl"], + "sl": ["slv-Latn"], + "sq": ["sqi-Latn"], + "sv": ["swe-Latn"], + "sw": ["swa-Latn"], + "ta": ["tam-Taml"], + "te": ["tel-Telu"], + "th": ["tha-Thai"], + "tl": ["tgl-Latn"], + "tr": ["tur-Latn"], + "ur": ["urd-Arab"], + "vi": ["vie-Latn"], + "zh-CN": ["cmo-Hans"], + "zh-TW": ["cmo-Hant"], +} + + +class MassiveIntentClassification(MultilingualTask, AbsTaskClassification): + fast_loading = True + metadata = TaskMetadata( + name="MassiveIntentClassification", + dataset={ + "path": "mteb/amazon_massive_intent", + "revision": "4672e20407010da34463acc759c162ca9734bca6", + }, + description="MASSIVE: A 1M-Example Multilingual Natural Language Understanding Dataset with 51 Typologically-Diverse Languages", + reference="https://arxiv.org/abs/2204.08582#:~:text=MASSIVE%20contains%201M%20realistic%2C%20parallel,diverse%20languages%20from%2029%20genera.", + category="s2s", + type="Classification", + eval_splits=["validation", "test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"validation": 2033, "test": 2974}, + avg_character_length={"validation": 34.8, "test": 34.6}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MassiveScenarioClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MassiveScenarioClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..b6e3fe90806193f7d593fe48e3c165d0c857ad40 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MassiveScenarioClassification.py @@ -0,0 +1,89 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "af": ["afr-Latn"], + "am": ["amh-Ethi"], + "ar": ["ara-Arab"], + "az": ["aze-Latn"], + "bn": ["ben-Beng"], + "cy": ["cym-Latn"], + "da": ["dan-Latn"], + "de": ["deu-Latn"], + "el": ["ell-Grek"], + "en": ["eng-Latn"], + "es": ["spa-Latn"], + "fa": ["fas-Arab"], + "fi": ["fin-Latn"], + "fr": ["fra-Latn"], + "he": ["heb-Hebr"], + "hi": ["hin-Deva"], + "hu": ["hun-Latn"], + "hy": ["hye-Armn"], + "id": ["ind-Latn"], + "is": ["isl-Latn"], + "it": ["ita-Latn"], + "ja": ["jpn-Jpan"], + "jv": ["jav-Latn"], + "ka": ["kat-Geor"], + "km": ["khm-Khmr"], + "kn": ["kan-Knda"], + "ko": ["kor-Kore"], + "lv": ["lav-Latn"], + "ml": ["mal-Mlym"], + "mn": ["mon-Cyrl"], + "ms": ["msa-Latn"], + "my": ["mya-Mymr"], + "nb": ["nob-Latn"], + "nl": ["nld-Latn"], + "pl": ["pol-Latn"], + "pt": ["por-Latn"], + "ro": ["ron-Latn"], + "ru": ["rus-Cyrl"], + "sl": ["slv-Latn"], + "sq": ["sqi-Latn"], + "sv": ["swe-Latn"], + "sw": ["swa-Latn"], + "ta": ["tam-Taml"], + "te": ["tel-Telu"], + "th": ["tha-Thai"], + "tl": ["tgl-Latn"], + "tr": ["tur-Latn"], + "ur": ["urd-Arab"], + "vi": ["vie-Latn"], + "zh-CN": ["cmo-Hans"], + "zh-TW": ["cmo-Hant"], +} + + +class MassiveScenarioClassification(MultilingualTask, AbsTaskClassification): + fast_loading = True + metadata = TaskMetadata( + name="MassiveScenarioClassification", + dataset={ + "path": "mteb/amazon_massive_scenario", + "revision": "fad2c6e8459f9e1c45d9315f4953d921437d70f8", + }, + description="MASSIVE: A 1M-Example Multilingual Natural Language Understanding Dataset with 51 Typologically-Diverse Languages", + reference="https://arxiv.org/abs/2204.08582#:~:text=MASSIVE%20contains%201M%20realistic%2C%20parallel,diverse%20languages%20from%2029%20genera.", + category="s2s", + type="Classification", + eval_splits=["validation", "test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"validation": 2033, "test": 2974}, + avg_character_length={"validation": 34.8, "test": 34.6}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MultiHateClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MultiHateClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..c3f2a8cfe1da72c9d74f18efcef3c96cbdfd08e3 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MultiHateClassification.py @@ -0,0 +1,113 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + +_LANGUAGES = { + "ara": ["ara-Arab"], + "cmn": ["cmn-Hans"], + "eng": ["eng-Latn"], + "deu": ["deu-Latn"], + "fra": ["fra-Latn"], + "hin": ["hin-Deva"], + "ita": ["ita-Latn"], + "nld": ["nld-Latn"], + "pol": ["pol-Latn"], + "por": ["por-Latn"], + "spa": ["spa-Latn"], +} + + +class MultiHateClassification(MultilingualTask, AbsTaskClassification): + fast_loading = True + metadata = TaskMetadata( + name="MultiHateClassification", + dataset={ + "path": "mteb/multi-hatecheck", + "revision": "8f95949846bb9e33c6aaf730ccfdb8fe6bcfb7a9", + }, + description="""Hate speech detection dataset with binary + (hateful vs non-hateful) labels. Includes 25+ distinct types of hate + and challenging non-hate, and 11 languages. + """, + reference="https://aclanthology.org/2022.woah-1.15/", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2020-11-23", "2022-02-28"), + form=["written"], + domains=["Constructed"], + task_subtypes=["Sentiment/Hate speech"], + license="cc-by-4.0", + socioeconomic_status="high", + annotations_creators="expert-annotated", + dialect=[], + text_creation="created", + bibtex_citation=""" + @inproceedings{rottger-etal-2021-hatecheck, + title = "{H}ate{C}heck: Functional Tests for Hate Speech Detection Models", + author = {R{\"o}ttger, Paul and + Vidgen, Bertie and + Nguyen, Dong and + Waseem, Zeerak and + Margetts, Helen and + Pierrehumbert, Janet}, + editor = "Zong, Chengqing and + Xia, Fei and + Li, Wenjie and + Navigli, Roberto", + booktitle = "Proceedings of the 59th Annual Meeting of the Association for Computational Linguistics and the 11th International Joint Conference on Natural Language Processing (Volume 1: Long Papers)", + month = aug, + year = "2021", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2021.acl-long.4", + doi = "10.18653/v1/2021.acl-long.4", + pages = "41--58", + abstract = "Detecting online hate is a difficult task that even state-of-the-art models struggle with. Typically, hate speech detection models are evaluated by measuring their performance on held-out test data using metrics such as accuracy and F1 score. However, this approach makes it difficult to identify specific model weak points. It also risks overestimating generalisable model performance due to increasingly well-evidenced systematic gaps and biases in hate speech datasets. To enable more targeted diagnostic insights, we introduce HateCheck, a suite of functional tests for hate speech detection models. We specify 29 model functionalities motivated by a review of previous research and a series of interviews with civil society stakeholders. We craft test cases for each functionality and validate their quality through a structured annotation process. To illustrate HateCheck{'}s utility, we test near-state-of-the-art transformer models as well as two popular commercial models, revealing critical model weaknesses.", + } + + @inproceedings{rottger-etal-2022-multilingual, + title = "Multilingual {H}ate{C}heck: Functional Tests for Multilingual Hate Speech Detection Models", + author = {R{\"o}ttger, Paul and + Seelawi, Haitham and + Nozza, Debora and + Talat, Zeerak and + Vidgen, Bertie}, + editor = "Narang, Kanika and + Mostafazadeh Davani, Aida and + Mathias, Lambert and + Vidgen, Bertie and + Talat, Zeerak", + booktitle = "Proceedings of the Sixth Workshop on Online Abuse and Harms (WOAH)", + month = jul, + year = "2022", + address = "Seattle, Washington (Hybrid)", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2022.woah-1.15", + doi = "10.18653/v1/2022.woah-1.15", + pages = "154--169", + abstract = "Hate speech detection models are typically evaluated on held-out test sets. However, this risks painting an incomplete and potentially misleading picture of model performance because of increasingly well-documented systematic gaps and biases in hate speech datasets. To enable more targeted diagnostic insights, recent research has thus introduced functional tests for hate speech detection models. However, these tests currently only exist for English-language content, which means that they cannot support the development of more effective models in other languages spoken by billions across the world. To help address this issue, we introduce Multilingual HateCheck (MHC), a suite of functional tests for multilingual hate speech detection models. MHC covers 34 functionalities across ten languages, which is more languages than any other hate speech dataset. To illustrate MHC{'}s utility, we train and test a high-performing multilingual hate speech detection model, and reveal critical model weaknesses for monolingual and cross-lingual applications.", + } + """, + n_samples={"test": 10000}, + avg_character_length={"test": 45.9}, + ) + + def dataset_transform(self): + # for each language perform some transforms + for lang in self.dataset.keys(): + _dataset = self.dataset[lang] + _dataset = _dataset.rename_columns({"is_hateful": "label"}) + for label in ["label", "functionality"]: + _dataset = _dataset.class_encode_column(label) + _dataset = _dataset["test"].train_test_split( + train_size=1000, + test_size=1000, + seed=self.seed, + stratify_by_column="functionality", + ) # balanced sampling across types of hate speech + _dataset = _dataset.remove_columns(["functionality"]) + self.dataset[lang] = _dataset diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MultilingualSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MultilingualSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..de177efd74abc2234e765ef1b2dde52e93d12759 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/MultilingualSentimentClassification.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification, MultilingualTask, TaskMetadata + +_LANGUAGES = { + "urd": ["urd-Arab"], + "vie": ["vie-Latn"], + "dza": ["dza-Arab"], + "tha": ["tha-Thai"], + "tur": ["tur-Latn"], + "slk": ["slk-Latn"], + "nor": ["nor-Latn"], + "spa": ["spa-Latn"], + "rus": ["rus-Cyrl"], + "mlt": ["mlt-Latn"], + "kor": ["kor-Hang"], + "ind": ["ind-Latn"], + "heb": ["heb-Latn"], + "jpn": ["jpn-Jpan"], + "ell": ["ell-Latn"], + "deu": ["deu-Latn"], + "eng": ["eng-Latn"], + "fin": ["fin-Latn"], + "hrv": ["hrv-Latn"], + "zho": ["zho-Hans"], + "cmn": ["cmn-Hans"], + "bul": ["bul-Cyrl"], + "eus": ["eus-Latn"], + "uig": ["uig-Hans"], + "bam": ["bam-Latn"], + "pol": ["pol-Latn"], + # The train set for "cym" language is created from the test set + "cym": ["cym-Latn"], + # "hin": ["hin-Deva"], # Do not handle this subset since it does not contain a test set required by the evaluation + "ara": ["ara-Arab"], + "fas": ["fas-Arab"], +} + + +class MultilingualSentimentClassification(AbsTaskClassification, MultilingualTask): + fast_loading = True + metadata = TaskMetadata( + name="MultilingualSentimentClassification", + dataset={ + "path": "mteb/multilingual-sentiment-classification", + "revision": "2b9b4d10fc589af67794141fe8cbd3739de1eb33", + }, + description="""Sentiment classification dataset with binary + (positive vs negative sentiment) labels. Includes 30 languages and dialects. + """, + reference="https://huggingface.co/datasets/mteb/multilingual-sentiment-classification", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2022-08-01", "2022-08-01"), + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=["ar-dz"], + text_creation="found", + bibtex_citation=""" + @inproceedings{mollanorozy-etal-2023-cross, + title = "Cross-lingual Transfer Learning with \{P\}ersian", + author = "Mollanorozy, Sepideh and + Tanti, Marc and + Nissim, Malvina", + editor = "Beinborn, Lisa and + Goswami, Koustava and + Murado{\\u{g}}lu, Saliha and + Sorokin, Alexey and + Kumar, Ritesh and + Shcherbakov, Andreas and + Ponti, Edoardo M. and + Cotterell, Ryan and + Vylomova, Ekaterina", + booktitle = "Proceedings of the 5th Workshop on Research in Computational Linguistic Typology and Multilingual NLP", + month = may, + year = "2023", + address = "Dubrovnik, Croatia", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2023.sigtyp-1.9", + doi = "10.18653/v1/2023.sigtyp-1.9", + pages = "89--95", + } + """, + n_samples={"test": 7000}, + avg_character_length={"test": 56}, + ) + + def dataset_transform(self): + # create a train set from the test set for Welsh language (cym) + lang = "cym" + _dataset = self.dataset[lang] + if lang in self.dataset.keys(): + _dataset = _dataset.class_encode_column("label") + _dataset = _dataset["test"].train_test_split( + test_size=0.3, seed=self.seed, stratify_by_column="label" + ) + _dataset = self.stratified_subsampling( + dataset_dict=_dataset, seed=self.seed, splits=["test"] + ) + self.dataset[lang] = _dataset diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NaijaSenti.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NaijaSenti.py new file mode 100644 index 0000000000000000000000000000000000000000..3958dc0283b65aae5acbfe8bf009e6ecb6881783 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NaijaSenti.py @@ -0,0 +1,87 @@ +from typing import Any + +import datasets + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class NaijaSenti(AbsTaskClassification, MultilingualTask): + metadata = TaskMetadata( + name="NaijaSenti", + description="NaijaSenti is the first large-scale human-annotated Twitter sentiment dataset for the four most widely spoken languages in Nigeria — Hausa, Igbo, Nigerian-Pidgin, and Yorùbá — consisting of around 30,000 annotated tweets per language, including a significant fraction of code-mixed tweets.", + reference="https://github.com/hausanlp/NaijaSenti", + dataset={ + "path": "HausaNLP/NaijaSenti-Twitter", + "revision": "a3d0415a828178edf3466246f49cfcd83b946ab3", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs={ + "hau": ["hau-Latn"], + "ibo": ["ibo-Latn"], + "pcm": ["pcm-Latn"], + "yor": ["yor-Latn"], + }, + main_score="accuracy", + date=("2022-05-01", "2023-05-08"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="CC-BY-4.0 license", + socioeconomic_status="low", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{muhammad-etal-2022-naijasenti, + title = "{N}aija{S}enti: A {N}igerian {T}witter Sentiment Corpus for Multilingual Sentiment Analysis", + author = "Muhammad, Shamsuddeen Hassan and + Adelani, David Ifeoluwa and + Ruder, Sebastian and + Ahmad, Ibrahim Sa{'}id and + Abdulmumin, Idris and + Bello, Bello Shehu and + Choudhury, Monojit and + Emezue, Chris Chinenye and + Abdullahi, Saheed Salahudeen and + Aremu, Anuoluwapo and + Jorge, Al{\'\i}pio and + Brazdil, Pavel", + booktitle = "Proceedings of the Thirteenth Language Resources and Evaluation Conference", + month = jun, + year = "2022", + address = "Marseille, France", + publisher = "European Language Resources Association", + url = "https://aclanthology.org/2022.lrec-1.63", + pages = "590--602", + }""", + n_samples={"test": 4800}, + avg_character_length={"test": 72.81}, + ) + + def load_data(self, **kwargs: Any) -> None: + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + self.dataset = {} + for lang in self.hf_subsets: + self.dataset[lang] = datasets.load_dataset( + name=f"{lang}", + **self.metadata_dict["dataset"], + ) + self.dataset[lang] = datasets.DatasetDict( + { + "train": self.dataset[lang]["train"], + "test": self.dataset[lang]["test"], + } + ) + self.dataset_transform() + self.data_loaded = True + + def dataset_transform(self) -> None: + for lang in self.hf_subsets: + self.dataset[lang] = self.dataset[lang].map( + lambda example: {"text": example["tweet"]} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NordicLangClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NordicLangClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..d54d03d2d42ce5c263561242db37e76841c452c1 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NordicLangClassification.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class NordicLangClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="NordicLangClassification", + description="A dataset for Nordic language identification.", + reference="https://aclanthology.org/2021.vardial-1.8/", + dataset={ + "path": "strombergnlp/nordic_langid", + "revision": "e254179d18ab0165fdb6dbef91178266222bee2a", + "name": "10k", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=[ + "nob-Latn", + "nno-Latn", + "dan-Latn", + "swe-Latn", + "isl-Latn", + "fao-Latn", + ], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 3000}, + avg_character_length={"test": 78.2}, + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = super().metadata_dict + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 32 + return metadata_dict + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns( + {"sentence": "text", "language": "label"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NusaXSenti.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NusaXSenti.py new file mode 100644 index 0000000000000000000000000000000000000000..7584c7f33892547a2c41b687d71d22bad119614e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/NusaXSenti.py @@ -0,0 +1,66 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import MultilingualTask + + +class NusaXSentiClassification(AbsTaskClassification, MultilingualTask): + metadata = TaskMetadata( + name="NusaX-senti", + description="NusaX is a high-quality multilingual parallel corpus that covers 12 languages, Indonesian, English, and 10 Indonesian local languages, namely Acehnese, Balinese, Banjarese, Buginese, Madurese, Minangkabau, Javanese, Ngaju, Sundanese, and Toba Batak. NusaX-Senti is a 3-labels (positive, neutral, negative) sentiment analysis dataset for 10 Indonesian local languages + Indonesian and English.", + reference="https://arxiv.org/abs/2205.15960", + dataset={ + "path": "indonlp/NusaX-senti", + "revision": "a450ba4b1b6d2216c3674d3e576b2e85ce729add", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs={ + "ace": ["ace-Latn"], + "ban": ["ban-Latn"], + "bjn": ["bjn-Latn"], + "bug": ["bug-Latn"], + "eng": ["eng-Latn"], + "ind": ["ind-Latn"], + "jav": ["jav-Latn"], + "mad": ["mad-Latn"], + "min": ["min-Latn"], + "nij": ["nij-Latn"], + "sun": ["sun-Latn"], + "bbc": ["bbc-Latn"], + }, + main_score="accuracy", + date=("2022-05-01", "2023-05-08"), + form=["written"], + domains=[ + "Reviews", + "Web", + "Social", + "Constructed", + ], + task_subtypes=["Sentiment/Hate speech"], + license="CC-BY-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @misc{winata2022nusax, + title={NusaX: Multilingual Parallel Sentiment Dataset for 10 Indonesian Local Languages}, + author={Winata, Genta Indra and Aji, Alham Fikri and Cahyawijaya, + Samuel and Mahendra, Rahmad and Koto, Fajri and Romadhony, + Ade and Kurniawan, Kemal and Moeljadi, David and Prasojo, + Radityo Eko and Fung, Pascale and Baldwin, Timothy and Lau, + Jey Han and Sennrich, Rico and Ruder, Sebastian}, + year={2022}, + eprint={2205.15960}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +} +""", + n_samples={"test": 4800}, + avg_character_length={"test": 52.4}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SIB200Classification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SIB200Classification.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc4820086927e968691eeb31340cc0c548a99ba --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SIB200Classification.py @@ -0,0 +1,251 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + +_LANGS = { + "ace_Latn": ["ace-Latn"], + "acm_Arab": ["acm-Arab"], + "acq_Arab": ["acq-Arab"], + "aeb_Arab": ["aeb-Arab"], + "afr_Latn": ["afr-Latn"], + "ajp_Arab": ["ajp-Arab"], + "aka_Latn": ["aka-Latn"], + "als_Latn": ["als-Latn"], + "amh_Ethi": ["amh-Ethi"], + "apc_Arab": ["apc-Arab"], + "arb_Latn": ["arb-Latn"], + "ars_Arab": ["ars-Arab"], + "ary_Arab": ["ary-Arab"], + "arz_Arab": ["arz-Arab"], + "asm_Beng": ["asm-Beng"], + "ast_Latn": ["ast-Latn"], + "awa_Deva": ["awa-Deva"], + "ayr_Latn": ["ayr-Latn"], + "azb_Arab": ["azb-Arab"], + "azj_Latn": ["azj-Latn"], + "bak_Cyrl": ["bak-Cyrl"], + "bam_Latn": ["bam-Latn"], + "ban_Latn": ["ban-Latn"], + "bel_Cyrl": ["bel-Cyrl"], + "bem_Latn": ["bem-Latn"], + "ben_Beng": ["ben-Beng"], + "bho_Deva": ["bho-Deva"], + "bjn_Latn": ["bjn-Latn"], + "bod_Tibt": ["bod-Tibt"], + "bos_Latn": ["bos-Latn"], + "bug_Latn": ["bug-Latn"], + "bul_Cyrl": ["bul-Cyrl"], + "cat_Latn": ["cat-Latn"], + "ceb_Latn": ["ceb-Latn"], + "ces_Latn": ["ces-Latn"], + "cjk_Latn": ["cjk-Latn"], + "ckb_Arab": ["ckb-Arab"], + "crh_Latn": ["crh-Latn"], + "cym_Latn": ["cym-Latn"], + "dan_Latn": ["dan-Latn"], + "deu_Latn": ["deu-Latn"], + "dik_Latn": ["dik-Latn"], + "dyu_Latn": ["dyu-Latn"], + "dzo_Tibt": ["dzo-Tibt"], + "ell_Grek": ["ell-Grek"], + "eng_Latn": ["eng-Latn"], + "epo_Latn": ["epo-Latn"], + "est_Latn": ["est-Latn"], + "eus_Latn": ["eus-Latn"], + "ewe_Latn": ["ewe-Latn"], + "fao_Latn": ["fao-Latn"], + "fij_Latn": ["fij-Latn"], + "fin_Latn": ["fin-Latn"], + "fon_Latn": ["fon-Latn"], + "fra_Latn": ["fra-Latn"], + "fur_Latn": ["fur-Latn"], + "fuv_Latn": ["fuv-Latn"], + "gaz_Latn": ["gaz-Latn"], + "gla_Latn": ["gla-Latn"], + "gle_Latn": ["gle-Latn"], + "glg_Latn": ["glg-Latn"], + "grn_Latn": ["grn-Latn"], + "guj_Gujr": ["guj-Gujr"], + "hat_Latn": ["hat-Latn"], + "hau_Latn": ["hau-Latn"], + "heb_Hebr": ["heb-Hebr"], + "hin_Deva": ["hin-Deva"], + "hne_Deva": ["hne-Deva"], + "hrv_Latn": ["hrv-Latn"], + "hun_Latn": ["hun-Latn"], + "hye_Armn": ["hye-Armn"], + "ibo_Latn": ["ibo-Latn"], + "ilo_Latn": ["ilo-Latn"], + "ind_Latn": ["ind-Latn"], + "isl_Latn": ["isl-Latn"], + "ita_Latn": ["ita-Latn"], + "jav_Latn": ["jav-Latn"], + "jpn_Jpan": ["jpn-Jpan"], + "kab_Latn": ["kab-Latn"], + "kac_Latn": ["kac-Latn"], + "kam_Latn": ["kam-Latn"], + "kan_Knda": ["kan-Knda"], + "kas_Deva": ["kas-Deva"], + "kat_Geor": ["kat-Geor"], + "kaz_Cyrl": ["kaz-Cyrl"], + "kbp_Latn": ["kbp-Latn"], + "kea_Latn": ["kea-Latn"], + "khk_Cyrl": ["khk-Cyrl"], + "khm_Khmr": ["khm-Khmr"], + "kik_Latn": ["kik-Latn"], + "kin_Latn": ["kin-Latn"], + "kir_Cyrl": ["kir-Cyrl"], + "kmb_Latn": ["kmb-Latn"], + "kmr_Latn": ["kmr-Latn"], + "knc_Latn": ["knc-Latn"], + "kon_Latn": ["kon-Latn"], + "kor_Hang": ["kor-Hang"], + "lao_Laoo": ["lao-Laoo"], + "lij_Latn": ["lij-Latn"], + "lim_Latn": ["lim-Latn"], + "lin_Latn": ["lin-Latn"], + "lit_Latn": ["lit-Latn"], + "lmo_Latn": ["lmo-Latn"], + "ltg_Latn": ["ltg-Latn"], + "ltz_Latn": ["ltz-Latn"], + "lua_Latn": ["lua-Latn"], + "lug_Latn": ["lug-Latn"], + "luo_Latn": ["luo-Latn"], + "lus_Latn": ["lus-Latn"], + "lvs_Latn": ["lvs-Latn"], + "mag_Deva": ["mag-Deva"], + "mai_Deva": ["mai-Deva"], + "mal_Mlym": ["mal-Mlym"], + "mar_Deva": ["mar-Deva"], + "min_Latn": ["min-Latn"], + "mkd_Cyrl": ["mkd-Cyrl"], + "mlt_Latn": ["mlt-Latn"], + "mni_Beng": ["mni-Beng"], + "mos_Latn": ["mos-Latn"], + "mri_Latn": ["mri-Latn"], + "mya_Mymr": ["mya-Mymr"], + "nld_Latn": ["nld-Latn"], + "nno_Latn": ["nno-Latn"], + "nob_Latn": ["nob-Latn"], + "npi_Deva": ["npi-Deva"], + "nqo_Nkoo": ["nqo-Nkoo"], + "nso_Latn": ["nso-Latn"], + "nus_Latn": ["nus-Latn"], + "nya_Latn": ["nya-Latn"], + "oci_Latn": ["oci-Latn"], + "ory_Orya": ["ory-Orya"], + "pag_Latn": ["pag-Latn"], + "pan_Guru": ["pan-Guru"], + "pap_Latn": ["pap-Latn"], + "pbt_Arab": ["pbt-Arab"], + "pes_Arab": ["pes-Arab"], + "plt_Latn": ["plt-Latn"], + "pol_Latn": ["pol-Latn"], + "por_Latn": ["por-Latn"], + "prs_Arab": ["prs-Arab"], + "quy_Latn": ["quy-Latn"], + "ron_Latn": ["ron-Latn"], + "run_Latn": ["run-Latn"], + "rus_Cyrl": ["rus-Cyrl"], + "sag_Latn": ["sag-Latn"], + "san_Deva": ["san-Deva"], + "sat_Olck": ["sat-Olck"], + "scn_Latn": ["scn-Latn"], + "shn_Mymr": ["shn-Mymr"], + "sin_Sinh": ["sin-Sinh"], + "slk_Latn": ["slk-Latn"], + "slv_Latn": ["slv-Latn"], + "smo_Latn": ["smo-Latn"], + "sna_Latn": ["sna-Latn"], + "snd_Arab": ["snd-Arab"], + "som_Latn": ["som-Latn"], + "sot_Latn": ["sot-Latn"], + "spa_Latn": ["spa-Latn"], + "srd_Latn": ["srd-Latn"], + "srp_Cyrl": ["srp-Cyrl"], + "ssw_Latn": ["ssw-Latn"], + "sun_Latn": ["sun-Latn"], + "swe_Latn": ["swe-Latn"], + "swh_Latn": ["swh-Latn"], + "szl_Latn": ["szl-Latn"], + "tam_Taml": ["tam-Taml"], + "taq_Tfng": ["taq-Tfng"], + "tat_Cyrl": ["tat-Cyrl"], + "tel_Telu": ["tel-Telu"], + "tgk_Cyrl": ["tgk-Cyrl"], + "tgl_Latn": ["tgl-Latn"], + "tha_Thai": ["tha-Thai"], + "tir_Ethi": ["tir-Ethi"], + "tpi_Latn": ["tpi-Latn"], + "tsn_Latn": ["tsn-Latn"], + "tso_Latn": ["tso-Latn"], + "tuk_Latn": ["tuk-Latn"], + "tum_Latn": ["tum-Latn"], + "tur_Latn": ["tur-Latn"], + "twi_Latn": ["twi-Latn"], + "tzm_Tfng": ["tzm-Tfng"], + "uig_Arab": ["uig-Arab"], + "ukr_Cyrl": ["ukr-Cyrl"], + "umb_Latn": ["umb-Latn"], + "urd_Arab": ["urd-Arab"], + "uzn_Latn": ["uzn-Latn"], + "vec_Latn": ["vec-Latn"], + "vie_Latn": ["vie-Latn"], + "war_Latn": ["war-Latn"], + "wol_Latn": ["wol-Latn"], + "xho_Latn": ["xho-Latn"], + "ydd_Hebr": ["ydd-Hebr"], + "yor_Latn": ["yor-Latn"], + "yue_Hant": ["yue-Hant"], + "zho_Hant": ["zho-Hant"], + "zsm_Latn": ["zsm-Latn"], + "zul_Latn": ["zul-Latn"], +} + + +class SIB200Classification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="SIB200Classification", + description="""SIB-200 is the largest publicly available topic classification + dataset based on Flores-200 covering 205 languages and dialects annotated. The dataset is + annotated in English for the topics, science/technology, travel, politics, sports, + health, entertainment, and geography. The labels are then transferred to the other languages + in Flores-200 which are machine-translated. + """, + reference="https://arxiv.org/abs/2309.07445", + dataset={ + "path": "mteb/sib200", + "revision": "a74d7350ea12af010cfb1c21e34f1f81fd2e615b", + }, + type="Classification", + category="s2s", + eval_splits=["train", "validation", "test"], + eval_langs=_LANGS, + main_score="accuracy", + date=("2023-09-14", "2024-01-27"), + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="cc-by-sa-4.0", + socioeconomic_status="high", + annotations_creators="expert-annotated", # expert annotated for English --> human translations + dialect=[], + text_creation="human-translated and localized", + bibtex_citation="""@article{adelani2023sib, + title={SIB-200: A simple, inclusive, and big evaluation dataset for topic classification in 200+ languages and dialects}, + author={Adelani, David Ifeoluwa and Liu, Hannah and Shen, Xiaoyu and Vassilyev, Nikita and Alabi, Jesujoba O and Mao, Yanke and Gao, Haonan and Lee, Annie En-Shiun}, + journal={arXiv preprint arXiv:2309.07445}, + year={2023} + }""", + n_samples={"train": 701, "validation": 99, "test": 204}, + avg_character_length={"train": 111.24, "validation": 97.11, "test": 135.53}, + ) + + def dataset_transform(self): + for lang in self.dataset.keys(): + self.dataset[lang] = self.dataset[lang].class_encode_column("category") + self.dataset[lang] = self.dataset[lang].rename_columns( + {"category": "label"} + ) + self.dataset[lang] = self.dataset[lang].remove_columns(["index_id"]) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/ScalaClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/ScalaClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..89a8e417c7c8298dceadd6b5fea0b12e040e963e --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/ScalaClassification.py @@ -0,0 +1,72 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + +_LANGS = { + "Danish": ["dan-Latn"], + "Norwegian_b": ["nob-Latn"], + "Norwegian_n": ["nno-Latn"], + "Swedish": ["swe-Latn"], +} + + +class ScalaClassification(AbsTaskClassification, MultilingualTask): + metadata = TaskMetadata( + name="ScalaClassification", + description="""ScaLa a linguistic acceptability dataset for the mainland Scandinavian languages automatically constructed from dependency annotations in Universal Dependencies Treebanks. + Published as part of 'ScandEval: A Benchmark for Scandinavian Natural Language Processing'""", + reference="https://aclanthology.org/2023.nodalida-1.20/", + dataset={ + "path": "mteb/multilingual-scala-classification", + "revision": "ec85bb6c69679ed15ac66c0bf6e180bf563eb137", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=_LANGS, + main_score="accuracy", + date=( + "1990-01-01", + "2023-01-01", + ), # derived from dependency treebank, this a the best guess + form=["written"], + domains=["Fiction", "News", "Non-fiction", "Blog", "Spoken", "Web"], + task_subtypes=["Linguistic acceptability"], + license="CC BY-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="created", + bibtex_citation="""@inproceedings{nielsen-2023-scandeval, + title = "{S}cand{E}val: A Benchmark for {S}candinavian Natural Language Processing", + author = "Nielsen, Dan", + editor = {Alum{\"a}e, Tanel and + Fishel, Mark}, + booktitle = "Proceedings of the 24th Nordic Conference on Computational Linguistics (NoDaLiDa)", + month = may, + year = "2023", + address = "T{\'o}rshavn, Faroe Islands", + publisher = "University of Tartu Library", + url = "https://aclanthology.org/2023.nodalida-1.20", + pages = "185--201", + }""", + n_samples={"test": len(_LANGS) * 1024}, + avg_character_length={"test": 102.72}, + ) + + @property + def metadata_dict(self) -> dict[str, str]: + metadata_dict = super().metadata_dict + metadata_dict["n_experiments"] = 10 + metadata_dict["samples_per_label"] = 32 + return metadata_dict + + def dataset_transform(self): + for lang in self.dataset.keys(): + # convert label to a 0/1 label + labels = self.dataset[lang]["train"]["label"] # type: ignore + lab2idx = {lab: idx for idx, lab in enumerate(set(labels))} + self.dataset[lang] = self.dataset[lang].map( + lambda x: {"label": lab2idx[x["label"]]}, remove_columns=["label"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SouthAfricanLangClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SouthAfricanLangClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..6c83775ca4cfa19a27b2c509550d2bf399d6b3c5 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SouthAfricanLangClassification.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + +_LANGUAGES = { + "afr": ["afr-Latn"], + "eng": ["eng-Latn"], + "nbl": ["nbl-Latn"], + "nso": ["nso-Latn"], + "sot": ["sot-Latn"], + "ssw": ["ssw-Latn"], + "tsn": ["tsn-Latn"], + "tso": ["tso-Latn"], + "ven": ["ven-Latn"], + "xho": ["xho-Latn"], + "zul": ["zul-Latn"], +} + + +class SouthAfricanLangClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="SouthAfricanLangClassification", + dataset={ + "path": "mlexplorer008/south_african_language_identification", + "revision": "5ccda92ffd7e74fa91fed595a1cbcff1bb68ec2d", + }, + description="A language identification test set for 11 South African Languages.", + reference="https://www.kaggle.com/competitions/south-african-language-identification/", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2010-01-01", "2023-01-01"), + form=["written"], + domains=["Web", "Non-fiction"], + task_subtypes=["Language identification"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation="", + n_samples={"test": 2048}, + avg_character_length={"test": 247.49}, + ) + + def dataset_transform(self) -> None: + self.dataset = self.dataset.rename_columns( + {" text": "text", "lang_id": "label"} + ) + self.dataset = self.stratified_subsampling(self.dataset, seed=self.seed) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SwissJudgementClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SwissJudgementClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..c8b5dea156037cd0b1ad44e05d4c27f93c7f2ca1 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/SwissJudgementClassification.py @@ -0,0 +1,62 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class SwissJudgementClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="SwissJudgementClassification", + description="Multilingual, diachronic dataset of Swiss Federal Supreme Court cases annotated with the respective binarized judgment outcome (approval/dismissal)", + reference="https://aclanthology.org/2021.nllp-1.3/", + dataset={ + "path": "rcds/swiss_judgment_prediction", + "revision": "29806f87bba4f23d0707d3b6d9ea5432afefbe2f", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs={ + "de": ["deu-Latn"], + "fr": ["fra-Latn"], + "it": ["ita-Latn"], + }, + main_score="accuracy", + date=("2020-12-15", "2022-04-08"), + form=["written"], + domains=["Legal"], + task_subtypes=[ + "Political classification", + ], + license="CC-BY-4.0", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""@misc{niklaus2022empirical, + title={An Empirical Study on Cross-X Transfer for Legal Judgment Prediction}, + author={Joel Niklaus and Matthias Stürmer and Ilias Chalkidis}, + year={2022}, + eprint={2209.12325}, + archivePrefix={arXiv}, + primaryClass={cs.CL} +} +""", + n_samples={"test": 2048}, + avg_character_length={"test": 3411.72}, + ) + + def dataset_transform(self): + for lang in self.hf_subsets: + dataset = self.dataset[lang]["test"] + dataset_dict = {"test": dataset} + + subsampled_dataset_dict = self.stratified_subsampling( + dataset_dict=dataset_dict, + seed=42, + splits=["test"], + label="label", + n_samples=min(2048, len(dataset["text"])) - 2, + ) + + self.dataset[lang]["test"] = subsampled_dataset_dict["test"] diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/TurkicClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/TurkicClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..e158b1754e55c743708dab62a56c241d156d8468 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/TurkicClassification.py @@ -0,0 +1,75 @@ +from __future__ import annotations + +from collections import Counter + +import datasets +from datasets import DatasetDict + +from mteb.abstasks import AbsTaskClassification, MultilingualTask +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class TurkicClassification(MultilingualTask, AbsTaskClassification): + metadata = TaskMetadata( + name="TurkicClassification", + description="A dataset of news classification in three Turkic languages.", + dataset={ + "path": "Electrotubbie/classification_Turkic_languages", + "revision": "db1a67c1bdd54fbb8536af026dc8596f00f9c41d", + }, + reference="https://huggingface.co/datasets/Electrotubbie/classification_Turkic_languages/", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs={ + "ky": ["kir-Cyrl"], + "kk": ["kaz-Cyrl"], + "ba": ["bak-Cyrl"], + }, + main_score="accuracy", + date=("2023-02-16", "2023-09-03"), + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="Not specified", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + """, + n_samples={"train": 193056}, + avg_character_length={"train": 1103.13}, + ) + + def transform_data(self, dataset, lang): + dataset_lang = DatasetDict() + label_count = Counter(dataset["train"]["label"]) + dataset_lang["train"] = dataset["train"].filter( + lambda example: example["lang"] == lang + and label_count[example["label"]] >= 20 + ) + dataset_lang = self.stratified_subsampling( + dataset_lang, seed=self.seed, splits=["train"] + ) + return dataset_lang["train"] + + def load_data(self, **kwargs): + """Load dataset from HuggingFace hub""" + if self.data_loaded: + return + dataset = {} + metadata = self.metadata_dict.get("dataset", None) + full_dataset = datasets.load_dataset(**metadata) + full_dataset = full_dataset.rename_columns( + {"processed_text": "text", "category": "label"} + ) + for lang in self.langs: + dataset[lang] = DatasetDict() + filtered_dataset = self.transform_data(full_dataset, lang) + + dataset[lang]["train"] = filtered_dataset + + self.dataset = dataset + self.dataset_transform() + self.data_loaded = True diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/TweetSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/TweetSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..54a0ca27144d8c1e9cbfda347cf02a8c6158b486 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/TweetSentimentClassification.py @@ -0,0 +1,67 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification, MultilingualTask + +_LANGUAGES = { + "arabic": ["ara-Arab"], + "english": ["eng-Latn"], + "german": ["deu-Latn"], + "french": ["fra-Latn"], + "italian": ["ita-Latn"], + "portuguese": ["por-Latn"], + "spanish": ["spa-Latn"], + "hindi": ["hin-Deva"], +} + + +class TweetSentimentClassification(MultilingualTask, AbsTaskClassification): + fast_loading = True + metadata = TaskMetadata( + name="TweetSentimentClassification", + dataset={ + "path": "mteb/tweet_sentiment_multilingual", + "revision": "d522bb117c32f5e0207344f69f7075fc9941168b", + }, + description="A multilingual Sentiment Analysis dataset consisting of tweets in 8 different languages.", + reference="https://aclanthology.org/2022.lrec-1.27", + category="s2s", + type="Classification", + eval_splits=["test"], + eval_langs=_LANGUAGES, + main_score="accuracy", + date=("2018-05-01", "2020-03-31"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="cc-by-3.0", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{barbieri-etal-2022-xlm, + title = "{XLM}-{T}: Multilingual Language Models in {T}witter for Sentiment Analysis and Beyond", + author = "Barbieri, Francesco and + Espinosa Anke, Luis and + Camacho-Collados, Jose", + booktitle = "Proceedings of the Thirteenth Language Resources and Evaluation Conference", + month = jun, + year = "2022", + address = "Marseille, France", + publisher = "European Language Resources Association", + url = "https://aclanthology.org/2022.lrec-1.27", + pages = "258--266", + abstract = "Language models are ubiquitous in current NLP, and their multilingual capacity has recently attracted considerable attention. However, current analyses have almost exclusively focused on (multilingual variants of) standard benchmarks, and have relied on clean pre-training and task-specific corpora as multilingual signals. In this paper, we introduce XLM-T, a model to train and evaluate multilingual language models in Twitter. In this paper we provide: (1) a new strong multilingual baseline consisting of an XLM-R (Conneau et al. 2020) model pre-trained on millions of tweets in over thirty languages, alongside starter code to subsequently fine-tune on a target task; and (2) a set of unified sentiment analysis Twitter datasets in eight different languages and a XLM-T model trained on this dataset.", + } + """, + n_samples={"test": 2048}, + avg_character_length={"test": 83.51}, + ) + + def dataset_transform(self): + for lang in self.hf_subsets: + self.dataset[lang] = self.stratified_subsampling( + self.dataset[lang], n_samples=256, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/multilingual/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mya/MyanmarNews.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mya/MyanmarNews.py new file mode 100644 index 0000000000000000000000000000000000000000..f26583b28660cff4a7cf52e5b68aa3f08c2ad7a0 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mya/MyanmarNews.py @@ -0,0 +1,45 @@ +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class MyanmarNews(AbsTaskClassification): + metadata = TaskMetadata( + name="MyanmarNews", + dataset={ + "path": "ayehninnkhine/myanmar_news", + "revision": "b899ec06227db3679b0fe3c4188a6b48cc0b65eb", + }, + description="The Myanmar News dataset on Hugging Face contains news articles in Burmese. It is designed for tasks such as text classification, sentiment analysis, and language modeling. The dataset includes a variety of news topics in 4 categorie, providing a rich resource for natural language processing applications involving Burmese which is a low resource language.", + reference="https://huggingface.co/datasets/myanmar_news", + type="Classification", + category="p2p", + eval_splits=["train"], + eval_langs=["mya-Mymr"], + main_score="accuracy", + date=("2017-10-01", "2017-10-31"), + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="GPL 3.0", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="""" + @inproceedings{Khine2017, + author = {A. H. Khine and K. T. Nwet and K. M. Soe}, + title = {Automatic Myanmar News Classification}, + booktitle = {15th Proceedings of International Conference on Computer Applications}, + year = {2017}, + month = {February}, + pages = {401--408} + }""", + n_samples={"train": 2048}, + avg_character_length={"train": 174.2}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"category": "label"}) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mya/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/mya/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nep/NepaliNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nep/NepaliNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..830e35a5ceb01fd1e29e9821d38241388bce6790 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nep/NepaliNewsClassification.py @@ -0,0 +1,59 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class NepaliNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="NepaliNewsClassification", + description="A Nepali dataset for 7500 news articles ", + reference="https://github.com/goru001/nlp-for-nepali", + dataset={ + "path": "bpHigh/iNLTK_Nepali_News_Dataset", + "revision": "79125f20d858a08f71ec4923169a6545221725c4", + }, + type="Classification", + category="s2s", + date=("2019-01-01", "2020-01-01"), + eval_splits=["train"], + eval_langs=["nep-Deva"], + main_score="accuracy", + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="CC BY-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{arora-2020-inltk, + title = "i{NLTK}: Natural Language Toolkit for Indic Languages", + author = "Arora, Gaurav", + editor = "Park, Eunjeong L. and + Hagiwara, Masato and + Milajevs, Dmitrijs and + Liu, Nelson F. and + Chauhan, Geeticka and + Tan, Liling", + booktitle = "Proceedings of Second Workshop for NLP Open Source Software (NLP-OSS)", + month = nov, + year = "2020", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2020.nlposs-1.10", + doi = "10.18653/v1/2020.nlposs-1.10", + pages = "66--71", + abstract = "We present iNLTK, an open-source NLP library consisting of pre-trained language models and out-of-the-box support for Data Augmentation, Textual Similarity, Sentence Embeddings, Word Embeddings, Tokenization and Text Generation in 13 Indic Languages. By using pre-trained models from iNLTK for text classification on publicly available datasets, we significantly outperform previously reported results. On these datasets, we also show that by using pre-trained models and data augmentation from iNLTK, we can achieve more than 95{\%} of the previous best performance by using less than 10{\%} of the training data. iNLTK is already being widely used by the community and has 40,000+ downloads, 600+ stars and 100+ forks on GitHub.", + } + """, + n_samples={"train": 5975, "test": 1495}, + avg_character_length={"train": 196.61, "test": 196.017}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("paras", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nep/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nep/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nld/DutchBookReviewSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nld/DutchBookReviewSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..b5caef35856f7f41e46a6843293cca792e2e4c80 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nld/DutchBookReviewSentimentClassification.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class DutchBookReviewSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="DutchBookReviewSentimentClassification", + description="A Dutch book review for sentiment classification.", + reference="https://github.com/benjaminvdb/DBRD", + dataset={ + "path": "benjaminvdb/dbrd", + "revision": "3f756ab4572e071eb53e887ab629f19fa747d39e", + }, + type="Classification", + category="s2s", + date=("2019-10-04", "2019-10-04"), + eval_splits=["test"], + eval_langs=["nld-Latn"], + main_score="accuracy", + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="CC BY-NC-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="""@article{DBLP:journals/corr/abs-1910-00896, + author = {Benjamin, van der Burgh and + Suzan, Verberne}, + title = {The merits of Universal Language Model Fine-tuning for Small Datasets + - a case with Dutch book reviews}, + journal = {CoRR}, + volume = {abs/1910.00896}, + year = {2019}, + url = {http://arxiv.org/abs/1910.00896}, + archivePrefix = {arXiv}, + eprint = {1910.00896}, + timestamp = {Fri, 04 Oct 2019 12:28:06 +0200}, + biburl = {https://dblp.org/rec/journals/corr/abs-1910-00896.bib}, + bibsource = {dblp computer science bibliography, https://dblp.org} +} +""", + n_samples={"test": 2224}, + avg_character_length={"test": 1443.0}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nld/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nld/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/NoRecClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/NoRecClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..0f4a0006b23a085781b71f51cfe9653a302bd06c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/NoRecClassification.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class NoRecClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="NoRecClassification", + description="A Norwegian dataset for sentiment classification on review", + reference="https://aclanthology.org/L18-1661/", + dataset={ + # using the mini version to keep results ~comparable to the ScandEval benchmark + "path": "mteb/norec_classification", + "revision": "5b740b7c42c73d586420812a35745fc37118862f", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["nob-Latn"], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 2050}, + avg_character_length={"test": 82}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/NorwegianParliamentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/NorwegianParliamentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..9729acd5ab4255234108c03ecc56a809a78bb59f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/NorwegianParliamentClassification.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class NorwegianParliamentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="NorwegianParliamentClassification", + description="Norwegian parliament speeches annotated for sentiment", + reference="https://huggingface.co/datasets/NbAiLab/norwegian_parliament", + dataset={ + "path": "NbAiLab/norwegian_parliament", + "revision": "f7393532774c66312378d30b197610b43d751972", + }, + type="Classification", + category="s2s", + eval_splits=["test", "validation"], + eval_langs=["nob-Latn"], + # assumed to be bokmål + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 1200, "validation": 1200}, + avg_character_length={"test": 1884.0, "validation": 1911.0}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/nob/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ory/OdiaNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ory/OdiaNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..8877aef13bb7d3f1d7be14fb8d773ccdc6836935 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ory/OdiaNewsClassification.py @@ -0,0 +1,37 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class OdiaNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="OdiaNewsClassification", + description="A Odia dataset for 3-class classification of Odia news articles", + reference="https://github.com/goru001/nlp-for-odia", + dataset={ + "path": "mlexplorer008/odia_news_classification", + "revision": "ffb8a34c9637fb20256e8c7be02504d16af4bd6b", + }, + type="Classification", + category="s2s", + date=("2014-01-01", "2018-01-01"), + eval_splits=["test"], + eval_langs=["ory-Orya"], + main_score="f1", + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="", + n_samples={"test": 2048}, + avg_character_length={"test": 49.24}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"headings": "text"}) + self.dataset = self.stratified_subsampling(self.dataset, seed=self.seed) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pan/PunjabiNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pan/PunjabiNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b91e31ff3db7bc3c2f64b5a3a5f80a9687a825 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pan/PunjabiNewsClassification.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class PunjabiNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="PunjabiNewsClassification", + description="A Punjabi dataset for 2-class classification of Punjabi news articles", + reference="https://github.com/goru001/nlp-for-punjabi/", + dataset={ + "path": "mlexplorer008/punjabi_news_classification", + "revision": "cec3923e16519efe51d535497e711932b8f1dc44", + }, + type="Classification", + category="s2s", + date=("2014-01-01", "2018-01-01"), + eval_splits=["test"], + eval_langs=["pan-Guru"], + main_score="accuracy", + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=None, + n_samples={"train": 627, "test": 157}, + avg_character_length={"train": 4222.22, "test": 4115.14}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns( + {"article": "text", "is_about_politics": "label"} + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pol/PolishClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pol/PolishClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..a4a1130bb9e18999f2a9af8c7378c36536e09cae --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pol/PolishClassification.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + + +class CbdClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="CBD", + description="Polish Tweets annotated for cyberbullying detection.", + reference="http://2019.poleval.pl/files/poleval2019.pdf", + dataset={ + "path": "PL-MTEB/cbd", + "revision": "36ddb419bcffe6a5374c3891957912892916f28d", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["pol-Latn"], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 1000}, + avg_character_length={"test": 93.2}, + ) + + +class PolEmo2InClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="PolEmo2.0-IN", + description="A collection of Polish online reviews from four domains: medicine, hotels, products and " + "school. The PolEmo2.0-IN task is to predict the sentiment of in-domain (medicine and hotels) reviews.", + reference="https://aclanthology.org/K19-1092.pdf", + dataset={ + "path": "PL-MTEB/polemo2_in", + "revision": "d90724373c70959f17d2331ad51fb60c71176b03", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["pol-Latn"], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples=None, + avg_character_length=None, + ) + + +class PolEmo2OutClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="PolEmo2.0-OUT", + description="A collection of Polish online reviews from four domains: medicine, hotels, products and " + "school. The PolEmo2.0-OUT task is to predict the sentiment of out-of-domain (products and " + "school) reviews using models train on reviews from medicine and hotels domains.", + reference="https://aclanthology.org/K19-1092.pdf", + dataset={ + "path": "PL-MTEB/polemo2_out", + "revision": "6a21ab8716e255ab1867265f8b396105e8aa63d4", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["pol-Latn"], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 722}, + avg_character_length={"test": 756.2}, + ) + + +class AllegroReviewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="AllegroReviews", + description="A Polish dataset for sentiment classification on reviews from e-commerce marketplace Allegro.", + reference="https://aclanthology.org/2020.acl-main.111.pdf", + dataset={ + "path": "PL-MTEB/allegro-reviews", + "revision": "b89853e6de927b0e3bfa8ecc0e56fe4e02ceafc6", + }, + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["pol-Latn"], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 1006}, + avg_character_length={"test": 477.2}, + ) + + +class PacClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="PAC", + description="Polish Paraphrase Corpus", + reference="https://arxiv.org/pdf/2211.13112.pdf", + dataset={ + "path": "laugustyniak/abusive-clauses-pl", + "revision": "fc69d1c153a8ccdcf1eef52f4e2a27f88782f543", + }, + type="Classification", + category="p2p", + eval_splits=["test"], + eval_langs=["pol-Latn"], + main_score="accuracy", + date=None, + form=None, + domains=None, + task_subtypes=None, + license=None, + socioeconomic_status=None, + annotations_creators=None, + dialect=None, + text_creation=None, + bibtex_citation=None, + n_samples={"test": 3453}, + avg_character_length={"test": 185.3}, + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pol/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/pol/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/por/HateSpeechPortugueseClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/por/HateSpeechPortugueseClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..047e3ba60e9287e357f3b7f8bc1513d87c46a215 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/por/HateSpeechPortugueseClassification.py @@ -0,0 +1,60 @@ +from __future__ import annotations + +from mteb.abstasks.TaskMetadata import TaskMetadata + +from ....abstasks import AbsTaskClassification + + +class HateSpeechPortugueseClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="HateSpeechPortugueseClassification", + description="HateSpeechPortugueseClassification is a dataset of Portuguese tweets categorized with their sentiment (2 classes).", + reference="https://aclanthology.org/W19-3510", + dataset={ + "path": "hate_speech_portuguese", + "revision": "b0f431acbf8d3865cb7c7b3effb2a9771a618ebc", + }, + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["por-Latn"], + main_score="accuracy", + date=("2017-03-08", "2017-03-09"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="expert-annotated", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{fortuna-etal-2019-hierarchically, + title = "A Hierarchically-Labeled {P}ortuguese Hate Speech Dataset", + author = "Fortuna, Paula and + Rocha da Silva, Jo{\~a}o and + Soler-Company, Juan and + Wanner, Leo and + Nunes, S{\'e}rgio", + editor = "Roberts, Sarah T. and + Tetreault, Joel and + Prabhakaran, Vinodkumar and + Waseem, Zeerak", + booktitle = "Proceedings of the Third Workshop on Abusive Language Online", + month = aug, + year = "2019", + address = "Florence, Italy", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/W19-3510", + doi = "10.18653/v1/W19-3510", + pages = "94--104", + } + """, + n_samples={"train": 2048}, + avg_character_length={"train": 101.02}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/Moroco.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/Moroco.py new file mode 100644 index 0000000000000000000000000000000000000000..e87168963b285e6b0d4428f3779316a6d5a9496f --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/Moroco.py @@ -0,0 +1,50 @@ +from mteb.abstasks import AbsTaskClassification # type: ignore +from mteb.abstasks.TaskMetadata import TaskMetadata # type: ignore + + +class Moroco(AbsTaskClassification): + metadata = TaskMetadata( + name="Moroco", + dataset={ + "path": "universityofbucharest/moroco", + "revision": "d64d9b8cd876056a5c24552afe3caf7e6fd26c8e", + }, + description="The Moldavian and Romanian Dialectal Corpus. The MOROCO data set contains Moldavian and Romanian samples of text collected from the news domain. The samples belong to one of the following six topics: (0) culture, (1) finance, (2) politics, (3) science, (4) sports, (5) tech", + reference="https://huggingface.co/datasets/moroco", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["ron-Latn"], + main_score="accuracy", + date=("2017-10-01", "2017-10-31"), + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="CC BY-4.0", + socioeconomic_status="medium", + annotations_creators="derived", + dialect=[ + "ron-Latn-ron", + "ron-Latn-mol", + ], # Moldavian, or the Romanian dialect used in Moldova, does not have an ISO 639-1 code assigned to it. However, it has been given the three-letter code "mol" under ISO 639-3 + text_creation="found", + bibtex_citation="""" + @inproceedings{ Butnaru-ACL-2019, + author = {Andrei M. Butnaru and Radu Tudor Ionescu}, + title = "{MOROCO: The Moldavian and Romanian Dialectal Corpus}", + booktitle = {Proceedings of ACL}, + year = {2019}, + pages={688--698}, + } + """, + n_samples={"test": 2048}, + avg_character_length={"test": 1710.94}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns( + {"sample": "text", "category": "label"} + ).remove_columns(["id"]) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/RomanianSentimentClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/RomanianSentimentClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..12bc588d2499cc839a96b007fc0038900c73b0fc --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/RomanianSentimentClassification.py @@ -0,0 +1,47 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + +TEST_SAMPLES = 2048 + + +class RomanianSentimentClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="RomanianSentimentClassification", + description="An Romanian dataset for sentiment classification.", + reference="https://arxiv.org/abs/2009.08712", + dataset={ + "path": "dumitrescustefan/ro_sent", + "revision": "155048684cea7a6d6af1ddbfeb9a04820311ce93", + }, + type="Classification", + category="s2s", + date=("2020-09-18", "2020-09-18"), + eval_splits=["test"], + eval_langs=["ron-Latn"], + main_score="accuracy", + form=["written"], + domains=["Reviews"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="mixed", + annotations_creators="human-annotated", + dialect=[], + text_creation="found", + bibtex_citation="""@article{dumitrescu2020birth, + title={The birth of Romanian BERT}, + author={Dumitrescu, Stefan Daniel and Avram, Andrei-Marius and Pyysalo, Sampo}, + journal={arXiv preprint arXiv:2009.08712}, + year={2020} +} +""", + n_samples={"test": TEST_SAMPLES}, + avg_character_length={"test": 67.6}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("sentence", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/ron/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/san/SanskritShlokasClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/san/SanskritShlokasClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..6eba516a4de88146049e1eabefa0e86ae41cccae --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/san/SanskritShlokasClassification.py @@ -0,0 +1,56 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class SanskritShlokasClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="SanskritShlokasClassification", + description="This data set contains ~500 Shlokas ", + reference="https://github.com/goru001/nlp-for-sanskrit", + dataset={ + "path": "bpHigh/iNLTK_Sanskrit_Shlokas_Dataset", + "revision": "5a79d6472db143690c7ce6e974995d3610eee7f0", + }, + type="Classification", + category="s2s", + date=("2019-01-01", "2020-01-01"), + eval_splits=["train", "validation"], + eval_langs=["san-Deva"], + main_score="accuracy", + form=["written"], + domains=["Religious"], + task_subtypes=["Topic classification"], + license="CC BY-SA 4.0", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @inproceedings{arora-2020-inltk, + title = "i{NLTK}: Natural Language Toolkit for Indic Languages", + author = "Arora, Gaurav", + editor = "Park, Eunjeong L. and + Hagiwara, Masato and + Milajevs, Dmitrijs and + Liu, Nelson F. and + Chauhan, Geeticka and + Tan, Liling", + booktitle = "Proceedings of Second Workshop for NLP Open Source Software (NLP-OSS)", + month = nov, + year = "2020", + address = "Online", + publisher = "Association for Computational Linguistics", + url = "https://aclanthology.org/2020.nlposs-1.10", + doi = "10.18653/v1/2020.nlposs-1.10", + pages = "66--71", + abstract = "We present iNLTK, an open-source NLP library consisting of pre-trained language models and out-of-the-box support for Data Augmentation, Textual Similarity, Sentence Embeddings, Word Embeddings, Tokenization and Text Generation in 13 Indic Languages. By using pre-trained models from iNLTK for text classification on publicly available datasets, we significantly outperform previously reported results. On these datasets, we also show that by using pre-trained models and data augmentation from iNLTK, we can achieve more than 95{\%} of the previous best performance by using less than 10{\%} of the training data. iNLTK is already being widely used by the community and has 40,000+ downloads, 600+ stars and 100+ forks on GitHub.", + } + """, + n_samples={"train": 383, "validation": 96}, + avg_character_length={"train": 98.415, "validation": 96.635}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"Sloka": "text", "Class": "label"}) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/sin/SinhalaNewsSourceClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/sin/SinhalaNewsSourceClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..869cfa01510af53a4dfecad84c528dd8cf398829 --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/sin/SinhalaNewsSourceClassification.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class SinhalaNewsSourceClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="SinhalaNewsSourceClassification", + description="This dataset contains Sinhala news headlines extracted from 9 news sources (websites) (Sri Lanka Army, Dinamina, GossipLanka, Hiru, ITN, Lankapuwath, NewsLK, Newsfirst, World Socialist Web Site-Sinhala).", + dataset={ + "path": "NLPC-UOM/Sinhala-News-Source-classification", + "revision": "ac4d14eeb68efbef95e247542d4432ce674faeb1", + }, + reference="https://huggingface.co/datasets/NLPC-UOM/Sinhala-News-Source-classification", + type="Classification", + category="s2s", + eval_splits=["train"], + eval_langs=["sin-Sinh"], + main_score="accuracy", + date=("2021-02-17", "2022-08-20"), + form=["written"], + domains=["News"], + task_subtypes=["Topic classification"], + license="mit", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + @article{dhananjaya2022, + author = {Dhananjaya et al.}, + title = {BERTifying Sinhala - A Comprehensive Analysis of Pre-trained Language Models for Sinhala Text Classification}, + journal = {Year of Publication}, + year = {2022}, + }""", + n_samples={"train": 24094}, + avg_character_length={"train": 56.08}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_column("comment", "text") + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/sin/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/sin/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/slv/FrenkSlClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/slv/FrenkSlClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..6e08c7cba4e83e073c590cc091640b89ad9cc7ba --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/slv/FrenkSlClassification.py @@ -0,0 +1,46 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class FrenkSlClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="FrenkSlClassification", + description="Slovenian subset of the FRENK dataset. Also available on HuggingFace dataset hub: English subset, Croatian subset.", + dataset={ + "path": "classla/FRENK-hate-sl", + "revision": "37c8b42c63d4eb75f549679158a85eb5bd984caa", + }, + reference="https://arxiv.org/pdf/1906.02045", + type="Classification", + category="s2s", + eval_splits=["test"], + eval_langs=["slv-Latn"], + main_score="accuracy", + date=("2021-05-28", "2021-05-28"), + form=["written"], + domains=["Social"], + task_subtypes=["Sentiment/Hate speech"], + license="Not specified", + socioeconomic_status="low", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation="""@misc{ljubešić2019frenk, + title={The FRENK Datasets of Socially Unacceptable Discourse in Slovene and English}, + author={Nikola Ljubešić and Darja Fišer and Tomaž Erjavec}, + year={2019}, + eprint={1906.02045}, + archivePrefix={arXiv}, + primaryClass={cs.CL}, + url={https://arxiv.org/abs/1906.02045} + }""", + n_samples={"test": 2177}, + avg_character_length={"test": 136.61}, + ) + + def dataset_transform(self): + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["test"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/spa/SpanishNewsClassification.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/spa/SpanishNewsClassification.py new file mode 100644 index 0000000000000000000000000000000000000000..29bf0df39491fa3f2649744a07ea9c680a28098c --- /dev/null +++ b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/spa/SpanishNewsClassification.py @@ -0,0 +1,40 @@ +from __future__ import annotations + +from mteb.abstasks import AbsTaskClassification +from mteb.abstasks.TaskMetadata import TaskMetadata + + +class SpanishNewsClassification(AbsTaskClassification): + metadata = TaskMetadata( + name="SpanishNewsClassification", + description="A Spanish dataset for news classification. The dataset includes articles from reputable Spanish news sources spanning 12 different categories.", + reference="https://huggingface.co/datasets/MarcOrfilaCarreras/spanish-news", + dataset={ + "path": "MarcOrfilaCarreras/spanish-news", + "revision": "0086c197b914690a9dace258a19398890a05299a", + }, + type="Classification", + category="s2s", + date=("2023-05-01", "2024-05-01"), + eval_splits=["train"], + eval_langs=["spa-Latn"], + main_score="accuracy", + form=["written"], + domains=["News"], + task_subtypes=[], + license="MIT", + socioeconomic_status="mixed", + annotations_creators="derived", + dialect=[], + text_creation="found", + bibtex_citation=""" + """, + n_samples={"train": 2048}, + avg_character_length={"train": 4218.2}, + ) + + def dataset_transform(self): + self.dataset = self.dataset.rename_columns({"category": "label"}) + self.dataset = self.stratified_subsampling( + self.dataset, seed=self.seed, splits=["train"] + ) diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/spa/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/spa/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/tel/__init__.py b/testbed/embeddings-benchmark__mteb/mteb/tasks/Classification/tel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391