Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import argparse
import datetime
import logging
import os
import pathlib
import sys
import time
Expand Down Expand Up @@ -89,7 +90,8 @@ def handle_job_update(db, db_cursor, job_id, no_progress_reporting):
break # Done
if CompressionJobStatus.FAILED == job_status:
# One or more tasks in the job has failed
logger.error(f"Compression failed. {job_row['status_msg']}")
expanded_msg = os.path.expandvars(job_row["status_msg"])
logger.error(f"Compression failed. {expanded_msg}")
break # Done
if CompressionJobStatus.KILLED == job_status:
# The job is killed
Expand Down Expand Up @@ -242,6 +244,7 @@ def main(argv):
clp_config.validate_logs_input_config()
clp_config.validate_logs_dir()
clp_config.database.load_credentials_from_env()
os.environ["CLP_LOGS_DIR"] = str(clp_config.logs_directory)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that the CLP_LOGS_DIR environment variable has already been set in the compression worker container in

CLP_LOGS_DIR: "/var/log/compression_worker"
.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

not sure why, but when I remove this line, the "CLP_LOGS_DIR" in the path stored in status_msg can't be expanded with os.path.expandvars(), and we get

Compression failed. One or more compression tasks failed. See ${CLP_LOGS_DIR}/user/failed_compression_log_3.txt for more details.

as our ERROR output. any thoughts as to why that might be happening?

except:
logger.exception("Failed to load config.")
return -1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -180,23 +180,57 @@ def _process_s3_input(
paths_to_compress_buffer.add_file(object_metadata)


def _write_failed_compression_log(
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
status_msg: str, logs_directory: Path, job_id: Any
) -> Optional[Path]:
"""
Writes status_msg to a new log file located at
`{logs_directory}/user/failed_compression_log_{job_id}.txt`. The /user directory will be created
if it doesn't already exist.
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
:param status_msg:
:param logs_directory:
:param job_id:
:return: Path to the written log file relative to {logs_directory}, or `None` on error.
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
"""

user_logs_dir = Path(logs_directory) / "user"
try:
user_logs_dir.mkdir(parents=True, exist_ok=True)
except Exception as e:
logger.warning(f"Failed to create user logs directory: {e}")
return None

log_path = user_logs_dir / f"failed_compression_log_{job_id}.txt"
try:
with log_path.open("w", encoding="utf-8") as f:
timestamp = datetime.datetime.now().isoformat(timespec="seconds")
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
f.write(f"Failed compression job log.\nGenerated at {timestamp}.\n\n")
f.write(f"{status_msg.rstrip()}\n")
except Exception as e:
logger.warning(f"Failed to write compression failure log: {e}")
return None

return Path("user") / f"failed_compression_log_{job_id}.txt"

Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved

def _write_failed_path_log(
invalid_path_messages: List[str], logs_directory: Path, job_id: Any
) -> Optional[Path]:
"""
Writes the error messages in `invalid_path_messages` to a log file,
`{logs_directory}/user/failed_paths_{job_id}.txt`. The directory will be created if it doesn't
already exist.
Writes the error messages in `invalid_path_messages` to a new log file located at
`{logs_directory}/user/failed_paths_{job_id}.txt`. The /user directory will be created if it
doesn't already exist.
:param invalid_path_messages:
:param logs_directory:
:param job_id:
:return: Path to the written log file or `None` if error is encountered.
:return: Path to the written log file relative to {logs_directory}, or `None` on error.
"""
Comment on lines +183 to 201

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Narrow job_id type; align with lint and intent.

job_id: Any trips ANN401 and weakens the API. Use an integer.

 def _write_user_failure_log(
-    content: List[str],
-    logs_directory: Path,
-    job_id: Any,
+    content: List[str],
+    logs_directory: Path,
+    job_id: int,
     filename_suffix: str,
     title: str,
 ) -> Optional[Path]:
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _write_user_failure_log(
content: List[str],
logs_directory: Path,
job_id: Any,
filename_suffix: str,
title: str,
) -> Optional[Path]:
"""
Writes the error messages in `invalid_path_messages` to a log file,
`{logs_directory}/user/failed_paths_{job_id}.txt`. The directory will be created if it doesn't
already exist.
:param invalid_path_messages:
Writes a user-oriented failure log to
`{logs_directory}/user/job_{job_id}_{filename_suffix}.txt`. The `{logs_directory}/user`
directory will be created if it does not already exist.
:param content:
:param logs_directory:
:param job_id:
:return: Path to the written log file or `None` if error is encountered.
:param filename_suffix:
:param title:
:return: Path to the written log file relative to `logs_directory`, or `None` on error.
"""
def _write_user_failure_log(
content: List[str],
logs_directory: Path,
job_id: int,
filename_suffix: str,
title: str,
) -> Optional[Path]:
"""
Writes a user-oriented failure log to
`{logs_directory}/user/job_{job_id}_{filename_suffix}.txt`. The `{logs_directory}/user`
directory will be created if it does not already exist.
:param content:
:param logs_directory:
:param job_id:
:param filename_suffix:
:param title:
:return: Path to the written log file relative to `logs_directory`, or `None` on error.
"""
🧰 Tools
🪛 Ruff (0.14.2)

186-186: Dynamically typed expressions (typing.Any) are disallowed in job_id

(ANN401)

🤖 Prompt for AI Agents
In
components/job-orchestration/job_orchestration/scheduler/compress/compression_scheduler.py
around lines 183 to 201, change the job_id parameter's type from Any to int to
satisfy ANN401 and reflect intent; update the function signature to job_id: int,
adjust any internal code that formats or concatenates job_id (use str(job_id) or
f-strings) if necessary, and update the docstring/type hints accordingly so the
API and typing are consistent.


user_logs_dir = Path(logs_directory) / "user"
try:
user_logs_dir.mkdir(parents=True, exist_ok=True)
except Exception:
except Exception as e:
logger.warning(f"Failed to create user logs directory: {e}")
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
return None

log_path = user_logs_dir / f"failed_paths_{job_id}.txt"
Expand All @@ -206,10 +240,11 @@ def _write_failed_path_log(
f.write(f"Failed input paths log.\nGenerated at {timestamp}.\n\n")
for msg in invalid_path_messages:
f.write(f"{msg.rstrip()}\n")
except Exception:
except Exception as e:
logger.warning(f"Failed to write invalid path log: {e}")
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
return None

return log_path
return Path("user") / f"failed_paths_{job_id}.txt"
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved


def search_and_schedule_new_tasks(
Expand Down Expand Up @@ -274,18 +309,18 @@ def search_and_schedule_new_tasks(
if input_type == InputType.FS.value:
invalid_path_messages = _process_fs_input_paths(input_config, paths_to_compress_buffer)
if len(invalid_path_messages) > 0:
base_msg = "At least one of your input paths could not be processed."

user_log_path = _write_failed_path_log(
user_log_relative_path = _write_failed_path_log(
invalid_path_messages, clp_config.logs_directory, job_id
)
if user_log_path is None:
error_msg = base_msg + (
f" Check the compression scheduler logs in {clp_config.logs_directory} for"
" more details."
)
if user_log_relative_path is None:
macro_path = "${CLP_LOGS_DIR}/compression_scheduler/compression_scheduler.log"
else:
error_msg = base_msg + f" Check {user_log_path} for more details."
macro_path = f"${{CLP_LOGS_DIR}}/{user_log_relative_path}"
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved

error_msg = (
"At least one of your input paths could not be processed."
f" Check {macro_path} for more details."
)
Comment on lines +286 to 301

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don’t raise on log-write failure; fail job gracefully and continue.

Raising here aborts the scheduler loop (main returns -1), stalling all jobs. Update job status with a short fallback message instead, commit, and continue.

-                if user_log_relative_path is None:
-                    err_msg = "Failed to write user log for invalid input paths."
-                    raise RuntimeError(err_msg)
+                if user_log_relative_path is None:
+                    fallback_msg = (
+                        "At least one of your input paths could not be processed."
+                        " Additionally, writing a user error log failed. See the scheduler logs"
+                        " for details."
+                    )
+                    update_compression_job_metadata(
+                        db_cursor,
+                        job_id,
+                        {
+                            "status": CompressionJobStatus.FAILED,
+                            "status_msg": fallback_msg,
+                        },
+                    )
+                    db_conn.commit()
+                    continue

Based on learnings.

🤖 Prompt for AI Agents
In
components/job-orchestration/job_orchestration/scheduler/compress/compression_scheduler.py
around lines 286 to 301, the current code raises a RuntimeError when
_write_user_failure_log returns None which aborts the scheduler loop; instead,
replace the raise with logic that sets the job status to a graceful failure
using a short fallback message (e.g., "Could not write user failure log; see
scheduler logs for details"), persist/commit that status update to the
datastore, and then continue execution without throwing so the scheduler loop is
not interrupted.


update_compression_job_metadata(
db_cursor,
Expand Down Expand Up @@ -384,7 +419,7 @@ def search_and_schedule_new_tasks(
scheduled_jobs[job_id] = job


def poll_running_jobs(db_conn, db_cursor):
def poll_running_jobs(clp_config: CLPConfig, db_conn, db_cursor):
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved
"""
Poll for running jobs and update their status.
"""
Expand Down Expand Up @@ -434,12 +469,24 @@ def poll_running_jobs(db_conn, db_cursor):
)
else:
logger.error(f"Job {job_id} failed. See worker logs or status_msg for details.")

status_msg = error_message
error_log_relative_path = _write_failed_compression_log(
status_msg, clp_config.logs_directory, job_id
)
if error_log_relative_path is None:
macro_path = "${CLP_LOGS_DIR}/compression_scheduler/compression_scheduler.log"
else:
macro_path = f"${{CLP_LOGS_DIR}}/{error_log_relative_path}"

error_msg = f"One or more compression tasks failed. See {macro_path} for more details."
Comment thread
quinntaylormitchell marked this conversation as resolved.
Resolved

Comment on lines +453 to +469

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Avoid crashing the scheduler on task-error log-write failure.

Same concern as the invalid-path branch: don’t raise. Mark job FAILED with a compact message, commit, add to jobs_to_delete, and continue.

-            error_log_relative_path = _write_user_failure_log(
-                error_message,
+            error_log_relative_path = _write_user_failure_log(
+                error_messages,
                 logs_directory,
                 job_id,
                 filename_suffix="task_errors",
                 title="Compression task errors.",
             )
-            if error_log_relative_path is None:
-                err_msg = "Failed to write user log for failed compression job."
-                raise RuntimeError(err_msg)
+            if error_log_relative_path is None:
+                fallback_msg = (
+                    "One or more compression tasks failed."
+                    " Additionally, writing the user error log failed. See worker logs for details."
+                )
+                update_compression_job_metadata(
+                    db_cursor,
+                    job_id,
+                    dict(
+                        status=CompressionJobStatus.FAILED,
+                        status_msg=fallback_msg,
+                    ),
+                )
+                db_conn.commit()
+                jobs_to_delete.append(job_id)
+                continue
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
error_log_relative_path = _write_user_failure_log(
error_message,
logs_directory,
job_id,
filename_suffix="task_errors",
title="Compression task errors.",
)
if error_log_relative_path is None:
err_msg = "Failed to write user log for failed compression job."
raise RuntimeError(err_msg)
error_msg = (
"One or more compression tasks failed."
f" See the error log at '{error_log_relative_path}' inside your configured logs"
" directory (`logs_directory`) for more details."
)
error_log_relative_path = _write_user_failure_log(
error_messages,
logs_directory,
job_id,
filename_suffix="task_errors",
title="Compression task errors.",
)
if error_log_relative_path is None:
fallback_msg = (
"One or more compression tasks failed."
" Additionally, writing the user error log failed. See worker logs for details."
)
update_compression_job_metadata(
db_cursor,
job_id,
dict(
status=CompressionJobStatus.FAILED,
status_msg=fallback_msg,
),
)
db_conn.commit()
jobs_to_delete.append(job_id)
continue
error_msg = (
"One or more compression tasks failed."
f" See the error log at '{error_log_relative_path}' inside your configured logs"
" directory (`logs_directory`) for more details."
)
🤖 Prompt for AI Agents
In
components/job-orchestration/job_orchestration/scheduler/compress/compression_scheduler.py
around lines 451 to 467, the code raises a RuntimeError when writing the
user-facing task-error log fails; instead follow the same non-crashing behavior
used for the invalid-path branch: do not raise, set the job state to FAILED with
a compact message noting the inability to write the user error log, commit the
job state change, append the job_id to jobs_to_delete, and continue execution;
ensure the compact message is concise, persist the update via the same commit
method used elsewhere, and keep control flow consistent with the surrounding
error-handling pattern.

update_compression_job_metadata(
db_cursor,
job_id,
dict(
status=CompressionJobStatus.FAILED,
status_msg=error_message,
status_msg=error_msg,
),
)
db_conn.commit()
Expand Down Expand Up @@ -515,7 +562,7 @@ def main(argv):
clp_metadata_db_connection_config,
task_manager,
)
poll_running_jobs(db_conn, db_cursor)
poll_running_jobs(clp_config, db_conn, db_cursor)
time.sleep(clp_config.compression_scheduler.jobs_poll_delay)
except KeyboardInterrupt:
logger.info("Forcefully shutting down")
Expand Down