Skip to content
Merged
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
90 changes: 90 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,13 @@ but can encounter "too many parts" errors when executing very large loads
of xAPI statements) or loads that cover a period over 9 years between the
configured `start_date` and `end_date`.

A competency load (``taxonomy_type: competency``) also writes
``student_competency_statuses.csv.gz`` and
``student_competency_course_statuses.csv.gz``, in the column order of the
``event_sink.student_competency_status`` and
``event_sink.student_competency_course_status`` tables. A ``--load_db_only``
run loads them only when the config is a competency load too.

chdb
----
This backend generates lz4 compressed ClickHouse Native files in block storage
Expand All @@ -113,6 +120,27 @@ type to parallelize data writing and loading. This is the fastest engine for
very large scale tests and should be able to generate several billions of rows
of data across any length of time without error.

A competency load (``taxonomy_type: competency``) also writes files under the
``student_competency_status`` and ``student_competency_course_status``
prefixes. As with csv, a ``--load_db_only`` run loads them only when the
config is a competency load too.

Required Aspects migrations
---------------------------
All backends write into ``event_sink`` tables created by tutor-contrib-aspects
migrations. A load into an install that lacks one of these fails with a
missing table or a column count mismatch:

- ``0042_event_sink_pathways``: ``event_sink.catalog_pathway`` and
``event_sink.pathway_enrollment`` (not needed with
``num_catalog_pathways: 0``).
- ``0043_event_sink_student_competency_status``:
``event_sink.student_competency_status`` (competency loads only).
- ``0044_event_sink_student_competency_course_status``:
``event_sink.student_competency_course_status`` (competency loads only).
- ``0045_event_sink_taxonomy_type``: the ``taxonomy_type`` column of
``event_sink.taxonomy``, needed by every load.



Getting Started
Expand Down Expand Up @@ -250,6 +278,9 @@ environment variables override their corresponding config keys at load time
- ``lrs_password``
- ``ralph``

Log lines and errors that quote SQL show the S3 secret as ``****`` and only the
first 4 characters of the S3 key.

A typical pattern is to keep all non-secret keys in YAML and provide the
secrets via the shell, your CI secret store, or a ``.env`` file::

Expand Down Expand Up @@ -330,6 +361,65 @@ test::
# real enrollments dumped by the LMS, as with first_catalog_pathway_id.
first_pathway_enrollment_id: 100001

# Fake organizations are named <org_prefix>0, <org_prefix>1... A different
# prefix keeps a load apart from earlier ones, or from real data, in the
# org filters. Letters and digits only.
org_prefix: Org

# The ids given to the first fake taxonomy, tag and object tag; the rest
# count up from them (tag and object tag ids across all taxonomies and
# courses). Positive integers. Raise them above the ids of real rows dumped
# by the LMS into the same event_sink tables, or the two overwrite each
# other. They default to 1 because earlier loads numbered these rows from 1.
first_taxonomy_id: 1
first_tag_id: 1
first_object_tag_id: 1

# The taxonomy export id written on every fake object tag. No quotes or
# backslashes.
taxonomy_export_id: fake export id

# The type written on every fake taxonomy, in the last column of
# event_sink.taxonomy: "tags", or "competency" for competency taxonomies,
# as the platform-plugin-aspects taxonomy sink writes it. Any other value is
# rejected.
#
# Every load writes this column, whatever its value, so every load needs
# the tutor-contrib-aspects migration 0045_event_sink_taxonomy_type. On an
# install without it the taxonomy insert fails (ClickHouse reports a column
# count mismatch).
#
# Only a competency load writes learner competency statuses, to
# event_sink.student_competency_status (migration
# 0043_event_sink_student_competency_status) and
# event_sink.student_competency_course_status (migration
# 0044_event_sink_student_competency_course_status). A "tags" load leaves
# both tables alone, and the CSV backend writes no files for them.
#
# In a competency load, each learner enrolled in a course gets, per
# competency tagged on its blocks, one of: no status (about 20%),
# AttemptedNotDemonstrated, PartiallyAttempted or Demonstrated. A
# Demonstrated draw whose mastery time falls after end_date stays
# PartiallyAttempted. Each competency gets its own difficulty, drawn anew on
# every run, so time to mastery spreads from hours to weeks and two loads
# with the same config differ. Parent competencies are raised from their
# children the way openedx-core does.
taxonomy_type: tags

# The id given to the first fake Student Competency Status, kept above the
# ids of real statuses dumped by the LMS, as with first_catalog_pathway_id.
# One row per learner and competency, PartiallyAttempted or Demonstrated.
first_student_competency_status_id: 100001

# The first ids of a competency load's course-level rows in
# event_sink.student_competency_course_status: one course-level criteria
# group status per learner, competency and course in which the learner has
# a status. These can be AttemptedNotDemonstrated, which core never stores
# per competency. The fake criteria groups they point at exist only as ids,
# one per competency and course. Kept above the real ids, as above.
first_student_competency_course_status_id: 100001
first_competency_criteria_group_id: 100001

# The number of learners to create, random subsets of these will be
# "registered" for each course and have statements generated for them
# between their registration date and the end of the course
Expand Down
34 changes: 34 additions & 0 deletions default_config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,40 @@ first_catalog_pathway_id: 100001
num_enrollments_per_pathway: 5
first_pathway_enrollment_id: 100001

# Fake organizations are named <org_prefix>0, <org_prefix>1... Letters and
# digits only. A different prefix keeps a load apart from earlier ones in the
# org filters.
org_prefix: Org

# Ids of the fake taxonomies, tags and object tags (positive integers). Raise
# them above the ids of real rows the LMS dumps into the same event_sink tables,
# or the two overwrite each other.
first_taxonomy_id: 1
first_tag_id: 1
first_object_tag_id: 1

# Export id written on every fake object tag. No quotes or backslashes.
taxonomy_export_id: fake export id

# Type written on every fake taxonomy: "tags" or "competency". Every load writes
# event_sink.taxonomy.taxonomy_type, so every load needs the tutor-contrib-aspects
# migration 0045_event_sink_taxonomy_type. "competency" also generates learner
# competency statuses into event_sink.student_competency_status (migration
# 0043_event_sink_student_competency_status) and
# event_sink.student_competency_course_status (migration
# 0044_event_sink_student_competency_course_status). See README.
taxonomy_type: tags

# First id of a competency load's competency-level statuses
# (event_sink.student_competency_status).
first_student_competency_status_id: 100001

# First ids of a competency load's course-level criteria group statuses
# (event_sink.student_competency_course_status), and of the fake criteria groups
# they point at.
first_student_competency_course_status_id: 100001
first_competency_criteria_group_id: 100001

# This replicates users updating their profiles several times, creating
# more rows
num_actor_profile_changes: 5
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "xapi-db-load"
version = "4.0.0"
version = "5.0.0"
description = "Loads testing xAPI events into databases and LRSs"
requires-python = ">=3.12"
license = "AGPL-3.0"
Expand Down
84 changes: 70 additions & 14 deletions xapi_db_load/backends/base_async_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from typing import (
Dict,
List,
Type,
)

import clickhouse_connect
Expand All @@ -22,6 +23,28 @@
Waiter,
)

# How many characters of an SQL statement go into an error log line. The
# statements carry whole batches of rows and can be many MB.
MAX_LOGGED_SQL_LENGTH = 2000

# How many leading characters of the S3 access key id are left readable in logs,
# enough to tell which key was used. The secret is always hidden whole.
VISIBLE_S3_KEY_CHARS = 4


def redact_credentials(text: str, s3_key: str | None, s3_secret: str | None) -> str:
"""
Return text with the S3 secret hidden and all but the start of the S3 key
hidden, for SQL and error messages that embed them before they are logged
or raised.
"""
if s3_secret:
text = text.replace(s3_secret, "****")
if s3_key:
visible = s3_key[:VISIBLE_S3_KEY_CHARS] if len(s3_key) > VISIBLE_S3_KEY_CHARS else ""
text = text.replace(s3_key, f"{visible}****")
return text


class BaseBackendTasks:
"""
Expand All @@ -47,6 +70,21 @@ def __repr__(self) -> str:
def get_test_data_tasks(self) -> List[Waiter]:
"""Return the tasks to be run to generate test data."""

def competency_tasks(self, *task_classes: Type[Waiter], **kwargs) -> List[Waiter]:
"""
Return the learner competency status tasks, only for a competency load.

A "tags" load has no statuses to write, and an install without the
tutor-contrib-aspects competency migrations has no tables to load them
into, so it must not touch those tables at all.
"""
if not self.event_generator.is_competency_load:
return []
return [
task_class(self.config, self.logger, self.event_generator, **kwargs)
for task_class in task_classes
]

def get_backend_summary(self) -> Dict:
"""
Get a dict describing our backend configuration.
Expand Down Expand Up @@ -97,6 +135,23 @@ def __init__(self, config: Dict, logger: Logger, event_generator: EventGenerator
self.s3_secret = config.get("s3_secret")
self.batch_size = self.config["batch_size"]

def redact(self, text: str) -> str:
"""
Return text with the configured S3 credentials redacted, see
``redact_credentials``.
"""
return redact_credentials(text, self.s3_key, self.s3_secret)

def sql_for_log(self, sql: str) -> str:
"""
Return an SQL statement fit for a log line: credentials redacted and
truncated to ``MAX_LOGGED_SQL_LENGTH`` characters.
"""
sql = self.redact(sql)
if len(sql) > MAX_LOGGED_SQL_LENGTH:
sql = f"{sql[:MAX_LOGGED_SQL_LENGTH]}... ({len(sql)} characters in all)"
return sql

async def set_client(self):
"""
Set up the ClickHouse client and connect.
Expand Down Expand Up @@ -132,31 +187,32 @@ async def _insert_list_sql_retry(
VALUES {",".join(data_list)}
"""

await self._insert_sql_with_retry(sql)
await self._run_sql_command(sql)

async def _insert_sql_with_retry(self, sql: str):
async def _run_sql_command(self, sql: str):
"""
Wrap insert commands with a single retry.
Run an SQL command, connecting first if needed. No retry: on failure it
logs and re-raises with the S3 credentials redacted.
"""
try:
# from clickhouse_connect.driver.asyncclient import AsyncClient
# Sometimes the connection randomly dies, this gives us a second shot in that case
if not self.client:
await self.set_client()
assert self.client
await self.client.command(sql)
except OperationalError as e:
self.logger.error(e)
self.logger.error("ClickHouse OperationalError, trying to reconnect.")
raise
# await self.set_client()
# self.logger.error("Retrying insert...")
# await self.client.command(sql)
message = self.redact(str(e))
self.logger.error("ClickHouse OperationalError (connection problem):")
self.logger.error(message)
# Raised anew, without the original as its cause: the original's
# message can quote the SQL, credentials included. Same class and
# error code, so callers can still tell the errors apart.
raise type(e)(message, code=e.code, name=e.name) from None
except DatabaseError as e:
message = self.redact(str(e))
self.logger.error("ClickHouse DatabaseError:")
self.logger.error(e)
self.logger.error(sql)
raise
self.logger.error(message)
self.logger.error(self.sql_for_log(sql))
raise type(e)(message, code=e.code, name=e.name) from None


class QueueBackend(BaseClickhouseBackend):
Expand Down
Loading