GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — kafka/.github/scripts/develocity_reports.py at trunk · coderbruis/kafka Expand file tree/ Copy pathdevelocity_reports.pyMore file actions 1300 lines (1091 loc) · 55.1 KB / Copy pathdevelocity_reports.pyFile metadata and controls1300 lines (1091 loc) · 55.1 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 # 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. import os import requests import json from dataclasses import dataclass, field, asdict from typing import Dict, List, Tuple, Optional from datetime import datetime, timedelta import pytz # Add this import for timezone handling from collections import defaultdict import time import logging import concurrent.futures # Add this import at the top import pathlib import pickle from abc import ABC, abstractmethod logger = logging.getLogger(__name__) @dataclass class TestOutcome: passed: int failed: int skipped: int flaky: int not_selected: int = field(metadata={'name': 'notSelected'}) total: int @dataclass class BuildInfo: id: str timestamp: datetime duration: int has_failed: bool @dataclass class TestTimelineEntry: build_id: str timestamp: datetime outcome: str # "passed", "failed", "flaky", etc. @dataclass class TestResult: name: str outcome_distribution: TestOutcome first_seen: datetime timeline: List[TestTimelineEntry] = field(default_factory=list) recent_failure_rate: float = 0.0 # Added to track recent failure trends @dataclass class TestContainerResult: build_id: str outcome: str timestamp: Optional[datetime] = None @dataclass class TestCaseResult(TestResult): """Extends TestResult to include container-specific information""" container_name: str = "" @dataclass class BuildCache: last_update: datetime builds: Dict[str, 'BuildInfo'] def to_dict(self): return { 'last_update': self.last_update.isoformat(), 'builds': {k: asdict(v) for k, v in self.builds.items()} } @classmethod def from_dict(cls, data: dict) -> 'BuildCache': return cls( last_update=datetime.fromisoformat(data['last_update']), builds={k: BuildInfo(**v) for k, v in data['builds'].items()} ) class CacheProvider(ABC): @abstractmethod def get_cache(self) -> Optional[BuildCache]: pass @abstractmethod def save_cache(self, cache: BuildCache): pass class LocalCacheProvider(CacheProvider): def __init__(self, cache_dir: str = None): if cache_dir is None: cache_dir = os.path.join(os.path.expanduser("~"), ".develocity_cache") self.cache_file = os.path.join(cache_dir, "build_cache.pkl") os.makedirs(cache_dir, exist_ok=True) def get_cache(self) -> Optional[BuildCache]: try: if os.path.exists(self.cache_file): with open(self.cache_file, 'rb') as f: return pickle.load(f) except Exception as e: logger.warning(f"Failed to load local cache: {e}") return None def save_cache(self, cache: BuildCache): try: with open(self.cache_file, 'wb') as f: pickle.dump(cache, f) except Exception as e: logger.warning(f"Failed to save local cache: {e}") class GitHubActionsCacheProvider(CacheProvider): def __init__(self): self.cache_key = "develocity-build-cache" def get_cache(self) -> Optional[BuildCache]: try: # Check if running in GitHub Actions if not os.environ.get('GITHUB_ACTIONS'): return None cache_path = os.environ.get('GITHUB_WORKSPACE', '') cache_file = os.path.join(cache_path, self.cache_key + '.json') if os.path.exists(cache_file): with open(cache_file, 'r') as f: data = json.load(f) return BuildCache.from_dict(data) except Exception as e: logger.warning(f"Failed to load GitHub Actions cache: {e}") return None def save_cache(self, cache: BuildCache): try: if not os.environ.get('GITHUB_ACTIONS'): return cache_path = os.environ.get('GITHUB_WORKSPACE', '') cache_file = os.path.join(cache_path, self.cache_key + '.json') with open(cache_file, 'w') as f: json.dump(cache.to_dict(), f) except Exception as e: logger.warning(f"Failed to save GitHub Actions cache: {e}") class TestAnalyzer: def __init__(self, base_url: str, auth_token: str): self.base_url = base_url self.headers = { 'Authorization': f'Bearer {auth_token}', 'Accept': 'application/json' } self.default_chunk_size = timedelta(days=14) self.api_retry_delay = 2 # seconds self.max_api_retries = 3 # Initialize cache providers self.cache_providers = [ GitHubActionsCacheProvider(), LocalCacheProvider() ] self.build_cache = None self._load_cache() def _load_cache(self): """Load cache from the first available provider""" for provider in self.cache_providers: cache = provider.get_cache() if cache is not None: self.build_cache = cache logger.info(f"Loaded cache from {provider.__class__.__name__}") return logger.info("No existing cache found") def _save_cache(self): """Save cache to all providers""" if self.build_cache: for provider in self.cache_providers: provider.save_cache(self.build_cache) logger.info(f"Saved cache to {provider.__class__.__name__}") def build_query( self, project: str, chunk_start: datetime, chunk_end: datetime, test_tags: List[str] ) -> str: """ Constructs the query string to be used in both build info and test containers API calls. Args: project: The project name. chunk_start: The start datetime for the chunk. chunk_end: The end datetime for the chunk. test_tags: A list of tags to include. Returns: A formatted query string. """ test_tags.append("+github") tags = [] for tag in test_tags: if tag.startswith("+"): tags.append(f"tag:{tag[1:]}") elif tag.startswith("-"): tags.append(f"-tag:{tag[1:]}") else: raise ValueError("Tag should include + or - to indicate inclusion or exclusion.") tags = " ".join(tags) return f"project:{project} buildStartTime:[{chunk_start.isoformat()} TO {chunk_end.isoformat()}] gradle.requestedTasks:test {tags}" def process_chunk( self, chunk_start: datetime, chunk_end: datetime, project: str, test_tags: List[str], remaining_build_ids: set | None, max_builds_per_request: int ) -> Dict[str, BuildInfo]: """Helper method to process a single chunk of build information""" chunk_builds = {} # Use the helper method to build the query query = self.build_query(project, chunk_start, chunk_end, test_tags) # Initialize pagination for this chunk from_build = None continue_chunk = True while continue_chunk and (remaining_build_ids is None or remaining_build_ids): query_params = { 'query': query, 'models': ['gradle-attributes'], 'allModels': 'false', 'maxBuilds': max_builds_per_request, 'reverse': 'false', 'fromInstant': int(chunk_start.timestamp() * 1000) } if from_build: query_params['fromBuild'] = from_build for attempt in range(self.max_api_retries): try: response = requests.get( f'{self.base_url}/api/builds', headers=self.headers, params=query_params, timeout=(5, 30) ) response.raise_for_status() break except requests.exceptions.Timeout: if attempt == self.max_api_retries - 1: raise time.sleep(self.api_retry_delay * (attempt + 1)) except requests.exceptions.RequestException: raise response_json = response.json() if not response_json: break for build in response_json: build_id = build['id'] if 'models' in build and 'gradleAttributes' in build['models']: gradle_attrs = build['models']['gradleAttributes'] if 'model' in gradle_attrs: attrs = gradle_attrs['model'] build_timestamp = datetime.fromtimestamp(attrs['buildStartTime'] / 1000, pytz.UTC) if build_timestamp >= chunk_end: continue_chunk = False break if remaining_build_ids is None or build_id in remaining_build_ids: if 'problem' not in gradle_attrs: chunk_builds[build_id] = BuildInfo( id=build_id, timestamp=build_timestamp, duration=attrs.get('buildDuration'), has_failed=attrs.get('hasFailed', False) ) if remaining_build_ids is not None: remaining_build_ids.remove(build_id) if continue_chunk and response_json: from_build = response_json[-1]['id'] else: continue_chunk = False time.sleep(0.5) # Rate limiting between pagination requests return chunk_builds def get_build_info( self, build_ids: List[str] = None, project: str = None, test_tags: List[str] = None, query_days: int = None, bypass_cache: bool = False, fetch_all: bool = False ) -> Dict[str, BuildInfo]: builds = {} max_builds_per_request = 100 cutoff_date = datetime.now(pytz.UTC) - timedelta(days=query_days) current_time = datetime.now(pytz.UTC) if not fetch_all and not build_ids: raise ValueError(f"Either build_ids must be provided or fetch_all must be True: {build_ids} {fetch_all}") # Get builds from cache if available and bypass_cache is False if not bypass_cache and self.build_cache: cached_builds = self.build_cache.builds cached_cutoff = self.build_cache.last_update - timedelta(days=query_days) if fetch_all: # Use all cached builds within the time period for build_id, build in cached_builds.items(): if build.timestamp >= cached_cutoff: builds[build_id] = build else: # Use cached data for specific builds within the cache period for build_id in build_ids: if build_id in cached_builds: build = cached_builds[build_id] if build.timestamp >= cached_cutoff: builds[build_id] = build # Update cutoff date to only fetch new data cutoff_date = self.build_cache.last_update logger.info(f"Using cached data up to {cutoff_date.isoformat()}") if not fetch_all: # Remove already found builds from the search list build_ids = [bid for bid in build_ids if bid not in builds] if not build_ids: logger.info("All builds found in cache") return builds # Fetch remaining builds from API remaining_build_ids = set(build_ids) if not fetch_all else None chunk_size = self.default_chunk_size # Create time chunks chunks = [] chunk_start = cutoff_date while chunk_start < current_time: chunk_end = min(chunk_start + chunk_size, current_time) chunks.append((chunk_start, chunk_end)) chunk_start = chunk_end total_start_time = time.time() # Process chunks in parallel with concurrent.futures.ThreadPoolExecutor(max_workers=10) as executor: future_to_chunk = { executor.submit( self.process_chunk, chunk[0], chunk[1], project, test_tags, remaining_build_ids.copy() if remaining_build_ids else None, max_builds_per_request ): chunk for chunk in chunks } for future in concurrent.futures.as_completed(future_to_chunk): try: chunk_builds = future.result() builds.update(chunk_builds) if remaining_build_ids: remaining_build_ids -= set(chunk_builds.keys()) except Exception as e: logger.error(f"Chunk processing generated an exception: {str(e)}") total_duration = time.time() - total_start_time logger.info( f"\nBuild Info Performance:" f"\n Total Duration: {total_duration:.2f}s" f"\n Builds Retrieved: {len(builds)}" f"\n Builds Not Found: {len(remaining_build_ids) if remaining_build_ids else 0}" ) # Update cache with new data if not bypassing cache if builds and not bypass_cache: if not self.build_cache: self.build_cache = BuildCache(current_time, {}) self.build_cache.builds.update(builds) self.build_cache.last_update = current_time self._save_cache() return builds def get_test_results( self, project: str, threshold_days: int, test_tags: List[str], outcomes: List[str] = None ) -> List[TestResult]: """Fetch test results with timeline information""" if outcomes is None: outcomes = ["failed", "flaky"] logger.debug(f"Fetching test results for project {project}, last {threshold_days} days") end_time = datetime.now(pytz.UTC) start_time = end_time - timedelta(days=threshold_days) all_results = {} build_ids = set() test_container_results = defaultdict(list) chunk_size = self.default_chunk_size chunk_start = start_time while chunk_start < end_time: chunk_end = min(chunk_start + chunk_size, end_time) logger.debug(f"Processing chunk: {chunk_start} to {chunk_end}") # Use the helper method to build the query query = self.build_query(project, chunk_start, chunk_end, test_tags) query_params = { 'query': query, 'testOutcomes': outcomes, 'container': '*', 'include': ['buildScanIds'] # Explicitly request build scan IDs } response = requests.get( f'{self.base_url}/api/tests/containers', headers=self.headers, params=query_params ) response.raise_for_status() for test in response.json()['content']: test_name = test['name'] logger.debug(f"Processing test: {test_name}") if test_name not in all_results: outcome_data = test['outcomeDistribution'] if 'notSelected' in outcome_data: outcome_data['not_selected'] = outcome_data.pop('notSelected') outcome = TestOutcome(**outcome_data) all_results[test_name] = TestResult(test_name, outcome, chunk_start) # Collect build IDs by outcome if 'buildScanIdsByOutcome' in test: scan_ids = test['buildScanIdsByOutcome'] for outcome, ids in scan_ids.items(): if ids: # Only process if we have IDs for build_id in ids: build_ids.add(build_id) test_container_results[test_name].append( TestContainerResult(build_id=build_id, outcome=outcome) ) chunk_start = chunk_end logger.debug(f"Total unique build IDs collected: {len(build_ids)}") # Fetch build information using the updated get_build_info method print(build_ids) print(list(build_ids)) builds = self.get_build_info(list(build_ids), project, test_tags, threshold_days) logger.debug(f"Retrieved {len(builds)} builds from API") logger.debug(f"Retrieved build IDs: {sorted(builds.keys())}") # Update test results with timeline information for test_name, result in all_results.items(): logger.debug(f"\nProcessing timeline for test: {test_name}") timeline = [] for container_result in test_container_results[test_name]: logger.debug(f"Processing container result: {container_result}") if container_result.build_id in builds: build_info = builds[container_result.build_id] timeline.append(TestTimelineEntry( build_id=container_result.build_id, timestamp=build_info.timestamp, outcome=container_result.outcome )) else: logger.warning(f"Build ID {container_result.build_id} not found in builds response") # Sort timeline by timestamp result.timeline = sorted(timeline, key=lambda x: x.timestamp) logger.debug(f"Final timeline entries for {test_name}: {len(result.timeline)}") # Print build details for debugging logger.debug("Timeline entries:") for entry in timeline: logger.debug(f"Build ID: {entry.build_id}, Timestamp: {entry.timestamp}, Outcome: {entry.outcome}") # Calculate recent failure rate recent_cutoff = datetime.now(pytz.UTC) - timedelta(days=30) recent_runs = [t for t in timeline if t.timestamp >= recent_cutoff] if recent_runs: recent_failures = sum(1 for t in recent_runs if t.outcome in ('failed', 'flaky')) result.recent_failure_rate = recent_failures / len(recent_runs) return list(all_results.values()) def get_defective_tests(self, results: List[TestResult]) -> Dict[str, TestResult]: """ Analyze test results to find defective tests (failed or flaky) """ defective_tests = {} for result in results: if result.outcome_distribution.failed > 0 or result.outcome_distribution.flaky > 0: defective_tests[result.name] = result return defective_tests def get_long_quarantined_tests(self, results: List[TestResult], quarantine_threshold_days: int = 60) -> Dict[str, TestResult]: """ Find tests that have been quarantined longer than the threshold. These are candidates for removal or rewriting. Args: results: List of test results quarantine_threshold_days: Number of days after which a quarantined test should be considered for removal/rewrite """ long_quarantined = {} current_time = datetime.now(pytz.UTC) for result in results: days_quarantined = (current_time - result.first_seen).days if days_quarantined >= quarantine_threshold_days: long_quarantined[result.name] = (result, days_quarantined) return long_quarantined def get_problematic_quarantined_tests( self, results: List[TestResult], quarantine_threshold_days: int = 60, min_failure_rate: float = 0.3, recent_failure_threshold: float = 0.5 ) -> Dict[str, Dict]: """Enhanced version that includes test case details""" problematic_tests = {} current_time = datetime.now(pytz.UTC) chunk_start = current_time - timedelta(days=7) # Last 7 days for test cases for result in results: days_quarantined = (current_time - result.first_seen).days if days_quarantined >= quarantine_threshold_days: total_runs = result.outcome_distribution.total if total_runs > 0: problem_runs = result.outcome_distribution.failed + result.outcome_distribution.flaky failure_rate = problem_runs / total_runs if failure_rate >= min_failure_rate or result.recent_failure_rate >= recent_failure_threshold: # Get detailed test case information try: test_cases = self.get_test_case_details( result.name, "kafka", chunk_start, current_time, test_tags=["+trunk", "+flaky"] ) problematic_tests[result.name] = { 'container_result': result, 'days_quarantined': days_quarantined, 'failure_rate': failure_rate, 'recent_failure_rate': result.recent_failure_rate, 'test_cases': test_cases } except Exception as e: logger.error(f"Error getting test case details for {result.name}: {str(e)}") return problematic_tests def get_test_case_details( self, container_name: str, project: str, chunk_start: datetime, chunk_end: datetime, test_tags: List[str] ) -> List[TestCaseResult]: """ Fetch detailed test case results for a specific container. Args: container_name: Name of the test container project: The project name chunk_start: Start time for the query chunk_end: End time for the query test_tags: List of tags to query """ # Use the helper method to build the query, similar to get_test_results query = self.build_query(project, chunk_start, chunk_end, test_tags) query_params = { 'query': query, 'testOutcomes': ['failed', 'flaky'], 'container': container_name, 'include': ['buildScanIds'], # Explicitly request build scan IDs 'limit': 1000 } try: response = requests.get( f'{self.base_url}/api/tests/cases', headers=self.headers, params=query_params ) response.raise_for_status() test_cases = [] content = response.json().get('content', []) # Collect all build IDs first build_ids = set() for test in content: if 'buildScanIdsByOutcome' in test: for outcome_type, ids in test['buildScanIdsByOutcome'].items(): build_ids.update(ids) # Get build info for all build IDs builds = self.get_build_info(list(build_ids), project, test_tags, 7) # 7 days for test cases for test in content: outcome_data = test['outcomeDistribution'] if 'notSelected' in outcome_data: outcome_data['not_selected'] = outcome_data.pop('notSelected') outcome = TestOutcome(**outcome_data) test_case = TestCaseResult( name=test['name'], outcome_distribution=outcome, first_seen=chunk_start, container_name=container_name ) # Add build information with proper timestamps if 'buildScanIdsByOutcome' in test: for outcome_type, build_ids in test['buildScanIdsByOutcome'].items(): for build_id in build_ids: if build_id in builds: build_info = builds[build_id] test_case.timeline.append( TestTimelineEntry( build_id=build_id, timestamp=build_info.timestamp, outcome=outcome_type ) ) else: logger.warning(f"Build ID {build_id} not found for test case {test['name']}") # Sort timeline by timestamp test_case.timeline.sort(key=lambda x: x.timestamp) test_cases.append(test_case) return test_cases except requests.exceptions.RequestException as e: logger.error(f"Error fetching test case details for {container_name}: {str(e)}") raise def get_flaky_test_regressions(self, project: str, results: List[TestResult], recent_days: int = 7, min_flaky_rate: float = 0.2) -> Dict[str, Dict]: """ Identify tests that have recently started showing flaky behavior. Args: project: The project name results: List of test results recent_days: Number of days to consider for recent behavior min_flaky_rate: Minimum flaky rate to consider a test as problematic """ flaky_regressions = {} current_time = datetime.now(pytz.UTC) recent_cutoff = current_time - timedelta(days=recent_days) for result in results: # Skip tests with no timeline data if not result.timeline: continue # Split timeline into recent and historical periods recent_entries = [t for t in result.timeline if t.timestamp >= recent_cutoff] historical_entries = [t for t in result.timeline if t.timestamp < recent_cutoff] if not recent_entries or not historical_entries: continue # Calculate flaky rates recent_flaky = sum(1 for t in recent_entries if t.outcome == 'flaky') recent_total = len(recent_entries) recent_flaky_rate = recent_flaky / recent_total if recent_total > 0 else 0 historical_flaky = sum(1 for t in historical_entries if t.outcome == 'flaky') historical_total = len(historical_entries) historical_flaky_rate = historical_flaky / historical_total if historical_total > 0 else 0 # Check if there's a significant increase in flakiness if recent_flaky_rate >= min_flaky_rate and recent_flaky_rate > historical_flaky_rate * 1.5: flaky_regressions[result.name] = { 'result': result, 'recent_flaky_rate': recent_flaky_rate, 'historical_flaky_rate': historical_flaky_rate, 'recent_executions': recent_entries, 'historical_executions': historical_entries } return flaky_regressions def get_cleared_tests(self, project: str, results: List[TestResult], success_threshold: float = 0.7, min_executions: int = 5) -> Dict[str, Dict]: """ Identify quarantined tests that are consistently passing and could be cleared. Args: project: The project name results: List of test results success_threshold: Required percentage of successful builds to be considered cleared min_executions: Minimum number of executions required to make a determination """ cleared_tests = {} current_time = datetime.now(pytz.UTC) chunk_start = current_time - timedelta(days=7) # Last 7 days for test cases for result in results: # Only consider tests with sufficient recent executions recent_executions = result.timeline if len(recent_executions) < min_executions: continue # Calculate success rate at class level successful_runs = sum(1 for t in recent_executions if t.outcome == 'passed') success_rate = successful_runs / len(recent_executions) # Check if the test meets clearing criteria at class level if success_rate >= success_threshold: # Verify no recent failures or flaky behavior has_recent_issues = any(t.outcome in ['failed', 'flaky'] for t in recent_executions[-min_executions:]) if not has_recent_issues: try: # Get test case details test_cases = self.get_test_case_details( result.name, project, chunk_start, current_time, test_tags=["+trunk", "+flaky"] ) # Only include if all test cases are also passing consistently all_cases_passing = True passing_test_cases = [] for test_case in test_cases: case_total = test_case.outcome_distribution.total if case_total >= min_executions: case_success_rate = test_case.outcome_distribution.passed / case_total # Check recent executions for the test case recent_case_issues = any(t.outcome in ['failed', 'flaky'] for t in test_case.timeline[-min_executions:]) if case_success_rate >= success_threshold and not recent_case_issues: passing_test_cases.append({ 'name': test_case.name, 'success_rate': case_success_rate, 'total_executions': case_total, 'recent_executions': sorted(test_case.timeline, key=lambda x: x.timestamp)[-min_executions:] }) else: all_cases_passing = False break if all_cases_passing and passing_test_cases: cleared_tests[result.name] = { 'result': result, 'success_rate': success_rate, 'total_executions': len(recent_executions), 'successful_runs': successful_runs, 'recent_executions': recent_executions[-min_executions:], 'test_cases': passing_test_cases } except Exception as e: logger.error(f"Error getting test case details for {result.name}: {str(e)}") return cleared_tests def update_cache(self, builds: Dict[str, BuildInfo]): """ Update the build cache with new build information. Args: builds: Dictionary of build IDs to BuildInfo objects """ current_time = datetime.now(pytz.UTC) # Initialize cache if it doesn't exist if not self.build_cache: self.build_cache = BuildCache(current_time, {}) # Update builds and last update time self.build_cache.builds.update(builds) self.build_cache.last_update = current_time # Save to all cache providers self._save_cache() logger.info(f"Updated cache with {len(builds)} builds") def get_persistent_failing_tests(self, results: List[TestResult], min_failure_rate: float = 0.2, min_executions: int = 5) -> Dict[str, Dict]: """ Identify tests that have been consistently failing/flaky over time. Groups by test class and includes individual test cases. """ persistent_failures = {} current_time = datetime.now(pytz.UTC) chunk_start = current_time - timedelta(days=7) # Last 7 days for test cases # Group results by class class_groups = {} for result in results: class_name = result.name.split('#')[0] # Get class name if class_name not in class_groups: class_groups[class_name] = [] class_groups[class_name].append(result) # Analyze each class and its test cases for class_name, class_results in class_groups.items(): class_total = sum(r.outcome_distribution.total for r in class_results) class_problems = sum(r.outcome_distribution.failed + r.outcome_distribution.flaky for r in class_results) if class_total < min_executions: continue class_failure_rate = class_problems / class_total if class_total > 0 else 0 # Only include if class has significant failures if class_failure_rate >= min_failure_rate: try: # Get detailed test case information using the same method as other reports test_cases = self.get_test_case_details( class_name, "kafka", chunk_start, current_time, test_tags=["+trunk", "-flaky"] ) failing_test_cases = {} for test_case in test_cases: total_runs = test_case.outcome_distribution.total if total_runs >= min_executions: problem_runs = (test_case.outcome_distribution.failed + test_case.outcome_distribution.flaky) failure_rate = problem_runs / total_runs if total_runs > 0 else 0 if failure_rate >= min_failure_rate: # Extract just the method name method_name = test_case.name.split('.')[-1] failing_test_cases[method_name] = { 'result': test_case, 'failure_rate': failure_rate, 'total_executions': total_runs, 'failed_executions': problem_runs, 'timeline': sorted(test_case.timeline, key=lambda x: x.timestamp) } if failing_test_cases: # Only include classes that have problematic test cases persistent_failures[class_name] = { 'failure_rate': class_failure_rate, 'total_executions': class_total, 'failed_executions': class_problems, 'test_cases': failing_test_cases } except Exception as e: logger.error(f"Error getting test case details for {class_name}: {str(e)}") return persistent_failures def get_develocity_class_link(class_name: str, threshold_days: int) -> str: """ Generate Develocity link for a test class Args: class_name: Name of the test class threshold_days: Number of days to look back in search """ base_url = "https://develocity.apache.org/scans/tests" params = { "search.rootProjectNames": "kafka", "search.tags": "github,trunk", "search.timeZoneId": "UTC", "search.relativeStartTime": f"P{threshold_days}D", "tests.container": class_name, "search.tasks": "test" } return f"{base_url}?{'&'.join(f'{k}={requests.utils.quote(str(v))}' for k, v in params.items())}" def get_develocity_method_link(class_name: str, method_name: str, threshold_days: int) -> str: """ Generate Develocity link for a test method Args: class_name: Name of the test class method_name: Name of the test method threshold_days: Number of days to look back in search """ base_url = "https://develocity.apache.org/scans/tests" # Extract just the method name without the class prefix if '.' in method_name: method_name = method_name.split('.')[-1] params = { "search.rootProjectNames": "kafka", "search.tags": "github,trunk", "search.timeZoneId": "UTC", "search.relativeStartTime": f"P{threshold_days}D", "tests.container": class_name, "tests.test": method_name, "search.tasks": "test" } return f"{base_url}?{'&'.join(f'{k}={requests.utils.quote(str(v))}' for k, v in params.items())}" def print_most_problematic_tests(problematic_tests: Dict[str, Dict], threshold_days: int): """Print a summary of the most problematic tests""" print("\n## Most Problematic Tests") if not problematic_tests: print("No high-priority problematic tests found.") return print(f"Found {len(problematic_tests)} tests that have been quarantined for {threshold_days} days and are still failing frequently.") # Print table with class and method information print("\n<table>") print("<tr><td>Class</td><td>Test Case</td><td>Failure Rate</td><td>Build Scans</td><td>Link</td></tr>") for test_name, details in sorted(problematic_tests.items(), key=lambda x: x[1]['failure_rate'], reverse=True): class_link = get_develocity_class_link(test_name, threshold_days) print(f"<tr><td colspan=\"4\">{test_name}</td><td><a href=\"{class_link}\">↗️</a></td></tr>") for test_case in sorted(details['test_cases'], key=lambda x: (x.outcome_distribution.failed + x.outcome_distribution.flaky) / x.outcome_distribution.total if x.outcome_distribution.total > 0 else 0, reverse=True): method_name = test_case.name.split('.')[-1] if method_name != 'N/A': method_link = get_develocity_method_link(test_name, test_case.name, threshold_days) total_runs = test_case.outcome_distribution.total failure_rate = (test_case.outcome_distribution.failed + test_case.outcome_distribution.flaky) / total_runs if total_runs > 0 else 0 print(f"<tr><td></td><td>{method_name}</td>" f"<td>{failure_rate:.2%}</td><td>{total_runs}</td>" f"<td><a href=\"{method_link}\">↗️</a></td></tr>") print("</table>") # Print detailed execution history print("\n<details>") |
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |