Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions codecarbon/output_methods/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,23 +49,28 @@ def __init__(
):
self.endpoint_url: str = endpoint_url
self.api = ApiClient(
experiment_id=experiment_id,
endpoint_url=endpoint_url,
experiment_id=experiment_id,
api_key=api_key,
conf=conf,
create_run_automatically=False,
)
self.run_id = self.api.run_id

def live_out(self, _, delta: EmissionsData):
# Called at regular intervals
def _ensure_api_run(self) -> None:
if self.api.run_id is None and self.api.experiment_id is not None:
self.api._create_run(self.api.experiment_id)
self.run_id = self.api.run_id

def _emit(self, delta: EmissionsData) -> None:
try:
self._ensure_api_run()
self.api.add_emission(dataclasses.asdict(delta))
except Exception as e:
logger.error(e, exc_info=True)

def live_out(self, _, delta: EmissionsData):
self._emit(delta)

def out(self, _, delta: EmissionsData):
# Called on exit
try:
self.api.add_emission(dataclasses.asdict(delta))
except Exception as e:
logger.error(e, exc_info=True)
self._emit(delta)
39 changes: 39 additions & 0 deletions tests/output_methods/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,45 @@ def test_codecarbon_api_live_out(self):
api_output.live_out(None, self.emissions_data)
self.mock_add_emission.assert_called_once()

def test_codecarbon_api_live_out_creates_run_when_missing(self):
conf = {
"os": "linux",
"python_version": "3.12",
"codecarbon_version": "2.0",
"cpu_count": 4,
"cpu_model": "CPU",
"gpu_count": 0,
"gpu_model": "",
"longitude": 0.0,
"latitude": 0.0,
"region": "EU",
"provider": "AWS",
"ram_total_size": 16.0,
"tracking_mode": "machine",
}

with patch(
"codecarbon.output_methods.http.ApiClient._create_run"
) as mock_create_run:
api_output = CodeCarbonAPIOutput(
endpoint_url="http://test.com",
experiment_id="exp-1",
api_key=self.api_key,
conf=conf,
)
api_output.api.run_id = None

def create_run(experiment_id):
api_output.api.run_id = "run-created"
return "run-created"

mock_create_run.side_effect = create_run
api_output.live_out(None, self.emissions_data)

mock_create_run.assert_called_once_with("exp-1")
self.assertEqual(api_output.api.run_id, "run-created")
self.assertEqual(api_output.run_id, "run-created")

@patch("codecarbon.output_methods.http.logger.error")
def test_codecarbon_live_out_api_call_failure(self, mock_logger):
self.mock_add_emission.side_effect = Exception("Test exception")
Expand Down
Loading