def finish_record(
        self,
        calls_to_record: Callable[
            [
                List[record_schema.RecordAppCall],
                types_schema.Metadata,
                Optional[record_schema.Record],
            ],
            record_schema.Record,
        ],
        existing_record: Optional[record_schema.Record] = None,
    ):
        """Run the given function to build a record from the tracked calls and any
        pre-specified metadata.

        If existing_record is provided, updates that record with new data.
        """

        with self.lock:
            current_calls = dict(self.calls)  # copy
            self.calls = {}

            if existing_record is not None:
                for call in existing_record.calls:
                    current_calls[call.call_id] = call

            # Maintain an order in a record's calls to make sure the root call
            # (which returns last) is also last in the calls list:
            sorted_calls = sorted(
                current_calls.values(),
                key=lambda c: c.perf.end_time
                if c.perf is not None
                else datetime.max,
            )

            record = calls_to_record(
                sorted_calls, self.record_metadata, existing_record
            )

            if existing_record is None:
                # If existing record was given, we assume it was already
                # inserted into this list.
                self.records.append(record)

        return record
Run the given function to build a record from the tracked calls and any
        pre-specified metadata.

        If existing_record is provided, updates that record with new data.
        
src/core/trulens/core/instruments.py