From 73695ecc3443e923925487819fe367a2cf2e5089 Mon Sep 17 00:00:00 2001 From: Felipe Montoya Date: Tue, 10 Nov 2026 20:01:22 -0500 Subject: [PATCH] feat!: load fake learner competency statuses Co-Authored-By: Claude Opus 5.5 --- README.rst | 90 ++++ default_config.yaml | 34 ++ pyproject.toml | 2 +- xapi_db_load/backends/base_async_backend.py | 84 +++- xapi_db_load/backends/chdb.py | 170 +++++++- xapi_db_load/backends/clickhouse.py | 153 ++++++- xapi_db_load/backends/csv.py | 109 ++++- xapi_db_load/backends/ralph.py | 5 + xapi_db_load/backends/vector.py | 5 + xapi_db_load/constants.py | 61 +++ xapi_db_load/course_configs.py | 18 +- xapi_db_load/generate_load_async.py | 441 +++++++++++++++++++- xapi_db_load/runner.py | 12 + xapi_db_load/tests/test_backends.py | 173 +++++++- xapi_db_load/tests/test_event_generator.py | 395 ++++++++++++++++++ 15 files changed, 1683 insertions(+), 69 deletions(-) diff --git a/README.rst b/README.rst index 966bd0e..32d5245 100644 --- a/README.rst +++ b/README.rst @@ -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 @@ -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 @@ -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:: @@ -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 0, 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 diff --git a/default_config.yaml b/default_config.yaml index c91de0a..66a1d80 100644 --- a/default_config.yaml +++ b/default_config.yaml @@ -62,6 +62,40 @@ first_catalog_pathway_id: 100001 num_enrollments_per_pathway: 5 first_pathway_enrollment_id: 100001 +# Fake organizations are named 0, 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 diff --git a/pyproject.toml b/pyproject.toml index cdf73d4..740e8a7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/xapi_db_load/backends/base_async_backend.py b/xapi_db_load/backends/base_async_backend.py index a511870..2ef1fe8 100644 --- a/xapi_db_load/backends/base_async_backend.py +++ b/xapi_db_load/backends/base_async_backend.py @@ -8,6 +8,7 @@ from typing import ( Dict, List, + Type, ) import clickhouse_connect @@ -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: """ @@ -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. @@ -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. @@ -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): diff --git a/xapi_db_load/backends/chdb.py b/xapi_db_load/backends/chdb.py index a4a1114..92f27f7 100644 --- a/xapi_db_load/backends/chdb.py +++ b/xapi_db_load/backends/chdb.py @@ -85,6 +85,11 @@ def get_test_data_tasks(self) -> List[Waiter]: self.event_generator, self.db_loader, ), + *self.competency_tasks( + WriteStudentCompetencyStatuses, + WriteStudentCompetencyCourseStatuses, + db_loader=self.db_loader, + ), WriteBlocks( self.config, self.logger, @@ -297,9 +302,20 @@ async def _write_sql_with_retry(self, sql: str): try: await loop.run_in_executor(None, chdb.query, sql) except Exception as e: # pylint: disable=broad-exception-caught - self.logger.info(f"Retrying due to CHDB error: {e}") - self.logger.info(f"SQL: {sql}") - await loop.run_in_executor(None, chdb.query, sql) + # chdb raises one error type for everything, so a dropped S3 + # connection can't be told apart from bad SQL: retry once either way. + self.logger.warning( + f"CHDB error writing {self.table}, retrying once: {self.redact(str(e))}" + ) + self.logger.warning(f"SQL: {self.sql_for_log(sql)}") + try: + await loop.run_in_executor(None, chdb.query, sql) + except Exception as retry_error: + # Raised anew, without the original as its cause: chdb's message + # can quote the SQL, credentials included. + raise RuntimeError( + f"CHDB write of {self.table} failed twice: {self.redact(str(retry_error))}" + ) from None class WriteXAPIEvents(XAPILakeCHDBAsync): @@ -666,6 +682,120 @@ async def _run_task(self): await self._write_list_sql_retry(out_data, "pathway_enrollment") +class WriteStudentCompetencyStatuses(XAPILakeCHDBAsync): # pylint: disable=abstract-method + """ + Write the learners' competency statuses to S3 using CHDB, all under one dump. + """ + + task_name = "Insert Student Competency Statuses" + schema = "event_sink" + table = "student_competency_status" + s3_load_prefix = "student_competency_status" + table_definition = """ + `id` Int64, + `actor_id` String, + `tag_id` Int64, + `taxonomy_id` Int64, + `status_id` UInt8, + `status_name` String, + `created` String, + `modified` String, + `dump_id` UUID, + `time_last_dumped` String + """ + + async def _run_task(self): + """ + Insert the learners' competency statuses into the event sink db. + """ + statuses = self.event_generator.student_competency_statuses + self.update_total_task_count(len(statuses)) + + dump_id = str(uuid.uuid4()) + dump_time = datetime.now(UTC) + out_data = [] + + for s in statuses: + out_data.append( + f"""( + {s["id"]}, + '{s["actor_id"]}', + {s["tag_id"]}, + {s["taxonomy_id"]}, + {s["status_id"]}, + '{s["status_name"]}', + '{s["created"]}', + '{s["modified"]}', + '{dump_id}', + '{dump_time}' + )""" + ) + self.update_completed_task_count(increment_by=1) + + if out_data: + await self._write_list_sql_retry(out_data, "student_competency_status") + + +class WriteStudentCompetencyCourseStatuses(XAPILakeCHDBAsync): # pylint: disable=abstract-method + """ + Write the learners' course-level criteria group statuses to S3 using CHDB, all under one dump. + """ + + task_name = "Insert Student Competency Course Statuses" + schema = "event_sink" + table = "student_competency_course_status" + s3_load_prefix = "student_competency_course_status" + table_definition = """ + `id` Int64, + `actor_id` String, + `group_id` Int64, + `tag_id` Int64, + `taxonomy_id` Int64, + `course_key` String, + `status_id` UInt8, + `status_name` String, + `created` String, + `modified` String, + `dump_id` UUID, + `time_last_dumped` String + """ + + async def _run_task(self): + """ + Insert the learners' course-level criteria group statuses into the event sink db. + """ + statuses = self.event_generator.student_competency_course_statuses + self.update_total_task_count(len(statuses)) + + dump_id = str(uuid.uuid4()) + dump_time = datetime.now(UTC) + out_data = [] + + for s in statuses: + out_data.append( + f"""( + {s["id"]}, + '{s["actor_id"]}', + {s["group_id"]}, + {s["tag_id"]}, + {s["taxonomy_id"]}, + '{s["course_key"]}', + {s["status_id"]}, + '{s["status_name"]}', + '{s["created"]}', + '{s["modified"]}', + '{dump_id}', + '{dump_time}' + )""" + ) + self.update_completed_task_count(increment_by=1) + + if out_data: + await self._write_list_sql_retry( + out_data, "student_competency_course_status" + ) + + class WriteBlocks(XAPILakeCHDBAsync): # pylint: disable=abstract-method """ Write the course block data to S3 using CHDB. @@ -772,22 +902,19 @@ async def _run_task(self): for course in self.event_generator.courses: course_count += 1 obj_tag_out_data = [] - object_tags = course.serialize_object_tag_data_for_event_sink() + object_tags = course.get_object_tags() - row_id = 0 for _ in range(num_course_publishes): dump_id = str(uuid.uuid4()) dump_time = datetime.now(UTC) for obj_tag in object_tags: - row_id += 1 - out_tag = f"""( - {row_id}, + {obj_tag["object_tag_id"]}, '{obj_tag["object_id"]}', {obj_tag["taxonomy_id"]}, {obj_tag["tag_id"]}, '{obj_tag["value"]}', - 'fake export id', + '{obj_tag["export_id"]}', '{obj_tag["hierarchy"]}', '{dump_id}', '{dump_time}' @@ -812,11 +939,14 @@ class WriteTaxonomies(XAPILakeCHDBAsync): # pylint: disable=abstract-method schema = "event_sink" table = "taxonomy" s3_load_prefix = "taxonomy" + # taxonomy_type is last: migration 0045 appends it to event_sink.taxonomy, + # and the S3 load inserts by position (SELECT *). table_definition = """ `id` Int32, `name` String, `dump_id` UUID, - `time_last_dumped` String + `time_last_dumped` String, + `taxonomy_type` String """ async def _run_task(self): @@ -830,12 +960,13 @@ async def _run_task(self): dump_time = datetime.now(UTC) out_data = [] - for taxonomy in taxonomies.keys(): + for taxonomy, taxonomy_id in self.event_generator.taxonomy_ids.items(): out = f"""( - {self.completed_task_count}, + {taxonomy_id}, '{taxonomy}', '{dump_id}', - '{dump_time}' + '{dump_time}', + '{self.event_generator.taxonomy_type}' ) """ out_data.append(out) @@ -1127,11 +1258,16 @@ async def _process_queue_item(self, worker_id: int, batch_id: int, batch: Any): batch["schema"], batch["table_name"], batch["file_path"] ) except Exception as e: # pylint: disable=broad-exception-caught + # One failed file doesn't stop the other loads; the Runner fails the + # run at the end when error_count is above 0. self.update_error_count() - self.logger.error(batch) + self.logger.error(self.redact(str(batch))) self.logger.error( - f" DB load worker encountered an error: {worker_id}, job {batch['job_id']}.", - exc_info=e, + f" DB load worker encountered an error: {worker_id}, job {batch['job_id']}, " + f"loading {batch['schema']}.{batch['table_name']}: " + f"{type(e).__name__}: {self.redact(str(e))}. If the " + "table or one of its columns is missing, run the tutor-contrib-aspects " + "migrations listed in the README." ) finally: self.update_completed_task_count(increment_by=1) @@ -1151,7 +1287,7 @@ async def _load_file_to_clickhouse( """ # This is the IO bound part, this thread will block until the write is complete. - await self._insert_sql_with_retry(sql) + await self._run_sql_command(sql) async def _run_db_load_task(self): """ diff --git a/xapi_db_load/backends/clickhouse.py b/xapi_db_load/backends/clickhouse.py index afac8d5..441ab06 100644 --- a/xapi_db_load/backends/clickhouse.py +++ b/xapi_db_load/backends/clickhouse.py @@ -45,6 +45,9 @@ def get_test_data_tasks(self) -> List[Waiter]: InsertCourses(self.config, self.logger, self.event_generator), InsertCatalogPathways(self.config, self.logger, self.event_generator), InsertPathwayEnrollments(self.config, self.logger, self.event_generator), + *self.competency_tasks( + InsertStudentCompetencyStatuses, InsertStudentCompetencyCourseStatuses + ), InsertBlocks(self.config, self.logger, self.event_generator), InsertObjectTags(self.config, self.logger, self.event_generator), InsertTaxonomies(self.config, self.logger, self.event_generator), @@ -70,24 +73,52 @@ async def _insert_rows( column_names: List[str] | str = "*", database: str = "event_sink", ): - """Insert rows via clickhouse-connect's parameterized insert.""" + """ + Insert rows via clickhouse-connect's parameterized insert. + + A dropped connection (OperationalError) is retried once. Any other + DatabaseError, such as a missing table or a column count that doesn't + match, is not: retrying can't fix it. + """ try: if not self.client: await self.set_client() assert self.client - await self.client.insert( - table, rows, column_names=column_names, database=database - ) + try: + await self.client.insert( + table, rows, column_names=column_names, database=database + ) + except OperationalError as e: + self.logger.error( + "ClickHouse OperationalError inserting into %s.%s, retrying once: %s", + database, + table, + e, + ) + await self.set_client() + assert self.client + await self.client.insert( + table, rows, column_names=column_names, database=database + ) except OperationalError as e: - self.logger.error(e) - self.logger.error("ClickHouse OperationalError, retrying once.") - await self.set_client() - assert self.client - await self.client.insert( - table, rows, column_names=column_names, database=database + # Caught before DatabaseError, its parent class: a connection that is + # still down after the retry is no migration problem. + self.logger.error( + "ClickHouse insert into %s.%s failed, connection problem: %s", + database, + table, + e, ) + raise except DatabaseError as e: - self.logger.error("ClickHouse DatabaseError: %s", e) + self.logger.error( + "ClickHouse insert into %s.%s failed: %s. If the table or one of its " + "columns is missing, run the tutor-contrib-aspects migrations listed " + "in the README.", + database, + table, + e, + ) raise @@ -351,6 +382,82 @@ async def _run_task(self): self.update_completed_task_count(increment_by=len(batch)) +class InsertStudentCompetencyStatuses(XAPILakeClickhouseAsync): # pylint: disable=abstract-method + """Inserts Student Competency Status data to ClickHouse.""" + + task_name = "Insert Student Competency Statuses" + + async def _run_task(self): + """ + Insert the learners' competency statuses to ClickHouse, all under one dump, in batches. + """ + statuses = self.event_generator.student_competency_statuses + self.update_total_task_count(len(statuses)) + + dump_id = str(uuid.uuid4()) + dump_time = str(datetime.now(UTC)) + batch_size = self.config["batch_size"] + + for i in range(0, len(statuses), batch_size): + batch = statuses[i:i + batch_size] + out_data = [ + ( + s["id"], + s["actor_id"], + s["tag_id"], + s["taxonomy_id"], + s["status_id"], + s["status_name"], + s["created"], + s["modified"], + dump_id, + dump_time, + ) + for s in batch + ] + await self._insert_rows("student_competency_status", out_data) + self.update_completed_task_count(increment_by=len(batch)) + + +class InsertStudentCompetencyCourseStatuses(XAPILakeClickhouseAsync): # pylint: disable=abstract-method + """Inserts Student Competency Course Status data to ClickHouse.""" + + task_name = "Insert Student Competency Course Statuses" + + async def _run_task(self): + """ + Insert the learners' course-level criteria group statuses to ClickHouse, all under one dump, in batches. + """ + statuses = self.event_generator.student_competency_course_statuses + self.update_total_task_count(len(statuses)) + + dump_id = str(uuid.uuid4()) + dump_time = str(datetime.now(UTC)) + batch_size = self.config["batch_size"] + + for i in range(0, len(statuses), batch_size): + batch = statuses[i:i + batch_size] + out_data = [ + ( + s["id"], + s["actor_id"], + s["group_id"], + s["tag_id"], + s["taxonomy_id"], + s["course_key"], + s["status_id"], + s["status_name"], + s["created"], + s["modified"], + dump_id, + dump_time, + ) + for s in batch + ] + await self._insert_rows("student_competency_course_status", out_data) + self.update_completed_task_count(increment_by=len(batch)) + + class InsertBlocks(XAPILakeClickhouseAsync): # pylint: disable=abstract-method """Inserts course block data to ClickHouse.""" @@ -411,24 +518,22 @@ async def _run_task(self): self.logger.info( f" {self.task_name} starting insert for course {self.completed_task_count}" ) - object_tags = course.serialize_object_tag_data_for_event_sink() + object_tags = course.get_object_tags() for _ in range(num_course_publishes): dump_id = str(uuid.uuid4()) dump_time = datetime.now(UTC) obj_tag_out_data = [] - row_id = 0 for obj_tag in object_tags: - row_id += 1 obj_tag_out_data.append( ( - row_id, + obj_tag["object_tag_id"], obj_tag["object_id"], obj_tag["taxonomy_id"], obj_tag["tag_id"], obj_tag["value"], - "fake export id", + obj_tag["export_id"], obj_tag["hierarchy"], dump_id, str(dump_time), @@ -455,10 +560,18 @@ async def _run_task(self): self.update_total_task_count(len(taxonomies)) out_data = [] - tag_id = 0 - for taxonomy in taxonomies.keys(): - tag_id += 1 - out_data.append((tag_id, taxonomy, dump_id, str(dump_time))) + for taxonomy, taxonomy_id in self.event_generator.taxonomy_ids.items(): + out_data.append( + ( + taxonomy_id, + taxonomy, + dump_id, + str(dump_time), + # Last: migration 0045 appends the column to event_sink.taxonomy, + # and rows go in by position. + self.event_generator.taxonomy_type, + ) + ) self.update_completed_task_count(increment_by=1) await self._insert_rows("taxonomy", out_data) diff --git a/xapi_db_load/backends/csv.py b/xapi_db_load/backends/csv.py index 4152948..2db3e26 100644 --- a/xapi_db_load/backends/csv.py +++ b/xapi_db_load/backends/csv.py @@ -50,6 +50,10 @@ def get_test_data_tasks(self) -> List[Waiter]: WriteCSVCourses(self.config, self.logger, self.event_generator), WriteCSVCatalogPathways(self.config, self.logger, self.event_generator), WriteCSVPathwayEnrollments(self.config, self.logger, self.event_generator), + *self.competency_tasks( + WriteCSVStudentCompetencyStatuses, + WriteCSVStudentCompetencyCourseStatuses, + ), WriteCSVBlocks(self.config, self.logger, self.event_generator), WriteCSVObjectTags(self.config, self.logger, self.event_generator), WriteCSVTaxonomies(self.config, self.logger, self.event_generator), @@ -130,8 +134,7 @@ async def _run_db_load_task(self): SELECT * FROM s3('{file}', '{self.config["s3_key"]}', '{self.config["s3_secret"]}', 'CSV'); """ - assert self.client - await self.client.command(sql) + await self._run_sql_command(sql) class WriteCSVXAPIEvents(XAPILakeCSVAsync): @@ -299,6 +302,84 @@ async def _run_task(self): self.update_completed_task_count(increment_by=1) +class WriteCSVStudentCompetencyStatuses(XAPILakeCSVAsync): + """Writes Student Competency Status data to a gzipped CSV file.""" + + task_name = "Write CSV Student Competency Statuses" + schema = "event_sink" + table = "student_competency_status" + filename = "student_competency_statuses.csv.gz" + + async def _run_task(self): + """ + Write out the learners' competency statuses data file, all under one dump. + """ + async with self.get_csv_handle("student_competency_statuses") as status_csv_writer: + statuses = self.event_generator.student_competency_statuses + self.update_total_task_count(len(statuses)) + + dump_id = str(uuid.uuid4()) + dump_time = datetime.now(UTC) + + for s in statuses: + status_csv_writer.writerow( + ( + s["id"], + s["actor_id"], + s["tag_id"], + s["taxonomy_id"], + s["status_id"], + s["status_name"], + s["created"], + s["modified"], + dump_id, + dump_time, + ) + ) + self.update_completed_task_count(increment_by=1) + + +class WriteCSVStudentCompetencyCourseStatuses(XAPILakeCSVAsync): + """Writes Student Competency Course Status data to a gzipped CSV file.""" + + task_name = "Write CSV Student Competency Course Statuses" + schema = "event_sink" + table = "student_competency_course_status" + filename = "student_competency_course_statuses.csv.gz" + + async def _run_task(self): + """ + Write out the learners' course-level criteria group statuses data file, all under one dump. + """ + async with self.get_csv_handle( + "student_competency_course_statuses" + ) as status_csv_writer: + statuses = self.event_generator.student_competency_course_statuses + self.update_total_task_count(len(statuses)) + + dump_id = str(uuid.uuid4()) + dump_time = datetime.now(UTC) + + for s in statuses: + status_csv_writer.writerow( + ( + s["id"], + s["actor_id"], + s["group_id"], + s["tag_id"], + s["taxonomy_id"], + s["course_key"], + s["status_id"], + s["status_name"], + s["created"], + s["modified"], + dump_id, + dump_time, + ) + ) + self.update_completed_task_count(increment_by=1) + + class WriteCSVBlocks(XAPILakeCSVAsync): """Writes course block data to a gzipped CSV file.""" @@ -358,23 +439,21 @@ async def _run_task(self): len(self.event_generator.courses) * num_course_publishes ) - row_id = 0 for course in self.event_generator.courses: - object_tags = course.serialize_object_tag_data_for_event_sink() + object_tags = course.get_object_tags() for _ in range(num_course_publishes): dump_id = str(uuid.uuid4()) dump_time = datetime.now(UTC) for obj_tag in object_tags: - row_id += 1 object_tag_csv_writer.writerow( ( - row_id, + obj_tag["object_tag_id"], obj_tag["object_id"], obj_tag["taxonomy_id"], obj_tag["tag_id"], obj_tag["value"], - "fake export id", + obj_tag["export_id"], obj_tag["hierarchy"], dump_id, dump_time, @@ -403,10 +482,18 @@ async def _run_task(self): dump_id = str(uuid.uuid4()) dump_time = datetime.now(UTC) - tag_id = 1 - for taxonomy in taxonomies.keys(): - tag_id += 1 - taxonomy_csv_writer.writerow((tag_id, taxonomy, dump_id, dump_time)) + for taxonomy, taxonomy_id in self.event_generator.taxonomy_ids.items(): + taxonomy_csv_writer.writerow( + ( + taxonomy_id, + taxonomy, + dump_id, + dump_time, + # Last: migration 0045 appends the column to event_sink.taxonomy, + # and rows go in by position. + self.event_generator.taxonomy_type, + ) + ) self.update_completed_task_count(increment_by=1) diff --git a/xapi_db_load/backends/ralph.py b/xapi_db_load/backends/ralph.py index d9d292f..18cb649 100644 --- a/xapi_db_load/backends/ralph.py +++ b/xapi_db_load/backends/ralph.py @@ -22,6 +22,8 @@ InsertObjectTags, InsertPathwayEnrollments, InsertProfiles, + InsertStudentCompetencyCourseStatuses, + InsertStudentCompetencyStatuses, InsertTags, InsertTaxonomies, InsertXAPIEvents, @@ -45,6 +47,9 @@ def get_test_data_tasks(self): InsertCourses(self.config, self.logger, self.event_generator), InsertCatalogPathways(self.config, self.logger, self.event_generator), InsertPathwayEnrollments(self.config, self.logger, self.event_generator), + *self.competency_tasks( + InsertStudentCompetencyStatuses, InsertStudentCompetencyCourseStatuses + ), InsertBlocks(self.config, self.logger, self.event_generator), InsertObjectTags(self.config, self.logger, self.event_generator), InsertTaxonomies(self.config, self.logger, self.event_generator), diff --git a/xapi_db_load/backends/vector.py b/xapi_db_load/backends/vector.py index ca59c41..e864e8f 100644 --- a/xapi_db_load/backends/vector.py +++ b/xapi_db_load/backends/vector.py @@ -23,6 +23,8 @@ InsertObjectTags, InsertPathwayEnrollments, InsertProfiles, + InsertStudentCompetencyCourseStatuses, + InsertStudentCompetencyStatuses, InsertTags, InsertTaxonomies, InsertXAPIEvents, @@ -46,6 +48,9 @@ def get_test_data_tasks(self): InsertCourses(self.config, self.logger, self.event_generator), InsertCatalogPathways(self.config, self.logger, self.event_generator), InsertPathwayEnrollments(self.config, self.logger, self.event_generator), + *self.competency_tasks( + InsertStudentCompetencyStatuses, InsertStudentCompetencyCourseStatuses + ), InsertBlocks(self.config, self.logger, self.event_generator), InsertObjectTags(self.config, self.logger, self.event_generator), InsertTaxonomies(self.config, self.logger, self.event_generator), diff --git a/xapi_db_load/constants.py b/xapi_db_load/constants.py index a884968..7d4c881 100644 --- a/xapi_db_load/constants.py +++ b/xapi_db_load/constants.py @@ -58,6 +58,67 @@ # Share of fake Pathway Enrollments that end up unenrolled (``is_active`` False). PATHWAY_UNENROLLED_RATIO = 0.1 +# Defaults of the ``org_prefix``, ``taxonomy_export_id`` and ``taxonomy_type`` +# config keys (see README for what each does). +DEFAULT_ORG_PREFIX = "Org" +DEFAULT_TAXONOMY_EXPORT_ID = "fake export id" + +# The values the platform-plugin-aspects taxonomy sink writes in +# ``event_sink.taxonomy.taxonomy_type``: "competency" for an openedx-core +# CompetencyTaxonomy, "tags" otherwise. Only these two are accepted. +TAXONOMY_TYPE_TAGS = "tags" +TAXONOMY_TYPE_COMPETENCY = "competency" +TAXONOMY_TYPES = (TAXONOMY_TYPE_TAGS, TAXONOMY_TYPE_COMPETENCY) +DEFAULT_TAXONOMY_TYPE = TAXONOMY_TYPE_TAGS + +# Defaults of ``first_taxonomy_id``, ``first_tag_id`` and ``first_object_tag_id``. +# They stay at 1, not above the real ids like the status ids below, because +# earlier loads always numbered these rows from 1: a load with the defaults +# keeps replacing the same fake rows instead of adding a second copy. +DEFAULT_FIRST_TAXONOMY_ID = 1 +DEFAULT_FIRST_TAG_ID = 1 +DEFAULT_FIRST_OBJECT_TAG_ID = 1 + +# Defaults of ``first_student_competency_status_id``, +# ``first_student_competency_course_status_id`` and +# ``first_competency_criteria_group_id``, kept above the ids of real rows dumped +# by the LMS, as with ``DEFAULT_FIRST_CATALOG_PATHWAY_ID``. +DEFAULT_FIRST_STUDENT_COMPETENCY_STATUS_ID = 100001 +DEFAULT_FIRST_STUDENT_COMPETENCY_COURSE_STATUS_ID = 100001 +DEFAULT_FIRST_COMPETENCY_CRITERIA_GROUP_ID = 100001 + +# openedx-core mastery status ids and the names the sinks write next to them. +# Core never stores AttemptedNotDemonstrated at the competency level, only on +# criteria groups, and "not started" is no row at all. The ids rank the statuses: +# a higher id is further along, and the generator compares them with max() and >. +MASTERY_STATUS_ATTEMPTED_NOT_DEMONSTRATED = 10 +MASTERY_STATUS_PARTIALLY_ATTEMPTED = 20 +MASTERY_STATUS_DEMONSTRATED = 30 +MASTERY_STATUS_NAMES = { + MASTERY_STATUS_ATTEMPTED_NOT_DEMONSTRATED: "AttemptedNotDemonstrated", + MASTERY_STATUS_PARTIALLY_ATTEMPTED: "PartiallyAttempted", + MASTERY_STATUS_DEMONSTRATED: "Demonstrated", +} + +# How a learner enrolled in a course stands on each competency the course +# assesses: the course-level criteria group status, drawn with these weights for +# (no status, AttemptedNotDemonstrated, PartiallyAttempted, Demonstrated). The +# competency-level status records AttemptedNotDemonstrated as PartiallyAttempted. +COMPETENCY_COURSE_STATUS_WEIGHTS = (0.2, 0.15, 0.25, 0.4) + +# A learner's first status on a competency lands soon after they enroll: an +# exponential delay with this median, in hours. Their first xAPI activity in the +# course comes after the enrollment too, so time to mastery measured from either +# one is mostly the mastery time below. +COMPETENCY_FIRST_STATUS_MEDIAN_HOURS = 12.0 + +# Each competency gets its own difficulty: the median time its learners take to +# demonstrate it, drawn log-uniformly from this range (in days) on every run, so +# some take hours and others weeks. Each learner then takes a log-normal time +# around that median with this sigma. +COMPETENCY_MASTERY_MEDIAN_DAYS_RANGE = (0.15, 30.0) +COMPETENCY_MASTERY_SIGMA = 0.6 + # Range of "course runs" generated per logical course (inclusive of low, # exclusive of high — passed straight to ``random.randrange``). MIN_COURSE_RUNS = 1 diff --git a/xapi_db_load/course_configs.py b/xapi_db_load/course_configs.py index 391e6de..2140f9c 100644 --- a/xapi_db_load/course_configs.py +++ b/xapi_db_load/course_configs.py @@ -87,6 +87,7 @@ def __init__(self): self.forum_post_ids: List[str] = [] self.actors: list[EnrolledActor] = [] self.all_tags: list = [] + self._object_tags: List[Dict] | None = None self.start_date: datetime.datetime | None = None self.end_date: datetime.datetime | None = None @@ -398,8 +399,18 @@ def serialize_block_data_for_event_sink(self) -> List[Dict]: return course_structure - def serialize_object_tag_data_for_event_sink(self) -> List[Dict]: - """Return list of object_tag dicts for the event-sink schema.""" + def get_object_tags(self) -> List[Dict]: + """ + Return this course's object tag dicts for the event-sink schema. + + The blocks are tagged at random on the first call, and that same list + (not a copy) is returned after that, so every caller sees the same object + tags. ``EventGenerator.setup_object_tags`` adds ``object_tag_id`` and + ``export_id`` to these dicts in place during setup, so callers that need + those keys must run after setup. + """ + if self._object_tags is not None: + return self._object_tags object_tags = [] cnt = 0 for block_type in ( @@ -420,6 +431,8 @@ def serialize_object_tag_data_for_event_sink(self) -> List[Dict]: for _ in range(num_tags): tag = random.choice(self.all_tags) object_tag = copy.deepcopy(tag) + # The tag's own fixture id; object tags get object_tag_id. + del object_tag["id"] # TODO: Need to break this call out to only return what we need, or refactor # storing the object id so we don't have to do this twice object_tag["object_id"] = self._serialize_block( @@ -427,4 +440,5 @@ def serialize_object_tag_data_for_event_sink(self) -> List[Dict]: )["location"] object_tags.append(object_tag) + self._object_tags = object_tags return object_tags diff --git a/xapi_db_load/generate_load_async.py b/xapi_db_load/generate_load_async.py index 415b0a4..5edf9a8 100644 --- a/xapi_db_load/generate_load_async.py +++ b/xapi_db_load/generate_load_async.py @@ -5,9 +5,11 @@ import asyncio import datetime import json +import math import os import random import uuid +from dataclasses import dataclass from logging import Logger from random import ( choice, @@ -17,19 +19,39 @@ Dict, Generator, List, + NamedTuple, ) from xapi_db_load.constants import ( + COMPETENCY_COURSE_STATUS_WEIGHTS, + COMPETENCY_FIRST_STATUS_MEDIAN_HOURS, + COMPETENCY_MASTERY_MEDIAN_DAYS_RANGE, + COMPETENCY_MASTERY_SIGMA, COURSE_ID_SHORT_LENGTH, DEFAULT_FIRST_CATALOG_PATHWAY_ID, + DEFAULT_FIRST_COMPETENCY_CRITERIA_GROUP_ID, + DEFAULT_FIRST_OBJECT_TAG_ID, DEFAULT_FIRST_PATHWAY_ENROLLMENT_ID, + DEFAULT_FIRST_STUDENT_COMPETENCY_COURSE_STATUS_ID, + DEFAULT_FIRST_STUDENT_COMPETENCY_STATUS_ID, + DEFAULT_FIRST_TAG_ID, + DEFAULT_FIRST_TAXONOMY_ID, DEFAULT_LMS_URL, DEFAULT_NUM_CATALOG_PATHWAYS, DEFAULT_NUM_ENROLLMENTS_PER_PATHWAY, + DEFAULT_ORG_PREFIX, + DEFAULT_TAXONOMY_EXPORT_ID, + DEFAULT_TAXONOMY_TYPE, + MASTERY_STATUS_ATTEMPTED_NOT_DEMONSTRATED, + MASTERY_STATUS_DEMONSTRATED, + MASTERY_STATUS_NAMES, + MASTERY_STATUS_PARTIALLY_ATTEMPTED, MAX_COURSE_RUNS, MIN_COURSE_RUNS, PATHWAY_CATEGORIES, PATHWAY_UNENROLLED_RATIO, + TAXONOMY_TYPE_COMPETENCY, + TAXONOMY_TYPES, ) from xapi_db_load.course_configs import ( Actor, @@ -118,6 +140,18 @@ def _random_datetime( return start + datetime.timedelta(microseconds=random.randrange(max(span, 1))) +def _as_utc_datetime(value: datetime.date) -> datetime.datetime: + """ + Return a date or datetime as a UTC datetime; course dates are plain dates + when the configured start and end dates are. + """ + if not isinstance(value, datetime.datetime): + return datetime.datetime.combine(value, datetime.time(), tzinfo=datetime.UTC) + if value.tzinfo is None: + return value.replace(tzinfo=datetime.UTC) + return value + + def to_sink_datetime(value: datetime.datetime) -> str: """ Format a UTC datetime the way the platform-plugin-aspects model sinks write @@ -130,6 +164,67 @@ def to_sink_datetime(value: datetime.datetime) -> str: return formatted +class StudentCompetencyCourseStatusRow(NamedTuple): + """ + How one learner stands on one competency in one course: the course-level + criteria group status, and when it was first set and last raised. + """ + + course: RandomCourse + tag_id: int + actor: Actor + status_id: int + created: datetime.datetime + modified: datetime.datetime + + +@dataclass +class StudentCompetencyStatusRow: + """ + A learner's single competency-level status row, raised as course statuses and + child competencies are folded into it. + """ + + actor: Actor + status_id: int + created: datetime.datetime + modified: datetime.datetime + + def fold_in( + self, + status_id: int, + created: datetime.datetime, + modified: datetime.datetime, + ) -> None: + """ + Fold another status into this row, the way openedx-core's raise-only + writes would: the higher status wins, ``created`` is the earliest, and a + Demonstrated row keeps its first mastery time. A PartiallyAttempted row + was never raised, so its ``modified`` stays equal to its ``created``. + """ + self.created = min(self.created, created) + if status_id > self.status_id: + self.status_id, self.modified = status_id, modified + elif status_id == self.status_id == MASTERY_STATUS_DEMONSTRATED: + self.modified = min(self.modified, modified) + if self.status_id != MASTERY_STATUS_DEMONSTRATED: + self.modified = self.created + + +# (actor user_id, tag_id) -> that learner's competency-level status row +StudentCompetencyStatusRows = Dict[tuple[int, int], StudentCompetencyStatusRow] + +# Config keys holding ids, each of which must be a positive integer. +POSITIVE_ID_CONFIG_KEYS = ( + "first_taxonomy_id", + "first_tag_id", + "first_object_tag_id", + "first_student_competency_status_id", + "first_student_competency_course_status_id", + "first_competency_criteria_group_id", +) + + class EventGenerator(Waiter): # pylint: disable=abstract-method """ Generates a batch of random xAPI events based on the EVENT_WEIGHTS proportions. @@ -151,7 +246,11 @@ def __init__( self.catalog_pathways: List[Dict] = [] self.pathway_enrollments: List[Dict] = [] self.taxonomies: Dict = {} + self.taxonomy_ids: Dict[str, int] = {} self.tags: List = [] + self.student_competency_statuses: List[Dict] = [] + self.student_competency_course_statuses: List[Dict] = [] + self.competency_mastery_median_days: Dict[int, float] = {} self.setup_complete = False self.start_date = config["start_date"] self.end_date = config["end_date"] @@ -178,6 +277,25 @@ def _validate_config(self) -> None: f"Course size {s} wants more actors than are configured in num_actors." ) + for key in POSITIVE_ID_CONFIG_KEYS: + value = self.config.get(key, 1) + if isinstance(value, bool) or not isinstance(value, int) or value < 1: + raise ValueError(f"{key} must be a positive integer, got {value!r}.") + + # These end up inside quoted SQL literals in the CHDB backend. + prefix = self.config.get("org_prefix", DEFAULT_ORG_PREFIX) + if not isinstance(prefix, str) or not prefix.isalnum(): + raise ValueError(f"org_prefix must be letters and digits, got {prefix!r}.") + export_id = self.config.get("taxonomy_export_id", DEFAULT_TAXONOMY_EXPORT_ID) + if not isinstance(export_id, str) or "'" in export_id or "\\" in export_id: + raise ValueError( + f"taxonomy_export_id must be a string without quotes or backslashes, got {export_id!r}." + ) + if self.taxonomy_type not in TAXONOMY_TYPES: + raise ValueError( + f"taxonomy_type must be one of {', '.join(TAXONOMY_TYPES)}, got {self.taxonomy_type!r}." + ) + async def run_task(self) -> None: """ We override run_task here instead of _run_task because this is the setup task @@ -194,6 +312,10 @@ async def run_task(self) -> None: await self.setup_courses() # Needs the courses, to enroll learners of the pathway's org. self.setup_pathway_enrollments() + # Needs the courses, whose blocks it tags. + self.setup_object_tags() + # Needs the object tags, to know which competencies each course assesses. + self.setup_student_competency_statuses() # Force this in case of a rounding error self.complete_pct = 1.0 @@ -212,8 +334,9 @@ def setup_orgs(self) -> None: """ Create some random organizations based on the config. """ + prefix = self.config.get("org_prefix", DEFAULT_ORG_PREFIX) for i in range(self.config["num_organizations"]): - self.orgs.append(f"Org{i}") + self.orgs.append(f"{prefix}{i}") def setup_catalog_pathways(self) -> None: """ @@ -313,6 +436,316 @@ def setup_pathway_enrollments(self) -> None: ) next_id += 1 + def setup_object_tags(self) -> None: + """ + Tag each course's blocks once, so every backend writes the same object + tags and the competency statuses match them. + + Object tag ids count up from ``first_object_tag_id`` across all courses, + and every row carries ``taxonomy_export_id`` as its taxonomy's export id. + Both are added in place to the dicts ``RandomCourse.get_object_tags`` + keeps and returns. + """ + next_id = self.config.get("first_object_tag_id", DEFAULT_FIRST_OBJECT_TAG_ID) + export_id = self.config.get("taxonomy_export_id", DEFAULT_TAXONOMY_EXPORT_ID) + for course in self.courses: + for object_tag in course.get_object_tags(): + object_tag["object_tag_id"] = next_id + object_tag["export_id"] = export_id + next_id += 1 + + @property + def taxonomy_type(self) -> str: + """ + The type written on every fake taxonomy. + """ + return self.config.get("taxonomy_type", DEFAULT_TAXONOMY_TYPE) + + @property + def is_competency_load(self) -> bool: + """ + Whether the fake taxonomies are competency taxonomies. + """ + return self.taxonomy_type == TAXONOMY_TYPE_COMPETENCY + + def setup_student_competency_statuses(self) -> None: + """ + Give learners a mastery status on the competencies their courses assess. + + Only for a competency load (see ``is_competency_load``). A course assesses + every competency tagged on one of its blocks. Each enrolled learner gets, + per competency and course, one of four course statuses: no status, + AttemptedNotDemonstrated, PartiallyAttempted or Demonstrated, weighted by + ``COMPETENCY_COURSE_STATUS_WEIGHTS`` (see ``_time_course_status`` for + the timing). A Demonstrated draw whose mastery time falls after + ``end_date`` stays PartiallyAttempted, so the real Demonstrated share is + below its weight, and lowest for the hardest competencies. + + Competency-level rows follow openedx-core's rules for + ``StudentCompetencyStatus``: + + - one row per learner and competency: across courses the higher status + wins, ``created`` is the earliest, and ``modified`` of a Demonstrated + row is when it was first demonstrated + - only PartiallyAttempted (20) and Demonstrated (30): AttemptedNotDemonstrated + is recorded as PartiallyAttempted, as core's rollup does + - parent competencies roll up (see ``roll_up_statuses``) + + The course statuses are also written as they are, as course-level + criteria group statuses: see ``_add_student_competency_course_statuses``. + + Rows match the ``event_sink.student_competency_status`` and + ``event_sink.student_competency_course_status`` tables written by the + platform-plugin-aspects sinks of the same names. + """ + if not self.is_competency_load: + return + + tags_by_id = {t["tag_id"]: t for t in self.tags} + low, high = COMPETENCY_MASTERY_MEDIAN_DAYS_RANGE + self.competency_mastery_median_days = { + tag_id: math.exp(random.uniform(math.log(low), math.log(high))) + for tag_id in tags_by_id + } + + course_statuses = self._draw_course_statuses() + statuses = self._fold_competency_statuses(course_statuses) + self.roll_up_statuses(statuses, tags_by_id) + self._add_student_competency_statuses(statuses, tags_by_id) + self._add_student_competency_course_statuses(course_statuses, tags_by_id) + + def _draw_course_statuses(self) -> List[StudentCompetencyCourseStatusRow]: + """ + Draw every enrolled learner's course status on every competency their course + assesses, leaving out the "no status" draws. + """ + _, run_end = self._run_window() + drawn_status_ids = ( + None, + MASTERY_STATUS_ATTEMPTED_NOT_DEMONSTRATED, + MASTERY_STATUS_PARTIALLY_ATTEMPTED, + MASTERY_STATUS_DEMONSTRATED, + ) + course_statuses = [] + for course in self.courses: + assessed_tag_ids = {o["tag_id"] for o in course.get_object_tags()} + course_end = min(_as_utc_datetime(course.end_date), run_end) + # course.actors is drawn with replacement, so a learner can be enrolled + # twice; keep one enrollment each, or they get two statuses per + # competency in the same course. + learners = {e.actor.user_id: e for e in course.actors} + for enrolled in learners.values(): + enrolled_at = _as_utc_datetime(enrolled.enroll_datetime) + for tag_id in assessed_tag_ids: + drawn_status_id = random.choices( + drawn_status_ids, COMPETENCY_COURSE_STATUS_WEIGHTS + )[0] + if drawn_status_id is None: + continue + status_id, created, modified = self._time_course_status( + drawn_status_id, tag_id, enrolled_at, course_end, run_end + ) + course_statuses.append( + StudentCompetencyCourseStatusRow( + course, tag_id, enrolled.actor, status_id, created, modified + ) + ) + return course_statuses + + def _time_course_status( + self, + drawn_status_id: int, + tag_id: int, + enrolled_at: datetime.datetime, + course_end: datetime.datetime, + run_end: datetime.datetime, + ) -> tuple[int, datetime.datetime, datetime.datetime]: + """ + Return the final status, created and modified times of one drawn status. + + The first status lands an exponential delay after enrollment + (``COMPETENCY_FIRST_STATUS_MEDIAN_HOURS``), by the course end at the + latest. A Demonstrated draw is mastered a log-normal time around the + competency's difficulty later (``competency_mastery_median_days``), and + stays PartiallyAttempted when that falls after the end of the run. + """ + # An exponential delay with median m has rate ln(2) / m. + first_status_rate = math.log(2) / (COMPETENCY_FIRST_STATUS_MEDIAN_HOURS * 3600) + first_status_delay = datetime.timedelta( + seconds=random.expovariate(first_status_rate) + ) + latest_first_status = max(course_end, enrolled_at) + created = min(enrolled_at + first_status_delay, latest_first_status) + + if drawn_status_id != MASTERY_STATUS_DEMONSTRATED: + return drawn_status_id, created, created + + mastered_at = created + datetime.timedelta( + days=random.lognormvariate(0, COMPETENCY_MASTERY_SIGMA) + * self.competency_mastery_median_days[tag_id] + ) + if mastered_at > run_end: + return MASTERY_STATUS_PARTIALLY_ATTEMPTED, created, created + return MASTERY_STATUS_DEMONSTRATED, created, mastered_at + + @staticmethod + def _fold_competency_statuses( + course_statuses: List[StudentCompetencyCourseStatusRow], + ) -> StudentCompetencyStatusRows: + """ + Fold the course statuses into one competency-level row per learner and + competency, recording AttemptedNotDemonstrated as PartiallyAttempted. + """ + statuses: StudentCompetencyStatusRows = {} + for o in course_statuses: + status_id = max(o.status_id, MASTERY_STATUS_PARTIALLY_ATTEMPTED) + key = (o.actor.user_id, o.tag_id) + if key in statuses: + statuses[key].fold_in(status_id, o.created, o.modified) + else: + statuses[key] = StudentCompetencyStatusRow( + o.actor, status_id, o.created, o.modified + ) + return statuses + + def _add_student_competency_statuses( + self, statuses: StudentCompetencyStatusRows, tags_by_id: Dict[int, Dict] + ) -> None: + """ + Write the competency-level rows in ``created`` order, with ids counting up + from ``first_student_competency_status_id``. + """ + next_id = self.config.get( + "first_student_competency_status_id", + DEFAULT_FIRST_STUDENT_COMPETENCY_STATUS_ID, + ) + for (_, tag_id), status in sorted( + statuses.items(), key=lambda item: item[1].created + ): + self.student_competency_statuses.append( + { + "id": next_id, + "actor_id": status.actor.id, + "tag_id": tag_id, + "taxonomy_id": tags_by_id[tag_id]["taxonomy_id"], + "status_id": status.status_id, + "status_name": MASTERY_STATUS_NAMES[status.status_id], + "created": to_sink_datetime(status.created), + "modified": to_sink_datetime(status.modified), + } + ) + next_id += 1 + + def _add_student_competency_course_statuses( + self, course_statuses: List[StudentCompetencyCourseStatusRow], tags_by_id: Dict[int, Dict] + ) -> None: + """ + Write one course-level criteria group status per learner, competency and + course they have a status in: AttemptedNotDemonstrated (10), + PartiallyAttempted (20) or Demonstrated (30). Ids count up from + ``first_student_competency_course_status_id``. + + The fake criteria groups exist only as ids: one course group per + competency and course run, counting up from + ``first_competency_criteria_group_id``. The sink writes course-level + groups only, so root and leaf groups have no rows here either. + """ + next_group_id = self.config.get( + "first_competency_criteria_group_id", + DEFAULT_FIRST_COMPETENCY_CRITERIA_GROUP_ID, + ) + group_id_by_tag_and_course: Dict[tuple, int] = {} + next_id = self.config.get( + "first_student_competency_course_status_id", + DEFAULT_FIRST_STUDENT_COMPETENCY_COURSE_STATUS_ID, + ) + for o in sorted(course_statuses, key=lambda o: o.created): + group_key = (o.tag_id, o.course.course_id) + if group_key not in group_id_by_tag_and_course: + group_id_by_tag_and_course[group_key] = next_group_id + next_group_id += 1 + self.student_competency_course_statuses.append( + { + "id": next_id, + "actor_id": o.actor.id, + "group_id": group_id_by_tag_and_course[group_key], + "tag_id": o.tag_id, + "taxonomy_id": tags_by_id[o.tag_id]["taxonomy_id"], + "course_key": o.course.course_id, + "status_id": o.status_id, + "status_name": MASTERY_STATUS_NAMES[o.status_id], + "created": to_sink_datetime(o.created), + "modified": to_sink_datetime(o.modified), + } + ) + next_id += 1 + + @staticmethod + def roll_up_statuses(statuses: StudentCompetencyStatusRows, tags_by_id: Dict[int, Dict]) -> None: + """ + Raise each learner's parent competencies from their children, deepest + level first, so a parent's children are final before it is computed. + + A parent is Demonstrated once every child the learner has a status on + is (mastered when the last one was), otherwise PartiallyAttempted from + the first child status. A parent the learner already has a direct status + on (it is tagged on a block too) is only ever raised by this, never + lowered, as with core's raise-only writes. + """ + depths: Dict[int, int] = {} + + def depth(tag_id: int) -> int: + if tag_id not in depths: + parent_tag_id = tags_by_id[tag_id]["parent_int_id"] + depths[tag_id] = 0 if parent_tag_id is None else 1 + depth(parent_tag_id) + return depths[tag_id] + + # Each learner's view of ``statuses``, by tag id. Both hold the same row + # objects, so a raised row is raised in both, but a new parent row has + # to be added to both. + statuses_by_user_id: Dict[int, Dict[int, StudentCompetencyStatusRow]] = {} + for (user_id, tag_id), status in statuses.items(): + statuses_by_user_id.setdefault(user_id, {})[tag_id] = status + + for user_id, user_statuses in statuses_by_user_id.items(): + deepest = max(depth(t) for t in user_statuses) + for level in range(deepest, 0, -1): + children_by_parent: Dict[int, List[StudentCompetencyStatusRow]] = {} + for tag_id, status in user_statuses.items(): + if depth(tag_id) == level: + parent_tag_id = tags_by_id[tag_id]["parent_int_id"] + children_by_parent.setdefault(parent_tag_id, []).append(status) + for parent_tag_id, children in children_by_parent.items(): + rolled = EventGenerator._roll_up_children(children) + if parent_tag_id in user_statuses: + user_statuses[parent_tag_id].fold_in( + rolled.status_id, rolled.created, rolled.modified + ) + else: + user_statuses[parent_tag_id] = rolled + statuses[(user_id, parent_tag_id)] = rolled + + @staticmethod + def _roll_up_children( + children: List[StudentCompetencyStatusRow], + ) -> StudentCompetencyStatusRow: + """ + Return the parent status a learner's child statuses roll up to: + Demonstrated when every child is (mastered when the last one was), + otherwise PartiallyAttempted from the first child status. + """ + created = min(c.created for c in children) + if all(c.status_id == MASTERY_STATUS_DEMONSTRATED for c in children): + return StudentCompetencyStatusRow( + children[0].actor, + MASTERY_STATUS_DEMONSTRATED, + created, + max(c.modified for c in children), + ) + return StudentCompetencyStatusRow( + children[0].actor, MASTERY_STATUS_PARTIALLY_ATTEMPTED, created, created + ) + def _run_window(self) -> tuple[datetime.datetime, datetime.datetime]: """ Return the configured start and end dates as UTC datetimes. @@ -423,10 +856,12 @@ def setup_taxonomies_tags(self) -> None: # it should be guaranteed that all parents already exist when we get to # the child. tag_hierarchy = {} - taxonomy_id = 0 + taxonomy_id = self.config.get("first_taxonomy_id", DEFAULT_FIRST_TAXONOMY_ID) - 1 + # Tag ids are unique across taxonomies, as in the LMS. + tag_id = self.config.get("first_tag_id", DEFAULT_FIRST_TAG_ID) - 1 for taxonomy in self.taxonomies: # pylint: disable=consider-using-dict-items taxonomy_id += 1 - tag_id = 0 + self.taxonomy_ids[taxonomy] = taxonomy_id for tag in self.taxonomies[taxonomy]: tag_id += 1 tag["tag_id"] = tag_id diff --git a/xapi_db_load/runner.py b/xapi_db_load/runner.py index ddd8b66..60f32ac 100644 --- a/xapi_db_load/runner.py +++ b/xapi_db_load/runner.py @@ -95,6 +95,18 @@ async def run(self, load_db_only: bool = False): for r in results: if isinstance(r, Exception): raise r + + # The S3 loader logs a failed file and goes on with the others, so the run + # only learns of it here. + failed_loads = sum(getattr(task, "error_count", 0) for task in self.test_data_tasks) + if failed_loads: + self.running = False + # Every task has finished, so log_status would soon report the run + # as complete; stop it so the failure is the last word. + log_status_task.cancel() + raise RuntimeError( + f"{failed_loads} database load job(s) failed, see the errors logged above." + ) self.running = False self.finished = True self.logger.info( diff --git a/xapi_db_load/tests/test_backends.py b/xapi_db_load/tests/test_backends.py index 9a84f3c..dba98d2 100644 --- a/xapi_db_load/tests/test_backends.py +++ b/xapi_db_load/tests/test_backends.py @@ -7,6 +7,7 @@ import os import re from contextlib import contextmanager +from csv import reader as csv_reader from unittest.mock import ( AsyncMock, MagicMock, @@ -15,7 +16,9 @@ import yaml from click.testing import CliRunner +from clickhouse_connect.driver.exceptions import DatabaseError +from xapi_db_load.backends.base_async_backend import redact_credentials from xapi_db_load.constants import ( DEFAULT_NUM_CATALOG_PATHWAYS, DEFAULT_NUM_ENROLLMENTS_PER_PATHWAY, @@ -24,7 +27,7 @@ @contextmanager -def override_config(config_path, tmp_path): +def override_config(config_path, tmp_path, **overrides): """ Override the config file with runtime variables (temp file paths, etc). @@ -35,6 +38,7 @@ def override_config(config_path, tmp_path): test_config["log_dir"] = str(tmp_path) test_config["csv_output_destination"] = str(tmp_path) + test_config.update(overrides) with patch("xapi_db_load.main.get_config") as mock_config: mock_config.return_value = test_config @@ -262,3 +266,170 @@ def test_chdb_backend(_mock_ch, _mock_chdb, _mock_boto, tmp_path): assert "Insert Initial Enrollments complete." in result.output assert "ALL TASKS DONE!" in result.output assert "Run duration was" in result.output + + +def _read_csv(test_config, prefix): + """Return the rows of one gzipped CSV output file.""" + with gzip.open( + os.path.join(test_config["log_dir"], f"{prefix}.csv.gz"), "rt" + ) as csv_file: + return list(csv_reader(csv_file)) + + +def test_csv_backend_competency_load(tmp_path): + """ + A competency load marks the taxonomy "competency" in its last column and + writes both learner competency status files. + """ + test_path = "xapi_db_load/tests/fixtures/small_csv_config.yaml" + + with override_config(test_path, tmp_path, taxonomy_type="competency") as test_config: + result = CliRunner().invoke( + load_db, f"--config_file {test_path}", catch_exceptions=False + ) + + assert "ALL TASKS DONE!" in result.output + taxonomies = _read_csv(test_config, "taxonomies") + assert taxonomies + assert {row[-1] for row in taxonomies} == {"competency"} + + statuses = _read_csv(test_config, "student_competency_statuses") + group_statuses = _read_csv(test_config, "student_competency_course_statuses") + assert statuses + assert group_statuses + # id, actor_id, group_id, tag_id, taxonomy_id, course_key, status_id, + # status_name, created, modified, dump_id, time_last_dumped + assert {len(row) for row in group_statuses} == {12} + + +def test_csv_backend_tags_load(tmp_path): + """A default load marks the taxonomy "tags" and writes no competency statuses.""" + test_path = "xapi_db_load/tests/fixtures/small_csv_config.yaml" + + with override_config(test_path, tmp_path) as test_config: + CliRunner().invoke(load_db, f"--config_file {test_path}", catch_exceptions=False) + + assert {row[-1] for row in _read_csv(test_config, "taxonomies")} == {"tags"} + # No files, so a load into an install without the competency tables + # never tries them. + for prefix in ("student_competency_statuses", "student_competency_course_statuses"): + assert not os.path.exists( + os.path.join(test_config["log_dir"], f"{prefix}.csv.gz") + ) + + +@patch( + "xapi_db_load.backends.base_async_backend.clickhouse_connect", + new_callable=AsyncMock, +) +def test_clickhouse_backend_competency_load(mock_clickhouse_connect, tmp_path): + """A competency load inserts both status tables and a "competency" taxonomy.""" + test_path = "xapi_db_load/tests/fixtures/small_clickhouse_config.yaml" + + with override_config(test_path, tmp_path, taxonomy_type="competency"): + result = CliRunner().invoke( + load_db, f"--config_file {test_path}", catch_exceptions=False + ) + + assert "ALL TASKS DONE!" in result.output + client = mock_clickhouse_connect.get_async_client.return_value + inserts = {c.args[0]: c.args[1] for c in client.insert.call_args_list} + assert inserts["student_competency_status"] + assert inserts["student_competency_course_status"] + assert {row[-1] for row in inserts["taxonomy"]} == {"competency"} + + +@patch( + "xapi_db_load.backends.base_async_backend.clickhouse_connect", + new_callable=AsyncMock, +) +@patch("xapi_db_load.backends.chdb.chdb") +@patch( + "xapi_db_load.backends.chdb.boto3", + new_callable=AsyncMock, +) +def test_chdb_backend_competency_load(_mock_boto, mock_chdb, _mock_ch, tmp_path): + """A competency load writes both status tables through CHDB.""" + test_path = "xapi_db_load/tests/fixtures/small_chdb_config.yaml" + + with override_config(test_path, tmp_path, taxonomy_type="competency"): + result = CliRunner().invoke( + load_db, f"--config_file {test_path}", catch_exceptions=False + ) + + assert "ALL TASKS DONE!" in result.output + sql = " ".join(str(c.args[0]) for c in mock_chdb.query.call_args_list) + assert "student_competency_status" in sql + assert "student_competency_course_status" in sql + assert "'competency'" in sql + + +def test_redact_credentials(): + """The secret is hidden whole, the key all but its first 4 characters.""" + sql = "s3('file', 'AKIAEXAMPLEKEY', 'very-secret', 'NATIVE')" + + redacted = redact_credentials(sql, "AKIAEXAMPLEKEY", "very-secret") + + assert redacted == "s3('file', 'AKIA****', '****', 'NATIVE')" + assert redact_credentials("key abc", "abc", None) == "key ****" + assert redact_credentials("nothing", None, None) == "nothing" + + +@patch( + "xapi_db_load.backends.base_async_backend.clickhouse_connect", + new_callable=AsyncMock, +) +@patch("xapi_db_load.backends.chdb.chdb") +@patch( + "xapi_db_load.backends.chdb.boto3", + new_callable=AsyncMock, +) +def test_chdb_failed_load_fails_the_run_without_leaking_credentials( + _mock_boto, _mock_chdb, mock_clickhouse_connect, tmp_path +): + """ + A file that fails to load into ClickHouse fails the whole run at the end, + and neither the logs nor the error show the S3 secret or the whole key. + """ + test_path = "xapi_db_load/tests/fixtures/small_chdb_config.yaml" + client = mock_clickhouse_connect.get_async_client.return_value + client.command.side_effect = DatabaseError( + "Code: 16. No such column taxonomy_type: s3('f', 'fake-key', 'fake-secret')" + ) + + with override_config(test_path, tmp_path): + result = CliRunner().invoke(load_db, f"--config_file {test_path}") + + assert isinstance(result.exception, RuntimeError) + assert "database load job(s) failed" in str(result.exception) + assert "ALL TASKS DONE!" not in result.output + assert "taxonomy" in result.output + assert "fake****" in result.output + assert "fake-secret" not in result.output + assert "fake-key" not in result.output + + +@patch( + "xapi_db_load.backends.base_async_backend.clickhouse_connect", + new_callable=AsyncMock, +) +@patch("xapi_db_load.backends.chdb.chdb") +@patch( + "xapi_db_load.backends.chdb.boto3", + new_callable=AsyncMock, +) +def test_chdb_failed_write_does_not_leak_credentials( + _mock_boto, mock_chdb, _mock_ch, tmp_path +): + """A CHDB write that fails twice raises, naming the table, with the credentials redacted.""" + test_path = "xapi_db_load/tests/fixtures/small_chdb_config.yaml" + mock_chdb.query.side_effect = Exception("Syntax error in s3('f', 'fake-key', 'fake-secret')") + + with override_config(test_path, tmp_path): + result = CliRunner().invoke(load_db, f"--config_file {test_path}") + + assert isinstance(result.exception, RuntimeError) + assert "failed twice" in str(result.exception) + assert "fake-secret" not in str(result.exception) + assert "fake-secret" not in result.output + assert "fake-key" not in result.output diff --git a/xapi_db_load/tests/test_event_generator.py b/xapi_db_load/tests/test_event_generator.py index b65dc2a..bce005c 100644 --- a/xapi_db_load/tests/test_event_generator.py +++ b/xapi_db_load/tests/test_event_generator.py @@ -6,18 +6,25 @@ import datetime import logging import re +import statistics import pytest from xapi_db_load.constants import ( + COMPETENCY_MASTERY_MEDIAN_DAYS_RANGE, DEFAULT_FIRST_CATALOG_PATHWAY_ID, DEFAULT_FIRST_PATHWAY_ENROLLMENT_ID, + DEFAULT_FIRST_STUDENT_COMPETENCY_COURSE_STATUS_ID, + DEFAULT_FIRST_STUDENT_COMPETENCY_STATUS_ID, DEFAULT_NUM_CATALOG_PATHWAYS, DEFAULT_NUM_ENROLLMENTS_PER_PATHWAY, PATHWAY_CATEGORIES, ) +from xapi_db_load.course_configs import Actor from xapi_db_load.generate_load_async import ( EventGenerator, + StudentCompetencyStatusRow, + _as_utc_datetime, to_sink_datetime, ) @@ -107,6 +114,28 @@ def test_valid_config_does_not_raise(): "wants more actors", id="actors_exceed_num_actors", ), + pytest.param({"first_tag_id": 0}, "first_tag_id must be a positive integer", id="tag_id_zero"), + pytest.param( + {"first_taxonomy_id": "1000"}, + "first_taxonomy_id must be a positive integer", + id="taxonomy_id_string", + ), + pytest.param( + {"first_student_competency_course_status_id": True}, + "first_student_competency_course_status_id must be a positive integer", + id="course_status_id_bool", + ), + pytest.param( + {"taxonomy_type": "competencies"}, + "taxonomy_type must be one of tags, competency", + id="taxonomy_type_misspelled", + ), + pytest.param({"org_prefix": "Org'"}, "org_prefix must be letters and digits", id="org_prefix_quote"), + pytest.param( + {"taxonomy_export_id": "it's"}, + "taxonomy_export_id must be a string without quotes", + id="export_id_quote", + ), ], ) def test_invalid_config_raises(overrides, expected_substring): @@ -342,3 +371,369 @@ def test_pathway_enrollments_none_without_pathways(): gen = asyncio.run(_make_enrolled_generator(num_catalog_pathways=0)) assert not gen.pathway_enrollments + + +def _competency_generator(**overrides) -> EventGenerator: + """A whole setup whose fake taxonomy is a competency taxonomy, with enough learners.""" + config = { + "taxonomy_type": "competency", + "taxonomy_export_id": "music", + "num_actors": 40, + "num_course_sizes": {"small": 3}, + "course_size_makeup": { + "small": { + "actors": 30, + "problems": 10, + "videos": 5, + "chapters": 2, + "sequences": 6, + "verticals": 8, + "forum_posts": 1, + } + }, + } + config.update(overrides) + return asyncio.run(_make_enrolled_generator(**config)) + + +def test_org_prefix(): + """org_prefix names the fake organizations, so a load can be told apart in the org filters.""" + gen = _make_generator(_base_config(num_organizations=2, org_prefix="Competency")) + gen.setup_orgs() + + assert gen.orgs == ["Competency0", "Competency1"] + + +def test_first_taxonomy_tag_and_object_tag_ids(): + """ + The first_* ids move the fake taxonomy, tag and object tag ids, tag ids are + unique across taxonomies, and object tag ids count up across courses. + """ + gen = _competency_generator(first_taxonomy_id=500, first_tag_id=1000, first_object_tag_id=7000) + + assert list(gen.taxonomy_ids.values()) == [500] + assert [t["tag_id"] for t in gen.tags] == list(range(1000, 1000 + len(gen.tags))) + object_tag_ids = [ + o["object_tag_id"] + for c in gen.courses + for o in c.get_object_tags() + ] + assert object_tag_ids == list(range(7000, 7000 + len(object_tag_ids))) + assert { + o["export_id"] + for c in gen.courses + for o in c.get_object_tags() + } == {"music"} + + +def test_object_tags_are_stable(): + """Every call returns the same object tags, so all backends write the same rows.""" + gen = _competency_generator() + course = gen.courses[0] + + assert course.get_object_tags() is course.get_object_tags() + + +def test_no_competency_statuses_without_a_competency_taxonomy(): + """A "tags" taxonomy isn't a competency taxonomy, so no statuses are generated.""" + gen = _competency_generator(taxonomy_type="tags") + + assert gen.taxonomy_type == "tags" + assert not gen.student_competency_statuses + assert not gen.student_competency_course_statuses + + +def test_taxonomy_type_defaults_to_tags(): + """Without taxonomy_type in the config, the fake taxonomy is a plain "tags" one.""" + assert "taxonomy_type" not in _base_config() + assert _make_generator(_base_config()).taxonomy_type == "tags" + + +def test_competency_statuses_follow_core_rules(): + """ + One row per learner and competency, only PartiallyAttempted or Demonstrated, + created before modified, a Partially row unchanged since created, ids from the + default first id, and every learner a known actor. + """ + gen = _competency_generator() + statuses = gen.student_competency_statuses + actor_ids = {a.id for a in gen.actors} + + assert statuses + assert [s["id"] for s in statuses] == list( + range( + DEFAULT_FIRST_STUDENT_COMPETENCY_STATUS_ID, + DEFAULT_FIRST_STUDENT_COMPETENCY_STATUS_ID + len(statuses), + ) + ) + assert len({(s["actor_id"], s["tag_id"]) for s in statuses}) == len(statuses) + assert {(s["status_id"], s["status_name"]) for s in statuses} == { + (20, "PartiallyAttempted"), + (30, "Demonstrated"), + } + for s in statuses: + assert s["actor_id"] in actor_ids + assert SINK_DATETIME_RE.match(s["created"]), s["created"] + assert SINK_DATETIME_RE.match(s["modified"]), s["modified"] + created = datetime.datetime.fromisoformat(s["created"]) + modified = datetime.datetime.fromisoformat(s["modified"]) + assert created <= modified + assert modified.date() <= gen.end_date + if s["status_id"] == 20: + assert created == modified + + +def test_competency_statuses_only_for_assessed_competencies_and_their_parents(): + """ + A learner's statuses cover competencies tagged on their courses' blocks, plus + ancestors. A parent is Demonstrated once every child the learner has a status + on is, and, unless it is tagged on a block itself, only then. + """ + gen = _competency_generator() + tags = {t["tag_id"]: t for t in gen.tags} + assessed_by_actor: dict = {} + for course in gen.courses: + tagged = {o["tag_id"] for o in course.get_object_tags()} + for enrolled in course.actors: + assessed_by_actor.setdefault(enrolled.actor.id, set()).update(tagged) + + def ancestors(tag_id): + parent = tags[tag_id]["parent_int_id"] + return set() if parent is None else {parent} | ancestors(parent) + + by_actor: dict = {} + for s in gen.student_competency_statuses: + by_actor.setdefault(s["actor_id"], {})[s["tag_id"]] = s + for actor_id, rows in by_actor.items(): + allowed = set(assessed_by_actor[actor_id]) + for tag_id in assessed_by_actor[actor_id]: + allowed |= ancestors(tag_id) + assert set(rows) <= allowed + for tag_id, row in rows.items(): + children = [r for t, r in rows.items() if tags[t]["parent_int_id"] == tag_id] + if not children: + continue + all_done = all(c["status_id"] == 30 for c in children) + if tag_id in assessed_by_actor[actor_id]: + # Tagged on a block too: rolling up only ever raises it. + if all_done: + assert row["status_id"] == 30 + else: + assert (row["status_id"] == 30) == all_done + + +def test_competency_statuses_spread_time_to_mastery(): + """ + Competencies differ in difficulty, from hours to weeks, so their time-to-mastery + boxes sit at different heights; within one competency learners still vary. + """ + gen = _competency_generator(num_actors=200, course_size_makeup={ + "small": { + "actors": 150, "problems": 10, "videos": 5, "chapters": 2, + "sequences": 6, "verticals": 8, "forum_posts": 1, + } + }) + medians = gen.competency_mastery_median_days + low, high = COMPETENCY_MASTERY_MEDIAN_DAYS_RANGE + assert all(low <= m <= high for m in medians.values()) + assert max(medians.values()) / min(medians.values()) > 10 + + tags = {t["tag_id"]: t for t in gen.tags} + leaves = {t for t in tags if not any(o["parent_int_id"] == t for o in tags.values())} + by_tag: dict = {} + for s in gen.student_competency_statuses: + if s["status_id"] == 30 and s["tag_id"] in leaves: + days = ( + datetime.datetime.fromisoformat(s["modified"]) + - datetime.datetime.fromisoformat(s["created"]) + ).total_seconds() / 86400 + by_tag.setdefault(s["tag_id"], []).append(days) + + observed = {t: statistics.median(d) for t, d in by_tag.items() if len(d) >= 20} + assert len(observed) >= 3 + fastest, slowest = min(observed, key=observed.get), max(observed, key=observed.get) + assert observed[slowest] > 5 * observed[fastest] + assert medians[slowest] > medians[fastest] + for days in by_tag.values(): + if len(days) >= 20: + assert max(days) > 1.5 * min(days) + + +def test_first_competency_status_lands_soon_after_enrollment(): + """A learner's first status comes soon after they enroll, not anywhere in the course.""" + gen = _competency_generator() + enrolled = {} + for course in gen.courses: + for e in course.actors: + when = e.enroll_datetime + if not isinstance(when, datetime.datetime): + when = datetime.datetime.combine(when, datetime.time(), tzinfo=datetime.UTC) + enrolled[e.actor.id] = min(enrolled.get(e.actor.id, when), when) + gaps = [ + (datetime.datetime.fromisoformat(s["created"]) - enrolled[s["actor_id"]]).total_seconds() / 3600 + for s in gen.student_competency_statuses + ] + assert min(gaps) >= 0 + assert statistics.median(gaps) < 48 + + +def test_course_statuses_include_attempted_not_demonstrated(): + """ + Course-level group statuses use all three stored values, including the + AttemptedNotDemonstrated that the competency level never holds, one row per + learner, competency and course, with ids from the default first id. + """ + gen = _competency_generator() + rows = gen.student_competency_course_statuses + + assert rows + assert {r["status_id"] for r in rows} == {10, 20, 30} + assert [r["id"] for r in rows] == list( + range( + DEFAULT_FIRST_STUDENT_COMPETENCY_COURSE_STATUS_ID, + DEFAULT_FIRST_STUDENT_COMPETENCY_COURSE_STATUS_ID + len(rows), + ) + ) + assert len({(r["actor_id"], r["tag_id"], r["course_key"]) for r in rows}) == len(rows) + course_keys = {c.course_id for c in gen.courses} + assert {r["course_key"] for r in rows} <= course_keys + # One course group per competency and course; no group tree columns. + groups = {(r["tag_id"], r["course_key"]): r["group_id"] for r in rows} + assert len(set(groups.values())) == len(groups) + assert not {"parent_group_id", "group_level"} & set(rows[0]) + + +def test_competency_status_agrees_with_course_statuses(): + """ + A leaf competency's row is Demonstrated exactly when some course group is, + and otherwise PartiallyAttempted, including when every course is + AttemptedNotDemonstrated, as core's rollup records it. A parent's row is at + least that, as its children may raise it. + """ + gen = _competency_generator() + by_pair: dict = {} + for r in gen.student_competency_course_statuses: + by_pair.setdefault((r["actor_id"], r["tag_id"]), []).append(r["status_id"]) + competency = {(s["actor_id"], s["tag_id"]): s["status_id"] for s in gen.student_competency_statuses} + + parents = {t["parent_int_id"] for t in gen.tags} + + assert by_pair + for (actor_id, tag_id), course_statuses in by_pair.items(): + from_courses = 30 if 30 in course_statuses else 20 + if tag_id in parents: + # Its children can raise it further, never lower it. + assert competency[(actor_id, tag_id)] >= from_courses + else: + assert competency[(actor_id, tag_id)] == from_courses + + +def test_as_utc_datetime(): + """Plain dates and naive datetimes become UTC datetimes; aware ones are kept.""" + utc = datetime.timezone.utc + assert _as_utc_datetime(datetime.date(2024, 1, 2)) == datetime.datetime(2024, 1, 2, tzinfo=utc) + assert _as_utc_datetime(datetime.datetime(2024, 1, 2, 3)) == datetime.datetime(2024, 1, 2, 3, tzinfo=utc) + aware = datetime.datetime(2024, 1, 2, 3, tzinfo=datetime.timezone(datetime.timedelta(hours=-5))) + assert _as_utc_datetime(aware) is aware + + +def _status(actor, status_id, created_day, modified_day=None): + """A competency-level row created and modified on days of January 2023.""" + def day(d): + return datetime.datetime(2023, 1, d, tzinfo=datetime.UTC) + return StudentCompetencyStatusRow( + actor, status_id, day(created_day), day(modified_day or created_day) + ) + + +def _tags(parents: dict) -> dict: + """tags_by_id from tag_id -> parent tag id.""" + return {t: {"tag_id": t, "parent_int_id": p} for t, p in parents.items()} + + +def _actor(): + return Actor(1) + + +def test_roll_up_raises_a_parent_with_its_own_status(): + """ + A parent tagged on a block has its own status; once every child is + Demonstrated, rolling up raises it to Demonstrated instead of skipping it. + """ + actor = _actor() + statuses = { + (1, 1): _status(actor, 20, 2), + (1, 2): _status(actor, 30, 3, 9), + } + EventGenerator.roll_up_statuses(statuses, _tags({1: None, 2: 1})) + + parent = statuses[(1, 1)] + assert parent.status_id == 30 + assert parent.created == datetime.datetime(2023, 1, 2, tzinfo=datetime.UTC) + assert parent.modified == datetime.datetime(2023, 1, 9, tzinfo=datetime.UTC) + + +def test_roll_up_never_lowers_a_parent(): + """A Demonstrated parent stays Demonstrated when a child is only PartiallyAttempted.""" + actor = _actor() + statuses = { + (1, 1): _status(actor, 30, 2, 4), + (1, 2): _status(actor, 20, 1), + } + EventGenerator.roll_up_statuses(statuses, _tags({1: None, 2: 1})) + + parent = statuses[(1, 1)] + assert parent.status_id == 30 + assert parent.modified == datetime.datetime(2023, 1, 4, tzinfo=datetime.UTC) + + +def test_roll_up_walks_every_level(): + """Grandparents are computed from parents that were themselves rolled up.""" + actor = _actor() + statuses = { + (1, 3): _status(actor, 30, 1, 5), + (1, 4): _status(actor, 30, 2, 6), + } + EventGenerator.roll_up_statuses(statuses, _tags({1: None, 2: 1, 3: 2, 4: 2})) + + assert statuses[(1, 2)].status_id == 30 + assert statuses[(1, 1)].status_id == 30 + assert statuses[(1, 1)].modified == datetime.datetime(2023, 1, 6, tzinfo=datetime.UTC) + + +def test_roll_up_handles_a_root_tag_with_id_zero(): + """A parent id of 0 is still a parent: only None means a root tag.""" + actor = _actor() + statuses = {(1, 1): _status(actor, 30, 1, 3)} + EventGenerator.roll_up_statuses(statuses, _tags({0: None, 1: 0})) + + assert statuses[(1, 0)].status_id == 30 + + +def test_fold_in_keeps_first_mastery_and_earliest_creation(): + """A second Demonstrated keeps the first mastery time; created is the earliest.""" + row = _status(_actor(), 30, 3, 5) + row.fold_in(30, datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC), + datetime.datetime(2023, 1, 8, tzinfo=datetime.UTC)) + + assert row.created == datetime.datetime(2023, 1, 1, tzinfo=datetime.UTC) + assert row.modified == datetime.datetime(2023, 1, 5, tzinfo=datetime.UTC) + + +def test_fold_in_partially_attempted_keeps_modified_at_created(): + """A PartiallyAttempted row was never raised, so modified follows the earliest created.""" + row = _status(_actor(), 20, 5) + row.fold_in(20, datetime.datetime(2023, 1, 2, tzinfo=datetime.UTC), + datetime.datetime(2023, 1, 2, tzinfo=datetime.UTC)) + + assert row.created == row.modified == datetime.datetime(2023, 1, 2, tzinfo=datetime.UTC) + + +def test_object_tags_drop_the_fixture_id(): + """Object tags carry object_tag_id, not the source tag's fixture id.""" + gen = _competency_generator() + + for course in gen.courses: + for object_tag in course.get_object_tags(): + assert "id" not in object_tag + assert "object_tag_id" in object_tag