id
stringlengths 40
40
| text
stringlengths 9
86.7k
| metadata
stringlengths 3k
16.2k
| source
stringclasses 1
value | added
stringdate 2024-11-21 00:00:00
2024-12-12 00:00:00
| created
stringdate 2024-11-21 00:00:00
2024-12-12 00:00:00
|
|---|---|---|---|---|---|
0d0b8133425f2bb2025ec7005c81dbe8c8edcf8e
|
Janus: Optimizing Memory and Storage Support for Non-Volatile Memory Systems
Sihang Liu†, Korakit Seemakhupt†, Gennady Pekhimenko*, Aasheesh Kolli‡, and Samira Khan†
†University of Virginia *University of Toronto ‡Penn State University ⋆VMware Research
ABSTRACT
Non-volatile memory (NVM) technologies can manipulate persistent data directly in memory. Ensuring crash consistency of persistent data enforces that data updates reach all the way to NVM, which puts these write requests on the critical path. Recent literature sought to reduce this performance impact. However, prior works have not fully accounted for all the backend memory operations (BMOs) performed at the memory controller that are necessary to maintain persistent data in NVM. These BMOs include support for encryption, integrity protection, compression, deduplication, etc., necessary to provide security, endurance, and lifetime guarantees. These BMOs significantly increase the NVM write latency and exacerbate the performance degradation caused by the critical write requests. The goal of this work is to minimize the BMO overhead of write requests in an NVM system.
The central challenge is to figure out how to optimize these seemingly dependent and monolithic BMOs. Our key insight is to decompose each BMO into a series of sub-operations and then reduce their overall latency through two mechanisms: (i) parallelize sub-operations across BMOs and (ii) pre-execute sub-operations off the critical path as soon as their inputs are ready. We expose a generic software interface that can be used to issue pre-execution requests compatible with common crash-consistency programming models and various BMOs. Based on these ideas, we propose Janus† - a hardware-software co-design that parallelizes and pre-executes BMOs in an NVM system. We evaluate Janus in an NVM system that integrates encryption, integrity verification, and deduplication. Therefore, all the writes issued to persistent data within a transaction become persistent when the transaction completes. The x86 and ARM ISA introduced new instructions [7, 33] that programmers can use to ensure that writes reach the persistent domain to provide durability guarantees required in crash-consistent software. However, these durability guarantees imply that writes to persistent data fall on the critical path of program execution. For example, programmers executing a database transaction expect that data modified within a transaction becomes persistent when the transaction completes. Therefore, all the writes issued to persistent data within a transaction have to reach all the way to NVM (or more specifically, the persistent domain) before the transaction completes. The x86 and ARM ISA introduced new instructions [7, 33] that programmers can use to ensure that writes reach the persistent domain to provide durability guarantees required in crash-consistent software. However, these durability guarantees imply that writes to persistent data fall on the critical path of program execution.
1 INTRODUCTION
Non-volatile memory (NVM) technologies, such as Intel and Micron’s 3D XPoint [36], offer data persistence similar to storage devices (e.g., SSD) while also delivering performance close to that of DRAM, having the potential to revolutionize persistent data management. NVMs store persistent/recoverable data in memory and allow direct manipulation of persistent data with load and store instructions rather than relying on software intermediaries (e.g., file system). An assortment of research efforts have sought to optimize recoverable or crash-consistent software (e.g., databases [4, 5, 22, 32, 58, 98], file systems [19, 24, 44, 93, 101, 109], key-value stores [5, 59, 102]) for NVMs. Crash-consistent software for NVMs exhibit a unique property – they place writes to memory on the critical path of program execution. For conventional software, only reads to memory are on the critical path, while writes may be buffered, coalesced and reordered on the way to memory for better performance. However, for crash-consistent software, the order of writes to memory is severely constrained to ensure data recoverability across failures [5, 42, 54, 62, 68]. Furthermore, crash-consistent software often has to guarantee the durability of data. For example, programmers executing a database transaction expect that data modified within a transaction becomes persistent when the transaction completes. Therefore, all the writes issued to persistent data within a transaction have to reach all the way to NVM (or more specifically, the persistent domain) before the transaction completes. The x86 and ARM ISA introduced new instructions [7, 33] that programmers can use to ensure that writes reach the persistent domain to provide durability guarantees required in crash-consistent software. However, these durability guarantees imply that writes to persistent data fall on the critical path of program execution.
bandwidth and wear out after a certain number of writes, necessi-
tating deduplication, compression, and/or wear-leveling of NVM writes [20, 21, 50, 57, 95, 113]. All these encryption, integrity pro-
tection, deduplication, and compression operations, collectively referred to as backend memory operations (BMOs) henceforth, are performed at the memory controller and significantly increase the NVM write latency. Moreover, since writes fall on the critical path of the crash-consistent software, the increase in write latency sig-
nificantly degrades application performance. In this work, our goal is to minimize the latency overhead in write operations caused by these BMOs in NVM systems.
The key challenge here is in figuring out how to optimize these seemingly dependent, monolithic operations. When viewed as depend-
dent, indivisible operations, common latency optimizations (e.g.,
parallelization) are precluded. For example, in a system with encryption and compression, performing compression before encryption is a reasonable approach, while performing them in parallel is not, as compression can change the address mapping of the compressed data which will then invalidate the encryption output that used the old address. Our key insight to optimize these BMOs is that when they are viewed as monolithic, indivisible operations, they have to be performed in series, however, if each BMO is viewed as a series of sub-operations, there exist many opportunities to optimize individual sub-operations across BMOs.
By viewing each BMO as a series of sub-operations, we can optimi-
ze them for latency using two mechanisms: (i) parallelization of sub-operations across BMOs and (ii) pre-execution of sub-operations without waiting until the NVM write reaches the memory controller. First, when BMOs are viewed as a series of sub-operations, there are many opportunities for parallelization as some sub-operations across BMOs do not have any dependencies among them and can be executed in parallel. For example, even though deduplication should happen before encrypting data, the first sub-operation of deduplication calculates and looks up the hash of the data value in the write request and can be executed in parallel with the first sub-operation of NVM encryption that uses the address of the write to generate a one-time pad (details in Section 3.1).
Second, while parallelization of the sub-operations helps speed-
ing up the BMOs, we observed that significant performance gains are still left on the table. Our key observation is that the parallel-
ized approach does not start any of the sub-operations until the write access reaches the memory controller, however, the inputs necessary for the sub-operations are available much earlier in prac-
tice. For example, undo-logging [16, 24, 35, 41] is frequently used in crash consistent NVM programs. An undo-logging transaction creates a backup copy of the data before modifying it. Before the modification takes place, the address and data for modification are already known during the backup step. Therefore, the BMOs for the update can be pre-executed as soon as the data and address become known at the backup step. We categorize sub-operations as address-
dependent, data-dependent, or both. They can be pre-executed as soon as the address and/or data is available. Pre-execution of these sub-operations decouples them from the original write and moves them off the critical path, delivering a significant performance gain.
Based on these two key ideas, we introduce Janus, a generic and extensible framework that parallelizes and pre-executes BMOs in NVM systems by decomposing them into smaller sub-operations. It provides a hardware implementation for parallelization and pre-
execution, and exposes an interface to the software to communi-
cate the address and data values of write requests before the write reaches the memory controller. However, several challenges need to be addressed both in the design of the hardware and the software interface of Janus. The challenges in the hardware design are as follows: First, the pre-executed results of the various sub-operations for the individual writes should not change the processor or mem-
ory state until the corresponding write operation happens. Second, the pre-execution should not be dependent on any stale processor or memory state to maintain correctness of the results. To address these challenges, we maintain an intermediate result buffer (IRB) in the memory controller to store the pre-executed results and isolate them from any other processor or memory state. We also track the address and data of the write operations in IRB to detect and invalidate any stale pre-execution results.
The challenges in the software interface design are the follow-
ning: First, with NVMs still being in a nascent stage of adoption, the software interface must be generic and extensible to systems with different BMOs. We only expose the address and the input data in the interface, decoupling the interface from the BMOs implemented in the system. Second, the software interface needs to be easy-to-
use and applicable to different NVM-based programs. We address this issue by providing a variety of functions that are suitable for different NVM programming models. We show that the frequently used crash-consistent software mechanisms, such as undo-logging, are particularly amenable to leveraging Janus’s pre-execution inter-
faced and programmers can manually insert these pre-execution requests to gain significant performance improvement. However, we also provide a compiler pass to automatically instrument the source code to alleviate programmer’s burden. We describe our design and our proposed solutions to these challenges in Section 4.
The contributions of this work are as follows:
• We show that it is possible to optimize the BMOs in NVM sys-
tems by decomposing these seemingly monolithic, dependent operations into a series of sub-operations.
• We propose a generic and extensible solution to optimize the sub-operations by categorizing their dependencies. First, we show that independent sub-operations across BMOs can be executed in parallel. Second, we show that the sub-operations can be pre-executed as soon as their inputs are available, which moves the latency of BMOs off the critical path of the writes.
• We propose Janus, the first system that parallelizes and pre-
executes BMOs before the actual write takes place. Janus provides a generic interface that decouples different BMOs at the hardware from the software.
• We exhibit the effectiveness of Janus by evaluating an NVM sys-
tem that integrates encryption, integrity verification, and dedu-
clication as the BMOs in the hardware. Our experimental results show that Janus achieves on average a 2.35× speedup while executing a set of applications where pre-execution requests are inserted manually over a baseline system that performs the BMOs serially. In comparison, instrumenting programs by our automated compiler pass achieves on average a 2.00× speedup over the serialized baseline.
## 2 BACKGROUND AND MOTIVATION
The new non-volatile memories (NVMs) [36, 43, 47, 103] offer persistency similar to storage devices, and performance close to DRAMs. The persistent data in NVM device can be accessed through a byte-addressable load/store interface instead of a traditional file interface.
### 2.1 NVM Crash Consistency
Programs can directly manage persistent data in NVM without using the conventional file system indirection for better performance. The persistent data maintained by the program is expected to be recoverable in the event of a failure. We refer to this requirement as the crash consistency guarantee. However, it is not trivial to ensure crash consistency. Due to performance optimization techniques, such as caching, buffering and reordering in modern processors, the order a write reaches NVM can be different from the program order. The program cannot recover to a consistent state if it fails to enforce a correct order. The x86 ISA has provided low-level primitives (e.g., clwb, sfence [33]) to writeback data to NVM and ensure the ordering between writes.
There have been many other works that provide crash consistency guarantees for NVM systems, including software-based solutions such as redo/undo logging [9, 10, 15, 30, 35, 37, 41, 94, 104], checkpointing [25, 39] and shadow paging [19, 65], and hardware mechanisms [38, 42, 51, 62, 72, 110]. The aforementioned methods diverge, while the key concept is similar, that is to enforce data writeback to NVM (e.g., using a sequence of clwb; sfence [33]) before carrying out the next step. Let’s take the commonly used undo logging method as an example. An undo log transaction typically has three steps: (1) creating a backup of the old data, (2) updating in-place and (3) committing the transaction [30, 35, 41, 62]. The backup (step 1) needs to be written back to NVM before the actual in-place update (step 2) happens; the in-place update needs to be written back before committing the transaction (step 3). Enforcing data writeback and ordering provides crash consistency guarantee, but it leaves the write latency on the critical path.
### 2.2 Memory and Storage Support
Using NVM as both main-memory and a storage device at the same time requires us to enforce the properties necessary for both transient and persistent (recoverable) data at the same time. First, due to its non-volatility, data remains on NVM even after being powered off. Therefore, attackers with physical access to the NVM device can potentially access data on NVM. To ensure the confidentiality of data, recent works encrypt data on NVM [13, 53, 70, 71, 90, 106, 107, 112]. Attackers can also tamper with the data on NVM. To ensure the integrity of data, recent works also use integrity verification techniques [71, 90, 106]. Second, NVM has a limited lifetime [36, 47]. A practical NVM system needs to overcome the limitation in lifetime. Prior works have proposed wearable-leveling [49, 55, 70] and error correction [8, 80, 99] techniques to mitigate the lifetime issue. Third, NVM has a limited write bandwidth compared to that of read [69, 89, 108]. A common way of overcoming the write bandwidth is to reduce the write traffic using compression [1–3, 11, 12, 14, 20, 29, 56, 66, 67, 82] or deduplication [21, 50, 57, 95, 113] techniques. We summarize the existing flavors of memory and storage support for NVM in Table 1. These memory and storage supports happen in the background, at the memory controller and are transparent to the processor, therefore, we collectively refer to them as backend memory operations (BMOs). In conventional programs, reads are on the critical path of execution, therefore, these BMOs optimize for read latency. For example, counter-mode encryption [23] allows the decryption to happen when the data is being read from memory; the integrity verification [27, 71, 76, 84–86, 90, 100, 106] uses caching to reduce the number of verification steps. There have been works that integrate one or multiple of these backend operations, but the integration is BMO-specific [90, 106, 113]. However, systematically integrating the BMOs in NVM systems and optimizing them for latency has been largely unstudied.
<table>
<thead>
<tr>
<th>Type</th>
<th>Backend Operation</th>
<th>Description</th>
<th>Extra Latency on Writes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Security</td>
<td>Encryption</td>
<td>Ensures data confidentiality. Counter-mode encryption is typically used in NVM.</td>
<td>40 ns [53, 85]</td>
</tr>
<tr>
<td>Integrity</td>
<td>Verification</td>
<td>Ensures the integrity of data preventing unauthorized modification. Typically, a Merkle Tree (a hash tree) is used to verify memory integrity.</td>
<td>560 ns (assume 9-layer Merkle Tree) [85]</td>
</tr>
<tr>
<td>ORAM</td>
<td>[26, 73–75, 81, 83, 96, 97]</td>
<td>Hides the memory access pattern by changing the location of data after every access.</td>
<td>~1000 ns [75]</td>
</tr>
<tr>
<td>Bandwidth</td>
<td>Deduplication</td>
<td>Reduce write accesses that have duplicated data to reduce the write bandwidth.</td>
<td>91-321 ns [113]</td>
</tr>
<tr>
<td>Compression</td>
<td>[1–3, 11, 12, 20, 56, 66, 67, 82]</td>
<td>Reduce the size of memory accesses to save the bandwidth.</td>
<td>5-30 ns [66, 67]</td>
</tr>
<tr>
<td>Endurance</td>
<td>Error Correction</td>
<td>Corrects memory error. Typical solutions include error-correcting code and pointers.</td>
<td>0.4-3 ns [63]</td>
</tr>
<tr>
<td></td>
<td>Weight-leveling</td>
<td>Spreads out writes requests to even out memory cell wear-out.</td>
<td>~1 ns [70]</td>
</tr>
</tbody>
</table>
Table 1: A description of the existing backend memory operations in NVM systems.
data if the write is not a duplicate. Finally, the integrity mechanism (e.g., Bonsai Merkle Tree [76]) updates the message authentication code (MAC) and hash tree to protect the encrypted data and counters. The ordering constraints serialize the latency from different BMOs, which is in the order of hundred nanoseconds.
Figure 1 demonstrates the latency breakdown of a write access. We assume a system with the Intel Asynchronous DRAM Refresh (ADR) technique [60] that ensures the write queues are in the persistence domain. Therefore, writes to NVM become persistent (or non-volatile) as soon as they are placed in the write queue in the memory controller, as the ADR technique can flush the write queue to NVM in case of a crash. Without any BMOs (Figure 1a), only the writeback from the cache hierarchy to the memory controller is exposed on the critical path, which typically takes around 15 ns in modern processors (e.g., Intel i7 processor [48]). The subsequent operations in the memory controller and the actual NVM device write operations do not contribute to the critical write latency. However, with BMOs (Figure 1b), both the writeback and the BMO latency are exposed on the critical path, as until BMOs are completed, the write cannot be placed in the write queue and hence cannot be considered persistent. As these BMOs add extra hundreds of nanoseconds of latency, the critical latency increases by more than 10 times.
Figure 1: Write latency (a) without and (b) with BMOs.
3 OVERVIEW
In this section, we describe our key ideas in optimizing the BMOs and providing the crash consistency guarantee.
3.1 Key Ideas
The BMOs need to execute in series if we regard them as monolithic, indivisible operations. However, we observe that BMOs can be further decomposed into smaller sub-operations. We first demonstrate decomposing two commonly used BMOs in NVM systems: counter-mode encryption [53, 71, 77, 85, 105–107, 112] and deduplication [21, 50, 57, 95, 113]. Next, we take a two-pronged approach to minimizing their latency: (1) parallelize BMOs as much as possible, and (2) pre-execute BMOs to move their latency off the critical path.
Decomposing BMOs. The counter-mode encryption [23] is an efficient encryption scheme that indirectly encrypts data blocks using unique counters. Its hardware implementation typically encrypts a unique counter together with the address of the data block into a bitstream called one-time padding (OTP), and then it XORs this bitstream with the data block to complete the encryption. To accelerate the read access, the hardware mechanism buffers these counters in an on-chip counter cache so that decryption can begin without waiting for data to be fetched from NVM, reducing the read latency. During a write access, it performs three sub-operations: (E1) generate a new counter, (E2) generate the one-time padding: \( \text{OTP} = \text{Enc(counter|address)} \), and (E3) encrypt data with an XOR operation: \( \text{EncData} = \text{OTP} \oplus \text{Data} \). As encryption begins only when
Parallelization. We observe that there are two types of dependencies between the previously decomposed sub-operations: intra-operation dependency and inter-operation dependency. Intra-operation dependency describes the dependency between sub-operations within one BMO, while inter-operation dependency describes the dependency between sub-operations between different BMOs. We demonstrate the dependencies as a dependency graph in Figure 2a. Two sets of sub-operations can happen in parallel as long as there is no incoming inter- or intra-operation dependency path from one set to another. Formally, let a node of sub-operation be \( Op \), a set of \( Op \) be \( S \), and a path from \( Op_1 \) to \( Op_2 \) be \( Op_1 \leadsto Op_2 \). \( S_1 \) and \( S_2 \) can execute in parallel, i.e., \( S_1 \parallel S_2 \), if and only if \( \forall Op_1 \in S_1 \) and \( \forall Op_2 \in S_2 \). We apply our theory to the example in Figure 2b. We mark the intra- and inter-operation dependencies with black and green edges, respectively. The intra-operation dependencies in each BMO follows the order of steps. And, there are two inter-operation dependencies: \( S_4 \) depends on \( E_1 \) as the address mapping co-locates with counter, and \( E_3 \) depends on \( D_2 \) as the memory controller cancels duplicated writes. According to these dependencies, we can circle out the sub-operations that are independent in each back-end operations (blue boxes): \( S_{E1-2} \) and \( S_{D1-3} \) are independent, and \( S_{E3} \) and \( S_{D4} \) are independent. Therefore, they can be executed in
parallel. By parallelizing groups of sub-operations, we reduce the serialization overhead. Figure 3a shows the execution timeline of an undo-logging transaction that consists of three steps (each with NVM writes): backup, update, and commit. In the serialized approach, deduplication and encryption operations are serialized for each step of the transaction. However, by parallelizing independent sub-operations, the execution latency of the three steps in an undo-logging transaction can be reduced, as shown in Figure 3b.

Pre-execution. So far, we have exploited the parallelism between BMOs by decomposing them into sub-operations. We further observe that the BMOs process two types of external inputs: the data and address of a write. These external inputs are different from any intermediate inputs generated and used between different sub-operations of the same BMO. Accordingly, apart from the inter-and intra-operation dependencies introduced earlier, external inputs introduce a new dependency, external dependency (marked as yellow arrow), that takes into account the external input of each sub-operation. A sub-operation is dependent on an external input if there exists an external dependency edge from the input. We merge nodes without any external dependency (marked in white) with their preceding nodes with external dependency (marked in gray). Figure 2b shows the simplified graph after the merge operation. A set of merged sub-operations is externally dependent on an external input if there exists an external dependency edge from the input or a path that indirectly connects the input to one/some of its sub-operation node (via inter- and intra-operation dependency edges). Formally, let the set of merged sub-operation nodes be $S$, an input (address or data of a write) be $in$, then $S$ has an external dependency to $in$ if and only if $\exists op \in S, in \sim op$.
Based on the type of external input, we categorize sub-operations into three types: address-dependent, data-dependent, and address-and data-dependent. In the example of Figure 2b, E1-E2 are address-dependent, D1-D2 are data-dependent, and E3 and D3-D4 are both address- and data-dependent. The external dependency implies that as soon as the external inputs are available, the BMOs can start execution even before the actual write access reaches the memory controller. Next, we use a code example to explain how we can exploit the opportunity of pre-executing BMOs.
Example. Figure 4 shows an example of updating an array using an undo-logging transaction that follows three steps: backup the old data, perform the in-place update, and commit the update. In this example, the address and data for the in-place update are known before the backup step (at line 1). Similarly, the address and data for the commit (validate the in-place update) are known before the commit step (at line 5). Therefore, the pre-execution of the BMOs for the in-place update and the commit steps can be overlapped with the previous steps of the undo-logging transactions, moving them off the critical path. Figure 3c shows the timeline of this pre-execution. By pre-executing the BMOs that have already been parallelized, we can gain a significant speedup.

### 3.2 Requirements
Pre-executing the BMOs before the actual write happens provides a significant benefit. However, the pre-execution should not affect the correctness of the normal execution. We summarize the requirements on the hardware support for pre-execution as follows:
1. **Does not affect processor state.** The pre-execution should not affect the processor or memory state, i.e., it should not change the data or metadata in memory, cache or register files.
2. **Invalidates stale pre-execution results.** The pre-execution should not be dependent on a stale processor or memory state, i.e., if the processor or memory state used in the pre-execution has been modified before the actual write access, the pre-execution result becomes invalid.
On the other hand, we need to provide an interface to let the software leverage the hardware support. We summarize the requirements on the software interface as follows:
3. **Extensible interface.** The software interface needs to be generic and extensible to systems with different BMOs, i.e., programs developed with the same interface should be compatible even though the BMOs change in the hardware.
4. **Programmable.** The software interface needs to be easy-to-use for different programming models that ensure crash consistency (e.g., undo/redologging), and should abstract away the memory layout.
Section 4.3 presents our solution to meet the two requirements for the hardware support, and Section 4.4 presents our software support that meets the two requirements on the software interface.
### 4 JANUS
In this section, we first describe the high-level design of our proposed system and then provide the details of the hardware mechanism (Section 4.3) and software support ((Section 4.4)).

#### 4.1 High-level of Janus
The goal of this work is to reduce the overhead of BMOs in write accesses using a software-hardware co-design. Figure 5 shows an overview of Janus. On the software side, programmers annotate the NVM programs using our software interface (step $\Phi$). To further reduce the programming effort, we provide a compiler pass that
automatically instruments the program. We present the use of Janus interface in Section 4.4 and the design of our compiler pass in Section 4.5. On the hardware side, the processor issues pre-execution requests to the memory controller during the execution of the annotated programs (step ➀). The processing of pre-execution requests consists of two parts. First, the optimized BMOs logic of Janus executes the sub-operations of the requests in parallel (step ➀). Then, it stores the temporal results in the intermediate result buffer (step ➁). When the actual writes arrive at the memory controller, they do not need to go through the BMOs, instead, they use the pre-executed results from the intermediate result buffer (step ➂) and complete the access to NVM (step ➃).
In the rest of this section, we first introduce the integration of three common BMOs in NVM systems. Then, we present Janus hardware details in Section 4.3, and the software interface in Section 4.4. Finally, we discuss the solutions to potential exceptions when integrating Janus in real systems in Section 4.6.
### 4.2 Backend Memory Operations
BMOs are integrated into memory and storage systems for different purposes, such as ensuring confidentiality and integrity, improving the lifespan, mitigating the write bandwidth limitation, etc. If we treat each of them as an entity, it seems difficult to execute them in parallel as the output of one operation flows into another. However, by breaking them down into smaller steps, we can leverage the underlying parallelism. There has been a myriad of BMOs, as shown in Table 1. To better demonstrate our idea, we take the two BMOs introduced in Section 3: encryption and deduplication, together with another popular BMO, integrity verification. Figure 6 presents the break down of the three BMOs.
#### Figure 6: The dependency graph of backend operations.
As we already described the operations in encryption and deduplication in Section 3, here we introduce the steps in an integrity verification technique. The Bonsai Merkle Tree [76] is an integrity verification scheme designed for memory encrypted under counter-mode. The leaf nodes of the tree are counters and the intermediate nodes are hashes of their child nodes. Therefore, the root hash is essentially the hash of all leaf nodes. Keeping the root hash in a secured non-volatile register ensures the integrity of the entire memory [76, 106]. Each data block is protected by a message authentication code (MAC) that consists of the encrypted data and its counter, i.e., $\text{MAC} = \text{Hash(EncData, Counter)}$. During a read access, the integrity verification mechanism compares the root hash computed from the counter read from memory with the existing root to verify the integrity. During a write access, this mechanism updates the integrity information in the following steps (Figure 6b): First, the integrity verification mechanism computes the hash of leaf nodes (step I1), and then it keeps computing higher-level intermediate nodes $\text{all the way to the root}$ (step I2-I3). The intra-operation dependencies between these steps are indicated by black arrows. In this mechanism, the write access includes this long latency of hashing. For example, if we assume each intermediate node is the hash of eight lower-level nodes, then the height of the Merkle Tree is 9 in a system with only 4GB NVM, resulting in a 360 ns latency for each write.
The integration of integrity verification with the other two BMOs introduces an extra step: the encryption operation needs to compute the MAC for Integrity verification before writing data back to NVM (step E4). Similar to the prior work, DeWrite [113], the Merkle Tree in our mechanism is built on the co-located address mapping and counter so that the metadata storage can be minimized. Therefore, the integration also introduces new inter-operation dependencies (green edges). The integrity verification support needs to take the latest counters or the remapping address (if duplicate) to update the Merkle Tree. Thus, step I1 depends on E1 and D2 (edge E1→I1 and D2→I1). To mitigate the extra latency on writes, we first apply the rule for parallelization (Section 3.1). Based on the intra-operation dependency edges, three sets of sub-operations E3-E4, I1-I3 and D3-D4 can execute in parallel as there is no edge between any pair of these sub-operation sets. Then, we apply the rule for pre-execution. We mark the nodes with external-dependency in gray. After merging the nodes without external-dependency (marked in white) to the ones with external-dependency, we find out that E1-E2 are address-dependent, D1-D2 are data-dependent, and the rest are both address- and data-dependent. These regions can be pre-executed once the dependencies are resolved. Next, we describe the hardware support that enables pre-execution.
### 4.3 Hardware Support
In this section, we describe the hardware support that meets the two requirements that we outlined in Section 3.2.
#### 4.3.1 Hardware Support for Pre-execution.
**Does not affect processor state.** The pre-execution of BMOs should not change the processor or memory state. Therefore, Janus stores the temporary results in an Intermediate Result Buffer (IRB). Figure 7c shows the fields in each IRB entry (and their sizes). IRB needs to support two basic functionalities: identify different pre-execution requests, and store and provide the pre-executed results. First, Janus uses a PRE_ID for each request in order to make sure the pre-execution requests are unique. Considering that different threads can be executing the same program and can have the same PRE_ID, each entry contains another field, ThreadID that distinguishes the requests from different threads. As recent works have proposed deferred commit [28, 41], a transaction may not
have all the updates written back to NVM before the transaction completes, causing more than one transactions with the same PRE_ID to co-exist. Each IRB entry further contains another field, TransactionID, that distinguishes pre-execution requests across different transactions. These three fields (PRE_ID, Thread_ID and Transaction_ID) are assigned by the software interface which we will introduce in Section 4.4. Using these fields, together with the physical address of the write (ProcAddr), Janus can uniquely identify pre-execution requests. Second, Janus needs to buffer pre-execution results for the actual write access when it arrives at the memory controller. The IntermediateResults field stores the intermediate results at cache line granularity. Considering the actual write access can arrive before the BMOs completes, a complete bit indicates whether all BMOs have completed or not.
Invalidate stale pre-execution results. The pre-execution becomes invalid if the memory or processor state it depends on has changed. Therefore, Janus invalidates the intermediate results from pre-execution by detecting any changes to the input memory or processor state. We summarize the potential cause of invalidation as the following two: (1) The input dependent data can be modified after the program issues the pre-execution request (e.g., due to cache line sharing, eviction or buggy program that modifies the input data for pre-execution). In order to detect any stale value used in pre-execution, Janus keeps a copy of the data value that has been used for pre-execution in the Data field of IRB entry. When the write access arrives, IRB compares the data from the write access with this copy. If they are the same, the write access can safely use the intermediate results and complete the write to NVM. Otherwise, data-dependent sub-operations have to be reprocessed using its new data. (2) Apart from the actual writes, pre-execution results buffered in the IRB may also depend on metadata structures employed by the BMOs. If these metadata structures are modified in such a way that they invalidate any prior pre-executed sub-operations, the pre-executed results must also be invalidated in the IRB. For example, pre-executing a deduplication sub-operation might identify that the current write (say to location B) is a duplicate of some prior write (say to location A). Therefore, the IRB stores the pre-execution result that the write to B is a duplicate of the value at A. However, before the pre-execution result is consumed, if an intervening write to location A changes the value of location A, then the pre-execution result in the IRB will be invalidated. In Janus, we extend BMOs to ensure that metadata changes trigger an IRB lookup and invalidates any stale pre-execution results.
4.3.2 Hardware Integration. Figure 7a shows the detailed hardware mechanism of Janus. First, the processor sends the requests to a Pre-execution Request Queue that buffers the requests (step ➊). It supports two types of requests: (1) requests that start immediately, and (2) requests that are buffered in the queue and wait until the hardware receives an explicit start command. In the latter case, the requests with coalescing addresses will be merged within the queue for better efficiency (details in Section 4.4). Second, a decoder decodes the request from the Pre-execution Request Queue into cache-line-sized operations and sends them to a Pre-execution Operation Queue (step ➋). Therefore, the pre-execution operations after the decoder stage all have one-cache-line granularity. Note that systems that perform BMOs at larger granularities (e.g., 256B block for deduplication) can also be supported by modifying the decoder. Figure 7b shows the fields in both queue entries. Third, the Pre-execution Operation Queue sends the decoded operations to the Optimized BMO Processing Logic (step ➌), and at the same time, it creates a new IRB entry. Figure 7d shows the execution flow of the Optimized BMO Logic (correspond to the design in Figure 6), where independent sub-operations can be executed in parallel and can be pre-executed if their external dependency is resolved. Finally, the Optimized Backend Memory Logic writes the pre-execution results to the previously created Intermediate Result Buffer entry (step ➍), which keeps track of the pre-execution at a cache line granularity, i.e., each entry in the buffer keeps the pre-execution result of one cache line. When the actual write access arrives, it can lookup the intermediate results from the IRB using its ProcAddr (step ❼). Note that the IRB, the Pre-execution Request Queue, and the Pre-execution Operation Queue have a fixed number of entries. If the buffer/queue is full, it drops newer requests. We discuss the software interface for our hardware mechanism in Section 4.4, and discuss the system integration and exception handling in Section 4.6. We present the hardware overhead in Section 5.2.7.
Apart from the performance overhead, maintaining crash consistency is another issue as the BMOs have their own metadata. The unconstructable metadata structures, the ones that cannot be rebuilt using the data in NVM, need to be kept up to date in NVM when data gets updated. In the BMOs we have considered, there are three structures that cannot be reconstructed: counters for encryption, the deduplication address remapping table, and the root of the Merkle Tree. A recent work [53] has proposed counter-atomicity that atomically writes back both the encrypted data and its counter to NVM in an encrypted NVM system. In this work, we extend this
atomicty to a more general metadata atomicty that writes back all unreckonstructorable metadata to NVN atomically, ensuring that the processor can still read correct data during recovery. Note that the root of the Merkle Tree is typically protected by a non-volatile register in the secured processor [76, 106]. Therefore, it does not require any metadata atomicty. In order to reduce the atomicty overhead, Janus also follows the selective method on atomicty proposed by prior work [53], where only the writes that can immediately affect the crash consistency status (e.g., write that commits a transaction) requires metadata atomicty.
4.4 Software Support for Optimization
**Extensible.** the BMOs in NVMs can vary in different systems. A program developed with a software interface should be compatible with systems using different BMOs, without a need for additional software modifications. Therefore, Janus only exposes the two fundamental external dependencies to the software: the address and data of the write access. Table 2 shows the software interface for pre-executing BMOs. Next, we explain how Janus provides an interface that can adapt to different NVM programming models.
**Programmable.** Janus provides a structure, pre_obj, that has its unique PRE_ID and keeps track of the current ThreadID and TransactionID. These three elements enables the hardware to distinguish different pre-execution requests. To perform pre-execution on a object stored in NVM, the programmer first needs to create a pre_obj and initialize it using PRE_INIT. Then, Janus provides two types of interfaces that enables programmers pre-execute the data structure that have either its address or data value available before the actual write to NVM. Functions are identified by the field Func in the Pre-execution Request Queue entry (Figure 7b).
The first type of function is for immediate execution. Janus provides three functions: PRE_BOTH, PRE_ADDR and PRE_DATA. Programmers can use them according to the availability of the dependent address or data. The input addresses are all virtual addresses from the program, and will be translated to processor-visible physical address (ProcAddr). Upon calling these functions, the pre-execution requests will be sent to the backend operation right away. Janus provides a special function, PRE_VAL, that takes a 64-bit integer value instead of the pointer to data. This function is designed to pre-execute transaction commit operations that typically set a valid bit or switches a pointer.
The second type is for deferred execution. Janus allows programs to buffer pre-execution requests using a class of functions that ends with the BUF suffix. These buffered requests can be executed together with the PRE_START_BUF function. Deferred execution provides more flexibility in scheduling the requests if the data structure to be pre-executed does not operate on a huge chunk of data, rather manipulates several elements in the structure separately. By buffering the requests for each element, the pre-execution buffer can merge the inputs before execution, leading to better efficiency.
**Guideline for using the software interface.** The hardware of Janus prevents misuse of the interface from causing any correctness issue. However, improperly placed Janus functions can lead to slowdown due to unused or discarded pre-execution. To effectively use the software interface, programmers need to be aware the following issues: (1) Between the pre-execution function call and the actual write operation, there should not be any update to the same location, or to the conflicting cache line. Although the underlying hardware mechanism can detect and fix such violations, the misuse can lead to a slowdown. (2) When using PRE_DATA alone, the data block must be cache-line-aligned (e.g., using alignment malloc). As the hardware tracks the pre_obj at cache line granularity, it is impossible to determine whether the data block shares its cache line with other data blocks without the address. Therefore, it is better to call pre-execution functions with PRE_ADDR or wait until both address and data become known if the programmer is not certain about the alignment. (3) As it takes a significant amount of time to execute the backend operations, it is better to place the pre-execution function calls sufficiently far away from the actual write. A simple and reasonable way to insert the pre-execution function call for a write request is to find the last update at that location and to insert that function right after that update.
**Examples.** Figure 8a shows an example using the immediate-execution interface. First, we observe that the value used in the update operation (val) is available right after the function call (assuming nodes are cache-line-aligned). Therefore, a PRE_DATA function can be placed at line 4 to pre-execute the data-dependent BMOs. Then, we observe that the program uses an undo log to back up the node before modification (line 11). Therefore, it is possible to issue a pre-execution request for the address-dependent BMOs by inserting a PRE_ADDR function at line 8. Using these two pre-execution requests, we move the latency from BMOs off the critical path of the actual write (line 11). Figure 8b shows an example of using the deferred-execution interface. The address and data for updates to Field1 and Field2 are already available after line 4. However, the two separate updates can be sharing a cache line.
<table>
<thead>
<tr>
<th>Type</th>
<th>Function</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Common</td>
<td>PRE_INIT(pre_obj* obj)</td>
<td>Initialize an pre_obj with a unique PRE_ID, the current ThreadID and TransactionID.</td>
</tr>
<tr>
<td>Immediate</td>
<td>PRE_BOTH(pre_obj* obj, void* addr, void* data, int size)</td>
<td>Pre-execute all sub-operations.</td>
</tr>
<tr>
<td></td>
<td>PRE_ADDR(pre_obj* obj, void* addr, int size)</td>
<td>Pre-execute address-dependent sub-operations.</td>
</tr>
<tr>
<td></td>
<td>PRE_DATA(pre_obj* obj, void* data, int size)</td>
<td>Pre-execute data-dependent sub-operations.</td>
</tr>
<tr>
<td></td>
<td>PRE_BOTH_VAL(pre_obj* obj, void* addr, int data_val)</td>
<td>Use an integer as the data. Pre-execute all sub-operations.</td>
</tr>
<tr>
<td>Deferred</td>
<td>PRE_BOTH_BUF(pre_obj* obj, void* addr, void* data, int size)</td>
<td>Buffer pre-execution for all sub-operations.</td>
</tr>
<tr>
<td></td>
<td>PRE_ADDR_BUF(pre_obj* obj, void* addr, int size)</td>
<td>Buffer pre-execution for address-dependent sub-operations.</td>
</tr>
<tr>
<td></td>
<td>PRE_DATA_BUF(pre_obj* obj, void* data, int size)</td>
<td>Buffer pre-execution for data-dependent sub-operations.</td>
</tr>
<tr>
<td></td>
<td>PRE_START_BUF(pre_obj* obj)</td>
<td>Start executing buffered pre-execution requests for pre_obj.</td>
</tr>
</tbody>
</table>
Table 2: Software interface of Janus for pre-execution.
(assuming the fields are not cache-line-aligned). The safe way to avoid invalidation of requests is to use the PRE_BUF function to buffer the pre-execution requests for each field and let them coalesce in the Pre-execution Request Queue. Then, placing a PRE_START_BUF function afterward will trigger the execution (line 10).
```c
void updateTable(int id, item_t val) {
// assume val is cache-line-aligned
PRE_DATA(&pre_obj, &val, sizeof(item_t));
sfence();
...
}
```
(a) (b)
Figure 8: Two NVM transactions optimized by Janus.
4.5 Compiler Support
The software interface of Janus is easy-to-use, but it still requires a good understanding of the program. To alleviate programmer’s effort, we provide a compiler pass that automatically instruments the program with Janus functions. 4.5.1 Compiler Design. We develop our compiler pass on LLVM 7.0.0 [46]. The compiler pass analyzes and instrument the intermediate representation (IR) of the source code in the following steps. (1) The first step is to locate the blocking writeback operations (e.g., a clwb() followed by an sfence()), as these operations are responsible for moving the write latency on the critical path. (2) The next step is to perform a dependency analysis on the writeback objects. Our compiler pass takes two different analysis approaches for the data and the address of these objects. For address, it tracks dependencies of the address generation IR instructions of the object; for data, it tracks the modification to the memory address of the object. (3) The final step is to inject Janus functions (PRE_DATA and PRE_ADDR). The compiler pass injects them as far away from the actual writeback as possible in order to provide a better performance benefit. The injection approach is different for address and data. For address, it hoists the previously tracked dependent IR instructions for address generation to the beginning of the function, and places a PRE_ADDR function after the address generation is complete; for data, it places a PRE_DATA function between the last two updates on the object. It inserts the function as close as possible to the pre-last update using the data value assigned by the last update. Note that for both data and address, if the writeback operation depends on a conditional statement (e.g., if/else), our pass conservatively inserts the pre-execution function under the same conditional statement to avoid introducing potentially useless pre-execution requests. We evaluate our compiler pass in Section 5.2.3 and compare it with our best-effort manual instrumentation.
4.5.2 Limitations. The compiler pass has the following limitations. First, it conservatively injects pre-execution functions within the same function as the writeback operation to guarantee correctness. Second, it can only inject pre-execution functions where both data and address dependencies can be resolved in compile time. For example, when a loop writes back an array of data, our pass cannot inject pre-execution for writesback in the loop due to the lack of runtime information about the loop. Third, due to the lack of dynamic memory information, our compiler pass does not handle cache line sharing. We discuss future works that can mitigate these limitations in Section 6.
4.6 Real-World Considerations
This section described various scenarios that might arise while integrating Janus into real systems.
**Unused pre-execution result.** A buggy program can issue useless pre-execution requests without issuing a subsequent write access that uses the pre-executed result. Therefore, a useless pre-execution result can get stuck in the IRB. Janus takes a twofold approach to solve this problem: (1) Add an age register to each IRB entry, and discard an entry when the age register reaches its maximum lifetime. (2) Clear all entries belonging to a certain thread when that thread terminates.
**Unused pre-execution request.** A buggy program can also issue buffered pre-execution requests without starting their execution with a PRE_START_BUF function, causing congestion in the Pre-execution Request Queue. Janus solves this problem by using a fixed size FIFO for this queue. When the queue is full, it discards the buffered pre-execution requests at the top of the queue to make space for the new requests. Note that discarding pre-execution requests will never cause any correctness issue, but can result in missed opportunities to improve performance.
**Memory swap.** OS can swap memory to the disk and swap it back later. In this case, the physical address (ProcAddr) can be different. Our solution is to let the memory controller clear out all Intermediate Result Buffer entries that belong to the address range that will be swapped out.
5 EVALUATION
5.1 Methodology
<table>
<thead>
<tr>
<th>Processor</th>
<th>Out-of-Order, 4GHz</th>
</tr>
</thead>
<tbody>
<tr>
<td>L1 D/I cache</td>
<td>64KB/32KB per core, private, 8-way</td>
</tr>
<tr>
<td>L2 cache</td>
<td>2MB per core, shared, 8-way</td>
</tr>
<tr>
<td>Counter cache</td>
<td>512KB per core, shared, 16-way</td>
</tr>
<tr>
<td>Mirkle Tree cache</td>
<td>512KB per core, shared, 16-way</td>
</tr>
<tr>
<td>Pre-exec. Request Queue</td>
<td>16 entries per core, shared</td>
</tr>
<tr>
<td>Pre-exec. Operation Queue</td>
<td>64 entries per core, shared</td>
</tr>
<tr>
<td>BMO Units</td>
<td>4 units per core (execute 4 BMOs in parallel); shared, perform at cache-line granularity</td>
</tr>
<tr>
<td>Intermediate Result Buffer</td>
<td>64 entries per core, shared</td>
</tr>
<tr>
<td>Memory</td>
<td>4GB PCM, 533MHz [40, 42, 53], tBCD/tCL/tCW/tFAW/tWR = 48/15/30/7.5/300 ns [103]</td>
</tr>
<tr>
<td>Backend Operation Latency</td>
<td>AES-128 (Encryption): 40 ns [53, 85], SHA-1 (Integrity): 40 ns [85], MD5 (Deduplication): 321 ns [113]</td>
</tr>
</tbody>
</table>
Table 3: System configuration.
We model and evaluate an NVM system that has three BMOs: encryption, integrity verification and deduplication (introduced in Section 3.1 and 4.3) using the cycle-accurate Gem5 simulator [6].
The system configuration is shown in Table 3. The memory system is backed by Intel’s ADR [60] support where all write accesses accepted by the write queue can drain to NVM in case of a failure. The encryption and deduplication mechanisms are based on recent work [113], where the encryption counter and the deduplication address mapping table share the same metadata entry to minimize the storage overhead, i.e., if data is duplicated, the metadata entry stores the address mapping, otherwise, it stores the counter. The Merkle Tree is built on the co-located counter or deduplication address mapping to protect the integrity of both. We use selective counter-atomicity [53] to ensure crash consistency of counter-mode encryption, and extend this support to the other unreconstructable metadata, including the address remapping table in the deduplication mechanism and the message authentication code (MAC) in the integrity verification mechanism. We store the root of the Merkle Tree in a non-volatile register in the secured processor, as proposed in previous works [76, 106]. Similar to the ratio in prior deduplication works [95, 113], our main results use a deduplication ratio of 0.5. We also present the performance in other deduplication ratios in Section 5.2.4. We evaluate and compare two system designs: 1. **Serialized**: Serialized backend operations. 2. **Janus**: Pre-execute the parallelized BMOs.
Our evaluation uses seven NVM-optimized transactional workloads (listed in Table 4), which are inspired by recent works [28, 42, 53]. We evaluate the serialized design with the original program that only supports metadata atomicity. Then we manually instrument Janus primitives to evaluate Janus. We compare the manual and automated instrumentation through our compiler pass in Section 5.2.3.
<table>
<thead>
<tr>
<th>Workload</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Array Swap</td>
<td>Swap random items in an array</td>
</tr>
<tr>
<td>Queue</td>
<td>Randomly en/dequeue items to/from a queue</td>
</tr>
<tr>
<td>Hash Table</td>
<td>Insert random values to a hash table</td>
</tr>
<tr>
<td>RB-Tree</td>
<td>Insert random values to a red-black tree</td>
</tr>
<tr>
<td>B-Tree</td>
<td>Insert random values to a b-tree</td>
</tr>
<tr>
<td>TATP</td>
<td>Update random records in the TATP benchmark [64]</td>
</tr>
<tr>
<td>TPCC</td>
<td>Add new orders from the TPCC benchmark [92]</td>
</tr>
</tbody>
</table>
**Table 4: Evaluated workloads.**
### 5.2 Results
This section presents the results of our evaluation that compares the performance of the two design points. The workloads are single-threaded unless explicitly mentioned.
#### 5.2.1 Single- and Multi-core Performance
In this experiment, we test the single- and multi-core performance of our design. Figure 9 presents the speedup of Janus. Janus provides on average 2.35 ~ 1.87× speedup in 1~8-core systems, respectively, over the serialized baseline system. We observe three broad trends from our results. (1) The speedup from pre-execution decreases as the number of cores increases because the memory bus contention increases when there are more threads executing in parallel, leading to a higher queuing latency in the memory controller. As a result, the ratio of BMO overhead decreases and the benefit of pre-executing BMOs also decreases. (2) The gain from pre-execution depends on the characteristics of the workloads: The speedup in B-Tree, TATP and TPCC is higher than that in Hash Table and RB-Tree. The reason is Hash Table and RB-Tree first look up the update location and then perform the update at that location. As a result, the address-dependent pre-execution request has a smaller window to execute and many times cannot complete before the actual write arrives. (3) Parallelization delivers a lower speedup compared to pre-execution because parallelization only reduces BMO latency, while pre-execution moves it off the critical path.

#### 5.2.2 Comparison with Non-blocking Writeback
In this experiment, we evaluate an ideal case where the writeback requests do not block the execution. Therefore, the BMO latency is not on writes’ critical path. We want to evaluate how much performance is lost when writes move on the critical path in crash consistent software and how much performance Janus can recover from that. Figure 10 shows the slowdown of the serialized baseline and Janus over the ideal case. We observe that the serialized baseline introduces almost 4.93X slowdown when the BMO latency falls on the critical path. Janus improves the performance by 2.35X by pre-execution and parallelization of the BMOs. However, it still incurs a 2.09X slowdown compared to the ideal scenario. There are two reasons behind the performance gap between Janus and the ideal case. First, not all BMOs can be pre-executed, as sometimes there is not enough gap between the point where the data and address are known and where the actual write happens. Second, not all pre-execution requests can complete before the actual write access arrives. We found that in our experiments, on average, only 45.13% BMOs have been completely pre-executed.

#### 5.2.3 Automated vs. Manual Instrumentation
In this experiment, we evaluate the performance of the automated instrumentation of Janus functions using our compiler pass. Figure 11 shows the speedup of Janus with the manual and automated instrumentation over the serialized baseline. In most cases, the performance
difference is within 12%. We notice two special cases. (1) The automated solution does not provide a significant performance benefit in RB-Tree and Queue. The static compiler cannot handle loops and pointers (discussed in Section 4.5), which severely affects these two workloads. (2) The automated instrumentation is slightly faster in TPCC. We found that the instrumentation enabled other compiler optimizations on the program, such as hoisting the address generation. On average, the automated solution is only 13.3% slower than our best-effort manual instrumentation. We conclude that our compiler pass effectively finds opportunities for pre-execution and improves performance.
5.2.4 Different Deduplication Ratios and Algorithms. In this experiment, we test three deduplication ratios: 0.25, 0.5, and 0.75, and compare two different hashing algorithms: MD5 and CRC-32. The design using CRC-32 follows the method in [113], which has a lower overhead. Figure 12 shows the speedup of Janus in systems using the MD5 and CRC-32 hashing algorithm. We observe that the speedup of Janus is almost the same under different deduplication ratios with MD5. In contrast, a higher deduplication ratio improves the benefit with the lightweight CRC-32. As MD5 takes around 4X longer than CRC-32, the BMOs dominate the write overhead. Therefore, the performance gain with MD5 is not impacted by the deduplication ratio. Even with CRC-32, the increase in speedup is small because BMOs contribute to most of the overhead, despite the benefit of deduplication.
Figure 12: Speedup of Janus over the serialized design with variable deduplication ratios and different algorithms.
5.2.5 Variable Transaction Sizes. In this experiment, we vary the size of the data update in each transaction from 64B to 8KB. As TATP and TPCC are real-world workloads that cannot be easily scaled without changing their semantics, we scale the first five workloads in this experiment. Figure 13 shows the speedup of Janus (parallelized and pre-executed) over the serialized baseline. We observe that the speedup from pre-execution increase with the size of transaction in the beginning, then it starts decreasing at a certain point in all workloads. In comparison to that, the speedup from parallelization keeps increasing but at a slow rate. The reasons are as follows: (1) Pre-execution benefits from a larger transaction size. However, at some point, the units and buffers for BMOs become full. The benefit is maximum at that point and then starts declining after that. (2) On the contrary, the benefit from parallelization is not affected by the BMOs resources. Therefore, the more writes the processor executes, the higher the benefit. We conclude that the speedup from pre-execution can benefit the performance the most when the write intensity is within a certain limit.
5.2.6 Variable Pre-execution Units and Buffer Size. The previous experiment has shown that the units and buffers for BMOs can become the bottleneck when processing large transactions. Therefore, in this experiment, we scale the number of units and buffers, while the size of transaction is fixed (8KB) for each of the five scalable workloads. We test the speedup of Janus over the serialized baseline with 1X, 2X and 4X of the default number of units and buffers (listed in Table 3). We also include a case with unlimited resources. Figure 14 shows that as the BMOs units and buffer size increases, the performance also increases. However, the speedup in most cases saturates when the BMOs units and buffers are no longer the performance bottleneck. B-Tree is an exception. It exhibits a high demand for pre-execution resources and can gain a significant benefit with unlimited resources.
Figure 13: Speedup of Janus over the serialized design with different transaction sizes.
Figure 14: Speedup of Janus over the serialized design with variable number of BMO units and buffer entries.
5.2.7 Overhead Analysis. Table 3 in Section 5.1 lists the size of buffers and queues that support pre-execution. The size of each Pre-execution Request Queue entry and Pre-execution Operation Queue entry is 119 bits and 103 bits, respectively. The size of each IRB entry is 148B. In Janus, we have 16 Pre-execution Request Queue entries, 64 Pre-execution Operation Queue entries, and 64 IRB entries. Therefore, the total storage overhead from queues and buffers is 9.25KB, which is 0.51% of the LLC size. The 4-wide BMOs in our design take 300k gates (according to [78, 79]), which only incurs a 0.065mm² die area with 14nm technology.
6 FUTURE WORKS
More precise compiler instrumentation. The limitation of our compiler pass boils down to the unavailable dynamic information during the static compilation time. There are two directions to mitigate this limitation. (1) Improving the dependency analysis on pointers can allow safe but more aggressive pre-execution. Techniques such as SVF [87, 88] can be greatly useful. (2) Utilizing dynamic analysis techniques can provide runtime information and enable more optimization opportunities, such as pre-executing BMOs outside of its function or outside its loop.
Tools for misuse detection. Section 4.4 has described the guidelines on using Janus interface in order to gain the best performance. Future works can provide tools to detect misuse of the interface. There are three typical misuse scenarios: (1) Modifications on pre-execution object. Tools can detect whether the pre-executed address and/or data have been invalidated between the pre-execution function and the actual write. Address invalidation can be detected
by monitoring memory de-allocation operations and data invalidations can be detected by monitoring assignments to the source of the data. (2) *Useless pre-execution functions.* Pre-execution on objects that do not affect the critical path is unnecessary. Tools can detect whether the pre-execution matches a subsequent blocking writeback. (3) *Insufficient pre-execution window.* The execution of BMOs takes a significant amount of time. The program should leave enough window between the pre-execution function and the actual write in order to maximize the benefit. A static tool can estimate the number of instructions in this window to determine whether the BMO latency can be perfectly overlapped; a dynamic tool can monitor the completion status of pre-execution functions and thereby adjust the instrumentation.
7 RELATED WORKS
Memory and Storage Supports for NVM. Prior works have proposed different optimizations for memory and storage support in NVM systems. Janus efficiently integrates these supports by the parallelization and pre-execution mechanisms, which is orthogonal to these prior works. For example, i-NVMM [13], DEUCE [107] and SeePM [112] design efficient encryption schemes for NVM systems that guarantee the confidentiality of data. Qureshi et al. [70] propose Start-Gap wear-leveling for NVM systems that effectively spreads the writes evenly to the memory cells, improving its lifetime. Error-correcting pointers [80] provide an effective way of remapping worn-out NVM cells to an error-free location. Liu et al. [53] integrate counter-mode encryption into an NVM system and ensures crash consistency by proposing counter atomicity. The authors further reduce the overhead due to counter-atomic writes by selectively applying counter atomicity to the writes that immediately mutates the crash consistency status. Osiris [106] provides confidentiality and integrity guarantees for NVM systems with encryption and integrity verification mechanisms. The authors leverage the ECC bits to detect inconsistency between the encrypted data blocks and their counters. DeWrite [113] integrates both encryption and an efficient deduplication algorithm into an NVM system. By using a low-overhead hashing algorithm and executing encryption in parallel with hashing, this mechanism achieves better performance over the previous schemes.
NVM Crash Consistency. Providing the crash consistency guarantee is another important aspect in NVM systems. Prior works have proposed and implemented a variety of software and hardware solutions to maintain crash consistency. Hardware-based mechanisms include implementations of low-level primitives such as DPO [42] and HOPS [62], and high-level hardware transactions such as Kln [110], ThyNVM [72], JUSTDO Logging [37] and ATM [38]. Software-based solutions, such as NV-Heaps [16], Mnemosyne [94], REWIND [10], Intel’s PMDK [35], LSNVMM [31], etc., abstract away the low-level crash consistency mechanism and provide a high-level software interface for programmers to manage their persistent data. There are also NVM-optimized file systems, such as Intel’s PMFS [24], BPFS [19], NOVA [104], and SCMFS [101]. Janus can be integrated with these crash consistency mechanisms to improve performance. For example, NVM transactions can overlap BMOs latency with other transactional steps using our pre-execution technique.
Compilers and Tools for NVM. There have been works on compiler support and toolchains for NVM systems. Atlas [9], SFR [28] and IDO [52] provide compiler supports that automatically convert the program into failure-atomic regions based on multithreading synchronization primitives, and thereby guarantee crash consistency. The conversion approaches in these works follow the typical NVM transaction programming models. Therefore, it is possible to integrate Janus interface into these compiler techniques. Yat [45], Pmemcheck [34] and PMTest [54], provide tools to detect crash consistency bugs in NVM-based programs. These tools can be extended to detect the misuse of Janus software interface and the mistakes in enforcing metadata atomicity.
Pre-execution in Conventional Processors. There have been pre-execution techniques for conventional processors to reduce LLC misses. The run-ahead execution technique aims to exploit memory-level parallelism in a large instruction window [61]. Speculative precomputation techniques generate helper threads to generate new cache misses [17, 18, 111]. These techniques pre-execute at a coarse granularity of code blocks or instructions. In comparison, Janus exploits pre-execution within each write access by pre-executing its BMOs. Also, these prior works require invasive modification to the out-of-order core, while the hardware modifications of Janus are contained within the memory controller.
8 CONCLUSIONS
In this work, we show that backend memory operations (BMOs), e.g., encryption, integrity verification, deduplication etc., necessary for NVM systems can cause a significant performance degradation as they increase the latency of writes that lie on the critical path. To reduce these overheads, we seek to parallelize and pre-execute the BMOs in NVM systems. We propose Janus, a general and extensible software-hardware approach to mitigate the overhead of BMOs. Over a suite of crash-consistent NVM applications, we observe that Janus achieves 2.35x and 2.00x speedup over a serialized baseline NVM system by manual and automated instrumentation of Janus primitives. We hope that Janus will open up new research opportunities in optimizing backend memory operations and will be integrated into real NVM systems.
ACKNOWLEDGMENT
We thank the anonymous reviewers, Yizhou Wei and Vinson Young for their valuable feedback. This work is supported by NSF grants award 1822965 and 1566483, and the SRC/DARPA Center for Research on Intelligent Storage and Processing-in-memory (CRISP).
REFERENCES
|
{"Source-Url": "http://www.cs.virginia.edu/~smk9u/Liu_Janus_ISCA19.pdf", "len_cl100k_base": 15456, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 49100, "total-output-tokens": 16288, "length": "2e13", "weborganizer": {"__label__adult": 0.0005364418029785156, "__label__art_design": 0.0005254745483398438, "__label__crime_law": 0.0004715919494628906, "__label__education_jobs": 0.0006604194641113281, "__label__entertainment": 0.00012165307998657228, "__label__fashion_beauty": 0.00025177001953125, "__label__finance_business": 0.000370025634765625, "__label__food_dining": 0.00045013427734375, "__label__games": 0.0013322830200195312, "__label__hardware": 0.01531982421875, "__label__health": 0.0006961822509765625, "__label__history": 0.0004677772521972656, "__label__home_hobbies": 0.00018584728240966797, "__label__industrial": 0.001102447509765625, "__label__literature": 0.00026035308837890625, "__label__politics": 0.0003635883331298828, "__label__religion": 0.0008325576782226562, "__label__science_tech": 0.2203369140625, "__label__social_life": 7.539987564086914e-05, "__label__software": 0.011383056640625, "__label__software_dev": 0.74267578125, "__label__sports_fitness": 0.0004134178161621094, "__label__transportation": 0.0010366439819335938, "__label__travel": 0.0002551078796386719}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 70204, 0.02407]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 70204, 0.47061]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 70204, 0.89475]], "google_gemma-3-12b-it_contains_pii": [[0, 4962, false], [4962, 12062, null], [12062, 17702, null], [17702, 22348, null], [22348, 27961, null], [27961, 33804, null], [33804, 39426, null], [39426, 46361, null], [46361, 52243, null], [52243, 57855, null], [57855, 63466, null], [63466, 70204, null], [70204, 70204, null], [70204, 70204, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4962, true], [4962, 12062, null], [12062, 17702, null], [17702, 22348, null], [22348, 27961, null], [27961, 33804, null], [33804, 39426, null], [39426, 46361, null], [46361, 52243, null], [52243, 57855, null], [57855, 63466, null], [63466, 70204, null], [70204, 70204, null], [70204, 70204, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 70204, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 70204, null]], "pdf_page_numbers": [[0, 4962, 1], [4962, 12062, 2], [12062, 17702, 3], [17702, 22348, 4], [22348, 27961, 5], [27961, 33804, 6], [33804, 39426, 7], [39426, 46361, 8], [46361, 52243, 9], [52243, 57855, 10], [57855, 63466, 11], [63466, 70204, 12], [70204, 70204, 13], [70204, 70204, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 70204, 0.20197]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
b5565d64a07327d26f74923c2071b8d0e7fbcc9e
|
Court Vision: An application to measure the performance of Wheelchair Basketball players
Ayush Jain
HCI-E MSc Final Project Report 2018
UCL Interaction Centre, University College London
Supervisor: Dr. Catherine Holloway
Project report submitted in part fulfilment of the requirements for the degree of
Master of Science (Human-Computer Interaction with Ergonomics) in the Faculty of Brain Sciences,
University College London, 2018.
NOTE BY THE UNIVERSITY This project report is submitted as an examination paper. No responsibility can be held by London University for the accuracy or completeness of the material therein.
Contents
1. Abstract .......................................................................................................................... 4
2. Introduction .................................................................................................................... 4
3. Background ..................................................................................................................... 5
3.1 Performance Analysis ............................................................................................... 5
3.1.1. Body worn devices .......................................................................................... 5
3.1.2. Vision based/external systems ........................................................................ 6
3.2 Vision-based tracking systems .................................................................................. 6
3.3 Sensor based tracking systems .................................................................................. 7
3.4 Visualization ............................................................................................................. 8
4. Design ............................................................................................................................. 10
4.1 Functional Requirements ......................................................................................... 10
4.2 Iterative Design Process ......................................................................................... 10
4.3 Architecture Overview ............................................................................................ 11
4.4 Initial Sketches .......................................................................................................... 13
4.5 Tracking .................................................................................................................... 13
4.5.1 Player Tracking ................................................................................................. 13
4.5.2 Ball Tracking .................................................................................................... 14
4.6 Data capture .............................................................................................................. 14
4.7 UI design principles .................................................................................................. 15
4.8 Initial high-fidelity prototype .................................................................................... 15
4.9 Implementation details .............................................................................................. 15
4.10 Visualizations ........................................................................................................... 20
5. Initial Evaluation and User Testing ................................................................................ 22
6. Modifications ................................................................................................................... 24
7. Final evaluation ............................................................................................................... 24
8. Discussion ....................................................................................................................... 26
9. Limitations ....................................................................................................................... 27
10. Conclusion and Further work ....................................................................................... 28
11. Appendix ....................................................................................................................... 29
11.1 Technical Implementation Details .......................................................... 29
11.1.1 Ball Tracking .................................................................................... 29
11.1.2 Baskets scored ................................................................................. 29
11.1.3 Court-Vision system ........................................................................ 30
12. References ............................................................................................. 37
1. Abstract
Over the last few years, sports analytics has become an increasing area of research and development. It is a collection of relevant data which when presented properly can provide a competitive advantage to a team or individual [71]. Sports analytics was brought to the public eye by the movie Moneyball [72] which was an adaptation of a book by Michael Lewis by the same name. Nowadays, teams from all sports are spending huge amount of money to gather relevant data which can be later analyzed for performance improvement. This has led to increasing number of companies building software and providing services for this purpose. These software are often expensive and require high computational power which makes them impractical to small teams and clubs.
In this project, I explored the possibility to creating a system for measuring the performance in wheelchair court sports. Wheelchair basketball, being one of the most common wheelchair court sports, was chosen for this purpose. Outcome of the project is “Court Vision”, a low-cost prototype for tracking players and presenting the captured data in an efficient manner to coaches and players. Court Vision is created with the aim to help the teams in improving their performance. An iterative design process was used for developing the system and various computer vision techniques and sensors were explored for tracking of players and the ball.
Author Keywords
Wheelchair basketball; Performance measurement; Tracking;
ACM Classification Keywords
HCI; Information interfaces
MSc Contribution Type
Design / Artefact
2. Introduction
Wheelchair sporting events were first introduced as part of rehabilitation program for individuals following spinal cord injury in Second World War era [27]. Since then, the popularity of wheelchair sporting events has increased with many competitive events worldwide. Wheelchair basketball is one of the most popular wheelchair sporting events. It is both a mainstream game in which wheelchair users and non-wheelchair users can participate in a team and is also played part of Paralympics Games as well, where teams are entirely composed of disabled people.
Quality of life (QOL) in people with physical disabilities has been widely studied across various fields of social, medical and behavioral sciences [49, 50]. The aim of these efforts is to understand and improve the Quality of Life for disabled individuals. Studies have also shown that individuals with spinal cord injury who participated in sporting events had a better satisfaction in life [30, 31]. Increased physical activities can also help in reducing the risk of cardiovascular diseases with spinal cord injury [29]. [48] suggests this is not just limited to spinal cord injury individuals but is applicable to all wheelchair users in general. Various forms of physical activity have been shown to result in substantial gains in strength and overall functioning of individuals with physical activities [48]. The same study also suggested that the wheelchair basketball players become more confident about their capabilities of performing general mobility tasks. Wheelchair basketball, like other sports can improve health and wellbeing outcomes, including mental health; with a definite relationship being found between playing competitive wheelchair basketball and improved mental health [47].
Technology advancements and increased opportunities have also resulted in increased participation of people with disabilities in
various sports [28]. As of 2006 there were around 100,000 people who played wheelchair basketball worldwide [1]. These included recreational players to elite national team members. At the time of writing, the International Wheelchair Basketball Federation (IWBF) had 105 National Organizations for Wheelchair Basketball (NOWB) worldwide with its number increasing every year [2]. Even with these increasing numbers, there isn’t much support available to measure the performance of players, especially during their practice at a local level. There are various tools in the market for measuring performance of players [40, 41, 42] which are used at professional levels and at events such as the Paralympics, but they are very expensive for a local club or team. Because of the lack of tools, coaches are often not able to quantify various performance metrics. In a study carried out last year [61], researchers, while looking for future potential of fitness technologies for stamina and fatigue management in wheelchair basketball, found that the key metrics requested by the coaches for measuring the performance of players were top speed, average speed in a game, total distance travelled and position of players at different times.
This project is a logical extension of an undergraduate project done earlier this year [85]. User requirements found during research in [85] are similar to the ones mentioned in [61]. The purpose of this project is to equip coaches with a tool which is low cost and can provide much needed quantifiable data. The primary objectives of this project are to build on previous work, which explored the requirements of a system to help coaches and to contribute “Court Vision”. Court Vision tracks the location of players and the basketball during a training session or game. It can calculate a wide range of matrices such as total distance travelled by a player in a game, total number of baskets scored, and number of passes made during the game.
Various techniques in computer vision and sensors were explored to capture these details, and the resulting methods are described alongside the visualizations used to present the data back to coaches in an easy to understand way. It can help the coaches to analyze the performance of individual players. Players can also log in to the system to view their performance. So, it can be used as a performance review system as well.
3. Background
3.1 Performance Analysis
Measuring performance of players is an important aspect of any sport. It is a specialized discipline involving systematic analysis to enhance performance and improve decision making [38]. Performance analysis in sports is defined as the analysis of data or information to help in the acceleration of athlete performance [39]. It provides the athletes and coaches with objective information which is then used to optimize team and player performance. Performance analysis can be useful in many ways because, it provides information about the performance of a team or player in any game or season. It also provides an overview of team’s skills including its strength and weaknesses. And finally, it quantifies a player’s or team’s performance. Because of these reasons, performance analysis in sports has gained a lot of attention in the past few years. Various systems and prototypes have been created for this purpose. Performance measuring systems can be broadly divided into 2 types:
3.1.1. Body worn devices
Wearable fitness devices, like Fitbit are being increasingly used by people to monitor their physical activity. These devices can track information like step count, calories burnt and heart rate among other things. Although fitness wearables revenue is expected to be $26.48 billion in 2018 [77], these devices are not widely
adopted by wheelchair users [78]. Authors in [78] have argued that one of the major reasons for the low adaptation is that most of the fitness devices measure physical activities as “steps”. This leads to the misperception that the technology is not capable of measuring the movements of wheelchair users. Wheelchair based tracking systems have been explored by researchers although this work is only in its infancy. [79] introduces a concept of Chairable Computing, which among other things, explores various ways in which fitness tracking can be accomplished for wheelchair users. It also focuses on fitness tracking for wheelchair basketball players. One of the implementations of Chairable for performance measurement of wheelchair basketball players is presented in [86], where the authors have created prototype consisting of various sensors like Wi-Fi-enabled microcontroller and 9-axis IMU which measures various tracked metrics including average speed, acceleration, distance travelled and top speed. Another example is SpokeSense [76]. SpokeSense is a fitness tracker for wheelchair athletes. It consists of a variety of sensors which fit into a small, laser-cut case which is then attached to the wheelchair. These sensors measure various core metrics including speed, distance, intensity zones, acceleration and braking of wheelchair. However, both these systems are unable to locate the players at any instant which is an important requirement for game analysis.
3.1.2 Vision based/external systems
Camera based systems are currently widely used for tracking players in sports. Almost all the professional sports use vision-based tracking systems for measuring the performance of players. Although, now allowed, GPS based wearables were not allowed in competitive sports till recently, like in soccer [80]. A major limitation of GPS technology is its reliance on satellite signals restricting its use to outdoor environments only. As a result, indoor sports like wheelchair basketball and wheelchair rugby cannot utilize GPS.
Given the limitation with the GPS based tracking solutions in indoor sports, the most reliable solutions available for tracking position of players are vision-based tracking systems and sensor-based tracking systems, which are analyzed further below.
Another important aspect of performance analysis is data sharing. Data from various metrics is captured and shared with other people (coach, other players and viewers). Although, [86] found that wheelchair basketball community, in general is less concerned about the privacy of their data and athletes are motivated by competition and work done in [87] also suggest that sharing data with peers is an engaging experience, care should be taken to minimize any privacy issues. During the interviews done in [86], some of the players raised these concerns and mentioned that some control over data should belong to them and that not everyone should be allowed to view their data. During my interviews as well, the coaches mentioned that only coaches should be able to view all players’ data and it should not be visible to other players.
3.2 Vision-based tracking
Tracking of moving objects has been an area of active research in computer science, especially computer vision. It becomes particularly difficult when the sport has multiple players or fast-moving objects [36]. Basketball is one such game with 10 players at any point of time and a relatively fast-moving ball. Player tracking is an important aspect of performance analysis as well. A lot of information can be extracted by tracking a player in a field or court. In recent years, a significant amount of work has been done to analyze the players abilities and performance across a variety of sports, examples include, techniques which track players and
allow for their positions and movements to be analyzed [33, 34]. Various professional systems and prototypes have been created for different sports to analyze the performance of players [40, 41, 42]. Interplay sports [41] is one of the early professional systems created for this purpose. In this system, the analysis is done manually where all the video streams are manually annotated and then analyzed. On the other hand, SportsVU [42] uses cameras installed in a basketball court to track real-time position of the players and the ball. This tracking data is then utilized to create various metrics. Bagadus [40] is another prototype created by combining different methodologies. It uses both camera and sensors to gather data during a match and then the analytics system is used to generate meaningful information from gathered data.
Various methods have been employed for the analysis of basketball games. Primary methods include processing of Basketball match videos using computer vision techniques [9, 35]. Over the past few years, particle filters also have proved to be a powerful tool for tracking players in a game [3, 4, 5]. This is a hypothesis tracker which approximates the position of a moving object based on a set of weights. The Kalman Filter [32] is one such filter which has been used extensively for this purpose [6, 7]. Kalman Filter is used to estimate the trajectory of moving objects (players and the ball) based on previous positions. Graph techniques have also been used for tracking multiple players in [8, 9]. In the graph techniques, detections from each frame are combined to estimate the most likely trajectories of objects. This process could become complicated. Both these methods also pose other problems like camera calibration, object occlusion and synchronization issues.
With the advancements in Deep Learning (DL) especially in Convolutional Neural Networks (CNN) in recent years, a lot of research on object tracking has begun to focus on using CNN. In [45], authors proposed a model which learns to detect events in a video. These events could be a player attempting a shoot or a block by another player. Similarly, in [46] authors have proposed a method to predict the likelihood of a player making a shot. CNNs became an area of active research after the creation of AlexNet [37] which won the ImageNet competition in 2012. Both Kalman Filter and Convolutional Neural Network are used to estimate parameters from a stream of data (in this case, player and ball positions). While in Kalman Filter, the model is explicitly written in form of equations, in a CNN, no explicit model is defined initially. It is learned by looking at many examples and by using various optimization schemes to understand the best set of transformations. Because a CNN learns by looking at examples, the training requires huge amount of data. Although, Kalman Filter is easy to implement and often gives reasonably good results, it does not give satisfactory results in case of sudden movements like when a player stops a ball in flight. CNNs does not have this issue and can easily detect such changes. Although CNNs are very powerful, they are difficult to build and often require a lot of time and computational power for the model to train. Because of time constraints, the premise of CNN was not further explored in this project.
3.3 Sensor based tracking systems
Because of the constraints of GPS systems, radio frequency-based sensors are mostly used for tracking players in indoor sports. [10] introduces a new system called Wireless Ad-hoc System for Positioning (WSAP) developed by the Commonwealth Scientific and Industrial Research Organization (CSIRO) for tracking in indoor environments. Similarly, in [11] authors have used radio waves to track players in indoor basketball. But the results were found to be unsatisfactory in that the system cannot be used for real-time tracking of players. [81] investigates the validity and reliability of a radio frequency-based system for accurately tracking athlete
movement within wheelchair court sports. It uses an Indoor Tracking System (ITS) which is a wired radio frequency-based real-time location system developed by Ubisense, UK. The results suggest that the ITS is a suitable system for quantifying both static and dynamic measurements specific to wheelchair court sports. Another radio-signal-based solution called Local Position Measurement (LPM) was introduced in [83]. It relies on the distance measurements between fixed base stations and mobile tags based on the frequency modulated continuous wave principle. Comparisons between LPM and ITS was done in [84] and it was found that LPM outperforms ITS by approximately a factor of 2 in terms of accuracy and approximately by a factor of 7 in terms of sampling rate.
Recently researchers have also explored the possibility using RFID sensors for tracking players in a court game. [82] uses several radio receivers placed around the court in such a way that the entire playing area is within radio reception range of at least three receivers. The players should wear RFID tags which transmit signals. Signal triangulation is then used to determine the exact location of the players.
Bluetooth sensors can also be used for tracking purposes. With the introduction of Bluetooth Low Energy (BLE) beacons like Apple’s iBeacon [12] and Google’s Eddystone [13], objects can be tracked by creating a mesh of sensors and calculating the RSSI value of received signal and doing triangulation to get the exact location. Court Vision uses a similar Bluetooth sensor called Estimote [62] Ultra-Wide Band (UWB) Bluetooth beacons for tracking the players.
Because Court Vision is designed in a way that the player tracking is independent of the visualization and user interface, any of the above-mentioned techniques can be used for tracking the players. Once the data is available in the database, the Court Vision system is capable to calculate all the metrics and present it to the user.
3.4 Visualization
Visualization relates to different meanings within different contexts [14]. For example, there are scientific visualizations where the use of visual images aids the understanding of complex concepts. Information visualization means to create a visual representation of abstract data to amplify cognition [15]. Visualization includes information graphics such as maps and charts as well as information design which is an effective way to communicate information through visual narratives within an illustrated context [16].
In the recent years, computer generated visualizations are increasingly used in sports to enhance viewer. Fans of all sports enjoy looking at stats for their favorite teams and players. Basketball is no exception. Fans from all around the world follow their favorite team and players and enjoy looking at different stats about them. Website of National Basketball League (NBA) [51] provides stats for all the players and teams and tools like [44] are built using those stats which fans can view and follow. Similarly, for wheelchair basketball, various teams and clubs provides stats for their players. Like the British Wheelchair Basketball association provides all the stats for their matches [73] for their fans to view.
Computer-generated visualizations play an important role in performance analysis of players during matches and training. Various systems have been created for visualization of sports data. In [17] authors have created a Glyph [18] based visualization, called Matchpad for the process of notational analysis in sports whereby the important events of a match are tagged by an analyst for post-match analysis. Matchpad was created for rugby but the concept can be applied to any sport.
NBA uses SportsVU Technology [42] to track every player and generates a lot of data with this tracking. Much of the data is freely available on NBA stats website [51]. Although it captures every movement of the players as well as the ball, there remains the challenge of how to effectively visualize the captured data. Some work has been done in this area [43, 44]. [43] introduced the concept of a ‘shot chart’ which revolutionized the analytics in NBA. Shot chart is a visual representation of a player’s shot performance displayed as a heat map. Figure 1 shows shot chart of Spread variable created for two players in a game. In [44], authors introduced a tool called Buckets which interactively and simultaneously compares multiple players’ visualizations as well as shows an overview of how the shooting behavior varies across the league. Figure 2 shows the visualizations available in the Buckets tool.
Figure 1. Shot chart (Source: [43])
Figure 2. Buckets
(Source: http://buckets.peterbeshai.com/app/#/playerView/201166_2015)
The main aim of the project is to design a low-cost solution which can measure the performance of players and teams. The other objective of the project is to create visualizations for analyzing the data pertaining to individual players and team. Court Vision can be used both by the coaches and players to analyze individual performances as well as for the whole team. It can also be used by the fans of the game to view the stats of their favorite players and team. Currently available systems are high in cost and require mammoth hardware stack [75] which makes them impractical for small teams and clubs. This project was intended to reduce the implementation cost and to make it more accessible to such teams. Court Vision is a technical design project which explores various ways to measure and improve player performance. Iterative design process was used during the development cycle where the various stages of design cycle, user research, ideation, prototyping and evaluation were carried out multiple times.
4. Design
4.1 Functional Requirements
Design of the system and user interface followed on from establishing the user requirements. Initial requirements of the project came from an under-graduate project done earlier this year [85]. My project was a logical extension of this piece of work, which gathered requirements from interviews and questionnaire surveys to develop initial user requirements of a system.
Primary user requirements that were synthesized as a result were:
- The coach/players should be able to analyze the game.
- The coach/player should be able to view performance matrices like total distance travelled by a player in a match, average speed of a player in a match, total baskets scored, position of players at any point in time etc.
- The coach/players should be able to access the system from smart phones to get different stats and player profile.
- User interface which displays all the available stats in a coherent way.
Players also mentioned some additional (good to have) features like:
- Integration with Fitbit.
- Monitor heart rate during a game or practice session.
- Monitor passes and shot accuracy.
- Get a count of calories burnt during a game or practice session.
Because the system would be displaying personal information about a user, it was important that some form of user authentication should also be added to it. Also, because the system would be used by wheelchair users, who might have limited hand dexterity, the user interface should be designed in a way that it is intuitive and easy to use and should allow user to navigate through it freely without a need for formal training.
As the coach and players should be able to analyze the game, there should be a way for them to view the match later. It should be also helpful if they can pause the game during analysis. These requirements became the basis of initial development of Court Vision.
4.2 Iterative Design Process
Iterative design process helps in expediting the development process and test the design quickly. Iteration is often considered to be an integral part of design process and is believed to be a natural feature of a designer’s competency [70]. Feedback from each of the different phases of design and development can be easily looped back into the next iteration. Figure 3 shows an iterative design process cycle. This cycle is usually repeated multiple times in the entire duration of the project. Although iterative design can be included in any phase of the design process including when you want to make improvements to an existing product, it is always advisable to include it during the initial phase of product development so that any major changes can be made during the initial development cycle.
An iterative design approach was taken during the design phase of Court Vision. An initial prototype was presented to a user group of wheelchair basketball coaches and players to get their feedback and those feedbacks were included into the system in next iteration of the design cycle. During the entire development, this process was repeated twice with the initial user requirements taken from the graduation project. Then in the ideation phase, initial sketches were made, and various approaches of implementation were considered.
Figure 3. Iterative design process
These included, creating a low-fidelity prototype with no database integration but it should contain all the user interface elements (Horizontal Prototype) or creating a high-fidelity prototype with limited functionality but with integration with database and other services (Vertical Prototype) Then an initial vertical prototype was created which was later evaluated with the user group. Based on their feedback, the entire cycle was repeated. Ideation and prototyping are again iterative processes in themselves (Green arrows in Figure 3) wherein different approaches were considered and feasibility of those approaches were evaluated. Further details about user evaluation and feedback are mentioned later in the “User evaluation” section.
4.3 Architecture Overview
UWB BLE (Ultra-Wide Band Bluetooth Low Energy) beacons are used for determining the precise location of players in Court Vision. These beacons use a process called time-of-flight two-way ranging [19] which ensures the beacons can measure the exact location of an object with inch-perfect precision [20]. Beacons register the location of a player once every 0.5 seconds and this location is saved in Estimote cloud. All the Estimote beacons are registered to an email address. User can create an Estimote cloud account using the same email address. This helps in managing the beacons as well as fetching the data from the beacons.
Court Vision reads the player’s co-ordinates from Estimote cloud and saves it locally in a relational database. Court Vision server exposes RESTful APIs [21] which Court Vision UI uses to fetch data and display to the user. Players can also view their Fitbit data in Court Vision. For this, the user’s Fitbit account should be integrated with Court Vision. Detailed steps about how to integrate Fitbit account with Court Vision is present in the Appendix section. An overview of architecture is shown in Figure 3.
Figure 3 shows three servers sending data to Court Vision application. They are, the Estimote cloud, PubNub server and Fitbit server. The “black” Bluetooth symbols around the court represent the beacons attached on the court while the “blue” symbols represent the players. As mentioned above, Estimote cloud saves players’ location co-ordinates and sends that data to Court Vision application using RESTful APIs [21]. Similarly, Fitbit APIs are used to get player’s fitness data. Although, the Fitbit data is not stored in the Court Vision database and the APIs are directly called from the UI, Figure 3 shows a connection between the Fitbit server and Court Vision application server. This is because Fitbit client ID is saved in Court Vision database and is mandatory to query the data from Fitbit server. Fitbit client ID is created by the user from Fitbit website and can be saved in Court Vision application from the user profile page. Further details about this process are mentioned in the Appendix section.
A Raspberry Pi is attached to a camera and is placed near the court to calculate the position of the ball. These co-ordinates are sent to a PubNub [69] cloud server. Details about the PubNub are mentioned in the next section. PubNub is a light weight publish subscribe framework which can be used to transmit data between clients and servers. PubNub is preferred over REST APIs here because Raspberry is not powerful enough to host REST APIs. Also, because PubNub uses publish/subscribe architecture, the client does
not need to constantly poll the server to fetch the data.
Once the data is stored in the Court Vision database, the web application can request it as per need to show the data to a user. The communication between the client and Court Vision server is again handled via REST APIs as shown in Figure 3. The user interface of Court Vision is developed using AngularJS [22] and Bootstrap [23] frameworks. The backend of the application was created in the Java Programming Language [24]. Java is a high-level programming language used extensively in software development [25].
4.4 Initial Sketches
During the ideation phase, I created some sketches to put my thoughts on paper. I came up with various designs. Most important components required on homepage were – an area to view player position during match (live view), statistics of current match and an option to select matches from a list. Figure 9 shows three different designs highlighting these three components.
Figure 9. Initial Sketches
4.5 Tracking
4.5.1 Player Tracking
Player Tracking is done by using Estimote BLE (Bluetooth Low Energy) location beacons. Multiple beacons are attached to the basketball court where they automatically map and create a floor plan. In this mapping phase, they calculate their relative positions with each other and overall dimension of the court. Once the mapping is done, the static beacons (attached to the court) can track and get the precise x and y co-ordinates of other moving beacons (attached to players’ wheelchairs) within the space. The mapping is done only once, and the same floor plan can be used later if the position of the beacons does not change.
4.5.2 Ball Tracking
Tracking the position of the ball was one of the important aspects of the project. Ball tracking would help in calculating the number of passes as well as showing it in the live game.
Ball Tracking is done using a Raspberry Pi camera. Single camera can determine the position of ball because the radius of the ball is known. The camera should be placed at a distance where it can capture the entire basketball court.
A Raspberry Pi camera V2 module has a Horizontal Field Of Vision (HFOV) of 62.2° [66]. Width of standard wheelchair basketball court is 28 meters. So, if the camera is placed at approximately 23.2 meters it will be able to capture the entire view of the court (Figure 4). The Vertical Field Of Vision (VFOV) of the raspberry pi camera is 48.8° [66], which means it can easily capture the top of the baskets, which is 3 meters.
Ball tracking consists of 2 different steps:
1. **Getting the distance of the ball from the camera** – To find the distance of the ball first the perceived focal length of the camera lens was found. Triangle similarity is then used to find the position of the ball. To find the perceived focal length, first the ball was placed at a known distance D from the camera and a picture of it was taken. Then, the apparent width of the object in pixels was measured (P). The perceived focal length of the camera was then found using the formula \( F = \frac{P \times D}{W} \), where W is the diameter of the ball. Once the perceived focal length of the lens was found, the same formula was applied to get the distance of the ball from the camera. The distance \( D' \) at any time now is, \( D' = \frac{F \times W}{P'} \). Here, \( P' \) is the width of the object which is calculated at any time instant. OpenCV [74] is used for finding the width of the object in pixels (\( P' \)).
\[
\tan (31.1) = \frac{14}{x}
\]
\( x \approx 23.2 \text{ m} \)
**Figure 4. Position of camera from court**
After calculating the ball position, these positions should be sent to Court Vision database which done using PubNub. Further details are described in next section, “Data capture”.
2. **Getting the angle of the ball from the center of the camera** – Trigonometry is used for calculating the angle of the ball from the center of the camera. Distance of the camera from the center of the court is already known. For every frame captured in the camera, the distance of the ball from the camera is determined, as described above. The angle between the center of the court and ball is calculated using OpenCV. Given these variables the angle between the camera and ball is calculated. Further details are described in the Appendix section.
**4.6 Data capture**
**Data from Estimote cloud** – Estimote exposes REST APIs to fetch data from the cloud [68] which provides beacons X and Y co-ordinates. Court Vision calls these APIs at regular intervals and
these co-ordinates are saved in the Court Vision database in form of Events. Further details about the database schema is present in the Appendix section.
**Data from ball tracking and baskets scored** – Ball tracking and counting number of baskets uses a Raspberry Pi and Arduino boards respectively which are not part of Estimote cloud. For fetching the data from both, Raspberry Pi and Arduino, PubNub [69] is used. PubNub is a real time publish subscribe framework. It offers the capability to transfer messages from publishers to subscribers in less than 0.25 seconds. As PubNub is a publish subscribe framework, objects from where the data is sent, Raspberry Pi and Arduino in this case, becomes the publisher. They publish the data to the PubNub cloud. Court Vision system is the subscriber that receives the data from PubNub cloud. PubNub offers push notification instead of polling, so that the subscriber doesn’t have to query the PubNub cloud at regular intervals. Instead the cloud APIs notify the subscriber whenever a new message is received.
Raspberry Pi and Arduino constantly publish data and Court Vision reads and saves it in the database from where it is further used.
**4.7 UI design principles**
As the users of the system are mainly wheelchair users who might have limited hand dexterity, it is important that the user interface is designed in a way that is intuitive and easy for the players and coaches to use. Following design principles were used throughout the design:
1. User should get feedback for every action [67].
2. There is sufficient spacing between the different controls of the system.
3. There is an option for the user to increase the font size.
4. Personalized data for coaches and players, so they don’t have to search for relevant details.
5. Use of consistent formatting for all displays [67].
6. Minimum user interaction so that there are minimal chances of error [67].
7. All the error messages should be appropriately displayed to user and wherever possible, there should be an option to recover from it.
Further details about these design principles are described in the “Implementation details” section.
**4.8 Initial high-fidelity prototype**
Once the initial sketches were created, I started working on an initial prototype. The idea was to create an initial version which can be shown to the user group to get some feedback early in the development cycle. This approach proved to be helpful as I got valuable feedback from the users which later helped in finalizing the features. The initial version contained limited features with options to create an account, view live games and track the position of players and ball at any point. I created dummy data for player and ball position for demonstration purposes. Results from the initial evaluation are presented in the next section “Initial Evaluation and User Testing”.
**4.9 Implementation details**
Instead of creating native mobile apps, the user Interface is created as a web application which renders perfectly in desktops as well as in mobile devices. This has tremendously decreased the overall development time and will reduced the maintenance effort.
The entire application is divided into various sections:
- **Login** – As Court-Vision contains personal information about players and coaches, all
users must first authenticate themselves before accessing other modules of the system. This also helps in showing personalized content to the user. Players would like to view their performance metrics first while coaches would like to focus more on team performance. Personalization helps in showing relevant content based on user profile, in this case coach and player. Personalization also impacts user’s decision-making stages [26] which can help coaches make fast decisions during a game. Figure 4 shows Court Vision login page.
- **Home** – Home page contains information about matches. It provides condensed stats like total baskets scored, top scorer in the game, game duration and pass accuracy about the current game. It also shows quarter specific stats like pass accuracy in different quarters. Figure 6 shows game stats available on home page. It also contains details about previous matches and links to move to other pages. One section of the home page will contain a view of the current match. User can select any previous game and it will display players’ movements over a period. User can also pause the game to analyze players’ positions. This will help the coaches to analyze the game in a better way. Figure 5 shows the live view of the court with player positions in real time. personalized information about that user.
- **Profile** – This page contains details about a player’s personal information like username, age, height, option to enable Fitbit integration, option to change password and option to request access other player’s data (more details on requesting access feature is present in the “Modifications” section).
- **Match details** – This page provides further details about the game. It provides a personalized view of data. For a player, it shows various visualizations stating the performance of the player in the match. These visualizations include, speed of player at any instant, average speed in the game, total distance travelled in the game. It also lists down the average speed of player and total distance travelled in different quarters of the game. If the player has enabled the Fitbit integration, this page will also show the heart rate of the player during the game as well as total calories burnt during the game. It also shows the position of player during the during in form of a heat map. Figure 7 shows a match details page for a player. This page also shows the overall player statistics like total distance travelled in the game, total baskets scored and average speed of the player in the game (Figure 9). A Coach could see all the above visualizations for all the players except for Fitbit data. Figure 8 shows match details page for a coach.
- **My Team** – This section is available to a coach only. This section is present towards the end of the home page. It lists down all the members of the team. Coach will have the option to go to an individual’s players profile from this page. If a player has requested access to view other player’s data, this page has the option for the coach to accept or reject his/her request. For more details about requesting access, please see “Modifications” section. Figure 17 shows My Team page.
Figure 4. Court Vision login page
Figure 5. Live position of players
Figure 6. Match specific stats (Pass accuracy in quarters, game duration, number of baskets)
Figure 7. Match stats (Player specific)
Figure 8. Match details (Coach view)
Unnecessary user interaction increases chances of error [67]. So, Court Vision is developed in a way to keep the user interaction to minimal level but still provide all the relevant details to the user. All the features are clearly segregated and defined in separate pages which makes it easier to navigate. Sufficient spacing is provided between all the controls to reduce the number of accidental clicks.
Every user must sign in to access Court Vision. This adds a level of security as well as helps in personalizing the content for the users. A player is usually concerned about his/her performance while a coach is interested in the performance of the entire team. Adding user roles and mandatory sign in helps in displaying personal and team specific data to player and coach respectively. Consistent formatting is used across all components to make the user interface look clean.
Initially, it was planned to add a search feature in the application. But later it was left out from the design because of three reasons:
1. Court Vision is not a data intensive application.
2. It could confuse users as to what he/she can search in it.
3. Search is hard to implement, and it was not feasible to implement in the given timelines.
When asked about if search would be an important feature in the application, one of the coaches said:
“It doesn’t look that it (search bar) is necessary here. Anyways [s]he can select a match from the list and view all the details [...]”
Ease of use is another important feature which was considered during the design of Court Vision. While viewing the games, user has the option to pause the game which makes it very convenient, especially for coaches when they want to analyze the game by checking the position of players with respect to ball at any instant. Another important feature is the option to view the game for any specific duration. The application provides a slider next to the live match window in which user can select any time duration and view the game only for that duration. This would help the coaches while analyzing the game.
4.10 Visualizations
One of the primary objectives of the project is to present the collected information to the coaches in an easy to understand way using different visualizations. Most of the visualizations created for this purpose are Cartesian graphs. These graphs are powerful because they not only allow the viewer to perceive the x and y values separately but, also provides the ability to understand the relationship between the 2 values [64]. For example, the graph in Figure 10 provides the comparison of the speeds to 2 players during a game. From this graph it is easy to get the speeds of a player at any instant but also to draw a comparison between the speeds of the 2 players. Similarly, Figure 11 is another Cartesian graph which shows the heart rate of a player during the game. Heart rate data is fetched from Fitbit APIs.

Figure 10. Comparison of Speeds of two players in a game
Figure 11. Heart Rate of player during different times in the game. Fetched from Fitbit
Figure 12. Heatmap of player’s position during the game
Heatmaps can be helpful in viewing certain kind of data. They can serve as illustrations of a user’s viewing behavior and distribution of attention. But they must be used cautiously as they communicate data but cannot explain or analyze it [65]. Heatmaps should always be accompanied with other analysis [65] which is done in Court Vision application. Heatmap of player position is shown in Figure 12. It gives the coach an indication of where the player is moving in the game which was one of the primary requirements that came up during initial evaluation phase of the project. This information is complemented by other information about the player like the total distance travelled and average and top speed of player in the game.
5. Initial Evaluation and User Testing
For the initial evaluation of the high-fidelity prototype, I met 2 coaches of a local wheelchair basketball team. During the conversation, I inquired about how they currently measure the performance of their players as well as asking them for feedback on the initial design. They mentioned that all the measurements are currently done manually. They use a mobile app called Basketball Stats Lite [63] where all the details should be added manually. During the game, one of the coaches would keep a track of all the passes made, baskets scored and add those to this app. They also mentioned that there is always a chance of error in this process and there is no way to avoid it. One of the features which they liked in this app was the option to export all the data in an excel sheet which they email to all the players after the game. Players can then analyze their performance in the game by checking this sheet. Figure 13 shows are sample data sheet.
Both the coaches really liked the idea of Court Vision. They were excited to see the features of the initial prototype. Some of the comments from the coaches were:
“[...] This will be really helpful for analyzing the performance. What I really liked is the option to view the entire game later. Option to pause the game is really cool.” – Coach 1.
“Currently we use beep test to measure the top speed of a player, which is not very accurate as it is measured only for a short distance. If we can get the top speed and average speed of player in a game, that would really help [...]” – Coach 2.
They also pointed out some potential issues and provided some feedback on how to rectify those issues.
- Initially, all the players were able to see other player’s data. As per the coaches, this could create some issues especially when the team loses a game with a minor difference.
“I can see that the views are similar for the coach and players. Only a coach should be able to view other player’s data. A player should only view his own data. Otherwise players tend to pick on a particular player if he/she did not perform well in a match and we lost that match with a minor difference.” – Coach 1.
There was no concept of different teams in the initial prototype. So effectively there will be only one team in the system. This would mean that only players from one team can be tracked in the game. To cater this requirement, a concept of different teams should be introduced.
- During signup only one person should be able to create an account as a coach. Others can only signup as players.
- Users can request permission to view other player’s data and it is on the discretion of coach whether he/she wants to allow that.
- If possible, there should be an option to export data as an excel sheet as our players are used to reading stats from an excel sheet.
After getting the above feedback, second cycle of iterative design process (Figure 3) started where all the feedback items were thought of and their feasibility were evaluated. Because the first 4 items were the limitations of the current prototype and the last one was an enhancement, I decided to work first on the limitations in the next iteration of Court Vision. Further details about the changes are mentioned in the “Modifications” section.
I also interviewed 3 wheelchair basketball players, one of whom was the captain of the team. I got similar feedback as I got from the coaches. They were excited to see the option to view the game later as well as the feature to pause it.
“[...] It would be helpful to watch the match afterwards [...]” - Player 1
“It would be very helpful to watch the game afterwards. So, if a referee called a foul, you can always go back and see why that happened [...]” – Player 2
When asked about the features they would like to see in the application, one of the players mentioned a way to get the energy levels during the game, which she later clarified as speed of player at different times of the game.
“Energy levels, [...] change in speed of players at different duration. So, between start of the game to versus the end of the game.” – Player 1
Almost, everyone also mentioned that these metrics should not be limited to a game, but they should be able to track these numbers over a period, like a season.
“These (metrics) are important for over a period of games like in a season.” – Player 2
6. Modifications
Based on initial feedback of the coaches, the signup process was modified. Concept of different teams was introduced in the system. Now during the registration process, user must select his/her team from a dropdown. Then the user can fill in his/her details and check a checkbox if he/she wants to register as a coach. Only one user from a team can register as a coach. Once a coach is registered for a team, the checkbox is disabled and all other users for the team will be registered as players. Figure 14 shows the signup page. Based on user profile as coach or player, he/she can see different views in the application.
Because now the players can ask for permission to view other player’s data, there should be a way to notify the coach when such requests come. For this purpose, the concept of notifications was also introduced in the second version of prototype. When a player raises a request, a notification is sent to the coach which he/she can see in the notifications (bell icon) in the header of Court Vision (Figure 16). Players can request access to view the entire data. He/she can do this from the profile’s page by simply clicking request access button. Figure 15 shows the player’s profile page with request access button. Once the player has requested access, a notification is sent to the coach and he/she decide whether to grant access or not. Figure 16 shows a notification received to coach to grant access to a player to view other player’s data. The coach can grant access to a player from my-team page. He/she can see all the requests on that page and can selectively decide to give access to specific users. Figure 17 shows the “My Team” section. Once the access is provided the player will effectively become a coach in Court Vision.
7. Final evaluation
Once these features were implemented, the second version was shown to the coaches and players. This was a discussion within a group rather than individual interviews. They were excited to see the new features and gave some good feedback. When asked about the new signup process, Coach 1 said:
“[...] This looks great. This is exactly what I was talking about last time [...]” – Coach 1
But one of the players mentioned that the current way to signing up as coach is not very secure and anyone can go and signup as a coach if the team coach has already not registered on the system. This turned out to be a genuine problem and everyone else agreed to it. She also suggested that there should be a centralized authentication system where the passwords to coaches should be sent, rather than they creating the passwords themselves so that proper check can be kept about the authenticity.
Figure 14. Signup page
Figure 15. User can request access from profile page
No changes are made around this after the feedback. This can be considered as a future work as there are a few open questions around this approach, like, how to check if the first-person registering is the coach. Additional work will be needed for integrating the Court Vision with SMTP server to send out system generated passwords as emails. One of the suggestions which came up during the discussion was to make sure that the first person to register in the system for a team is the head coach.
The users also liked the idea of using notifications. This will let the coaches know if they have any pending requests as soon as they login, rather than going to the “My Team” page.
“[…] I like the bell icon. I hope it will show me the notifications […]” – Coach 2
As the part of discussion, users were asked if they can understand the visualizations created for a match. As they are created as Cartesian graphs, they looked familiar to the users and they were able to decode them easily. They especially liked that the some of the visualizations were presenting quarter specific data which would be useful. As Player 1 suggested about the energy levels in the previous interviews, when asked about these graphs, she said:
“Yes, this would help in understanding the energy levels during the game. Now I can see my speeds in different quarters.” – Player 1
8. Discussion
Primary objective of this project was to help the coaches and players of wheelchair basketball teams to monitor and improve their performance with time. This was done by creating a high-fidelity prototype called “Court Vision”. It will cater to all the requirements of the players and coaches which were initially identified. Although there are already several systems available for this purpose in the market [41, 42], which are used in professional sports, none of them were created specifically for wheelchair basketball and are mostly used in non-wheelchair Basketball and Soccer. Court Vision is designed specifically for wheelchair basketball players which provides additional features like integration with Fitbit which was one of the initial requirements. One of the biggest advantages of Court Vision is that it is a low-cost system compared to other software available which is very important to local clubs and teams. Although, the cost of professional systems varies on the features users opt for and
it is not readily available online, typical cost of the basic version could be around $12000 per season [93]. Court Vision would cost less than 10% of this value. Most of the professional systems use computer vision techniques for tracking which makes them expensive as they require high computing power for processing. Court Vision, on the other hand, uses low energy BLE beacons and a Raspberry Pi powered camera which significantly reduces the computing power. Entire Court Vision application can easily run on a laptop or on a free cloud service which makes it an ideal low-cost substitute.
Chairables was a concept introduced in [76] and later prototypes for the same were created [79, 86]. In Chairables, various sensors were attached to the wheelchair to calculate a variety of trackable metrics. SpokeSense [76] is one such prototype which uses different kinds of sensors to measure various metrics like speed, acceleration and distance travelled for a player during a game. Court Vision extends the idea of Chairables where by attaching sensors to wheelchairs as well as in the court, it is capable of tracking players in real time. Court Vision can also be used by coaches to analyze the game by viewing the positions of players at any instant during the game. Coaches also have an option to pause the game to take a closer look at the player’s positions at any instant.
Currently, Court Vision uses Bluetooth beacons for tracking players. But, it is designed in a way that the user interface is independent of the tracking logic. So, Court Vision user interface can be a complement to the work done in [82] and [83] providing a user interface for coaches and players to view the tracking data. Court Vision also handles the data privacy issues in a unique way wherein initially only the coach will have the access to view the data of all the players, but there is an option for a player to request access to entire data. So, in Court Vision there is an option to restrict the data view as well as to share it across all players. This will address the concerns raised in [86].
Court Vision tracks multiple players at a time in a game. This creates an opportunity to explore the team dynamics of players in the game. Game mechanics and dynamics are frequently studied together and can contribute to performance measurement [88]. [89] defines game mechanics as a set of components of the game including the elements and rules of the game while game dynamics is defined as the run-time behavior of the mechanics acting on player’s inputs and outputs over time. Studies [90] have shown that ball passing networks and positioning variables can be linked to the match outcome. Notational analysis, like determining number of shots and successful passes, can also be a powerful framework to produce valid and reliable description of team’s performance [91, 92]. Court Vision is a tool which can help the coaches in determining these variables and in turn will help in performance improvement.
9. Limitations
Court Vision uses Estimote Beacons for player tracking. These beacons must be calibrated initially. During the calibration phase, they generate a floor map of the area in which they were installed. Due to some technical issues, the calibration phase did not work. Because of time constraints and lack of technical support from the Estimote team, I was not able to explore the root cause of the issue. Because of this, the player tracking did not work as intended. It would need some more exploration and help from Estimote team for it to work. But Court Vision is designed in a way that the tracking logic is loosely coupled with the user interface. So, if the issue with the Estimote beacons persist, additional methods for tracking players can be explored and the data can be fed to the Court Vision database. The user interface would work seamlessly without making any changes.
In wheelchair basketball, points are calculated based on from where the ball is shot into the basket. Currently, in Court Vision, all the points are calculated as a single value. It cannot differentiate between 2-point shot and a 3-point shot. This can be differentiated by checking the player’s position in the court when the ball was shot into the basket but because the player’s tracking is not working as expected, no further work was done in this area.
10. Conclusion and Further work
This project was intended to provide a low-cost solution for the coaches and players of wheelchair basketball teams to help them improve their performance. Court Vision does this by providing various performance metrics like the total distance travelled, average and top speed of players in the game, position of players and pass accuracy. It is also capable of providing quarter specific data which is important to determine the energy levels of players. A user interface was created for the coaches and players to view this data. The data is presented in easy to understand visualizations which makes it intuitive. It has additional features like integration with Fitbit which helps them to track their body stats like heart rate and number of calories burnt during the game.
Because of time constraints, some of the features, like player tracking did not work as expected. There were some technical issues in the initial calibration phase of Estimote beacons and because of time constraints and lack of technical support from Estimote team, the work on tracking players could not complete. Some additional effort would be needed to make the tracking work as expected. Other techniques like computer vision and Neural networks can also be explored for tracking players in the court.
Court Vision user interface does not currently support keyboard accessibility. It was not considered during the design as it was assumed that the players and coaches would be comfortable using a mouse. No feedback was provided by the users around this limitation during the user testing as well. But keyboard accessibility could be an important feature for some of the users and should be considered as a requirement for future development. Future work should also include making the user interface fully accessibility compliant.
During the first iteration of user testing, one of the coaches also requested a feature to export the data of a match to an excel sheet which the players of the team can use for analysis. Further exploration is needed to see if this could be helpful to other teams as well. Court Vision should also be tested with other teams to see if other visualizations could be added to make it more versatile.
Another limitation that was brought up during the user evaluation phase was coach signup. In the current signup process, there is a check box which a coach can check, and it will assign him/her coach user role for a team. All the users registering after that would have player user role, by default. Currently, there is no way to knowing if the first user registering in the application is a coach or not and a player has the option to register as coach if a coach has already not registered for that team. It would need some further exploration so that this entire process can be streamlined.
Fans of all sports enjoy looking at stats for their favorite teams and players. Currently, Court Vision is only meant for the coaches and players. It can be further extended to viewers and fans as well so that they can also view the stats of their favorite players and teams. This would require additional user research because some of the stats currently available to players and coaches might not be relevant to the viewers. So, another
user role like “viewer” or “fan” should be created and the content should be personalized accordingly. If Court Vision is deployed as a single cloud instance, where all the teams can register, a concept of ratings can also be introduced which will be of interest to the viewers.
Game dynamics is another area which can be further explored by using Court Vision. Although, Court Vision can be used to understand the basic team dynamics, further interactions with the coaches and players are needed to understand how it can be further improved.
It is hoped that with these further improvements, Court Vision would become a complete solution for local teams and that it would help the players and coaches to improve the performance of the team.
11. Appendix
11.1 Technical Implementation Details
Entire code of the project is available on Github at: [https://github.com/ayush04/court-vision](https://github.com/ayush04/court-vision)
11.1.1 Ball Tracking
As mentioned in 4.5.2, ball tracking involved 2 steps, first, to find the distance of the ball from the camera and second, find the angle between the camera and the ball. Figure 18 shows the position of ball and camera. Here, c is the camera, b is the center of the ball and o is the center of the court. Distance D and L and angle α is known.
By using Trigonometry, we can find the value of β.

11.1.2 Baskets scored
For calculating the number of baskets scored, HC-SR04 ultrasonic sensor [94] is used. It calculates the distance of an object by constantly transmitting ultrasonic waves and registering the time of return of these waves when they reflect from the object. An HC-SR04 sensor was attached to an Arduino board and the entire setup was put towards the end of the hoop. The distance calculated by the ultrasonic sensor was then checked against a threshold score. If the distance was below the threshold value, then it means that the ball has passed the hoop. This method is not very efficient because it is possible that the ball can directly hit the sensor without passing from the hoop. This is a limitation and should be investigated in future work. Whenever a basket is scored, the timestamp of the basket is registered. This data is then manually transmitted to Court Vision. Due to time constraints, I took code from [95] as reference.
11.1.3 Court-Vision system
Court Vision is created with an aim to provide the much-needed quantifiable data to the coaches and players of the wheel chair basketball which can assist them to improve the overall performance of the players.
The technology stack used in the implementation of the Court-Vision is:
1. AngularJS – An open-source JavaScript framework front-end web application development [22].
2. Bootstrap – A free and open-source framework for designing web applications [23].
3. Java Programming Language [24].
4. Hibernate – Object Relational Mapping (ORM) tool for Java Programming language. It provides a framework for mapping an object-oriented domain model to a relational database [52].
5. Apache Derby – An open-source relational database management system (RDBMS) [53].
6. REST APIs – Representational State Transfer APIs used for creating web services [54].
9. Google Charts – For creating interactive charts [57].
10. Fitbit APIs for Fitbit integration [58].
11.1.3.1 Server-Side Implementation
Server-side implementation is done using Java with Apache derby as the relational database. Hibernate is used as an ORM to make the code independent of database. This means that the entire application can be migrated to a different database without changing a single line of code. Only the database connection details should be changed in the hibernate properties file.
11.1.3.2 Database structure
There are 14 tables present in the application. Figure 17 shows the table schema along with their relationship with each other.
Complete database schema is available on Github along with the code.
Player / Ball co-ordinates – Positions of objects are stored as events in the system. EVENTS table stores all the data related to player’s and ball’s movements. Events are categorized into various types details of which are stored in EVENT_TYPES table. Various events are:
MATCH_START_EVENT_TYPE = 1
MATCH_END_EVENT_TYPE = 2
BASKET_SCORED_EVENT_TYPE = 3
PLAYER_POSITION_EVENT_TYPE = 4
BALL_POSITION_EVENT_TYPE = 5
QUARTER_END_EVENT_TYPE = 6
USER_ROLE_CHANGED_TO_COACH = 7
For every movement of the player an entry is made in the events table with event type 4. Similarly, for every movement of the ball, an entry is made with event type 5. X and Y co-ordinates of the object being tracked are saved with this entry.
11.1.3.3 Business logic
Every table is mapped to a data-object. Java code only interacts with these data-objects. It is the responsibility of Hibernate to update the data from these data-objects to the database. Business logic contains methods to calculate various metrics for the user to view.
Calculation of key metrics – To calculate the total distance travelled by a player in a game, distance between every 2 consecutive points is
calculated and added together. To calculate the average speed, total distance cannot be just divided by the duration of game because the game duration will include the half time and quarter breaks. This time duration should not include any time when the players were not playing such as during quarter breaks and half time. It is also possible that a player is replaced by another player during the game, so these events should be excluded when calculating the average speed of player. To calculate the actual time duration when the player played in the game, number of position events are calculated and multiplied by 2 as player position events are recorded every 2 seconds. Figure 16 shows the code snippet for calculating the average speed of player in game.
To calculate speed of a player at any point of time, the distance between 2 consecutive points are calculated and then divided by the time difference between the two events. Figure 15 shows the code snippet for calculating the average speed of player in a game.
Similarly, Figure 16 shows the code snippet for getting the total number of passes and successful passes in a game. Using these two values, pass accuracy is calculated.
```java
public static double getAverageSpeedOfPlayerInGame(long userId, long gameId) {
double distance = 0;
List<EventsData> playerEvents = EventsService.getPlayerPositions(userId, gameId);
EventsData initialEvent = playerEvents.get(0);
for (int i = 1; i < playerEvents.size(); i++) {
distance += distance(Double.parseDouble(initialEvent.getEventValue()),
Double.parseDouble(playerEvents.get(i).getEventValue()),
Double.parseDouble(playerEvents.get(i).getEventValue()));
initialEvent = playerEvents.get(i);
}
return distance==0 ? 0 : (distance/(playerEvents.size() * 2)) * 1000;
}
private static double distance(double x1, double y1, double x2, double y2) {
return Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
}
```
**Figure 15. Calculation of average speed and distance travelled by player**
Figure 16. Calculation of total number of passes and successful passes
```java
public static int[] getNumberOfPasses(long gameId) {
int numberOfPasses = 0;
int successfulPasses = 0;
long currentPlayerId = -1;
Double[] previousBallCoordinates = null;
HashMap<Long, List<Double[][]>> map = new HashMap<>();
long[] playerIds = MappingsService.getPlayersInAGame(gameId);
for(int i=0; i < playerIds.length; i++) {
List<Occurrences> positions = EventsService.getPlayerPositions(playerIds[i], gameId);
map = insertPositions(positions, map);
}
map = insertPositions(EventsService.getBallPositions(gameId), map);
for(Map.Entry<Long, List<Double[][]>> entry : map.entrySet()) {
List<Double[]> positionList = entry.getValue();
Double[] ballCoordinates = positionList.get(playerIds.length);
for(int i=0; i < playerIds.length; i++) {
if(Object.equals(positionList.get(i)[0], ballCoordinates[0])
&& Object.equals(positionList.get(i)[1], ballCoordinates[1])) {
if(currentPlayerId != -1 && currentPlayerId != i) {
numberOfPasses++;
}
}
if(previousBallCoordinates != null) {
if(!Object.equals(previousBallCoordinates[0], ballCoordinates[0])
|| !Object.equals(previousBallCoordinates[1], ballCoordinates[1])) {
numberOfPasses++;
}
} else {
previousBallCoordinates = ballCoordinates;
}
currentPlayerId = i;
}
}
return new int[]{numberOfPasses, successfulPasses};
}
```
Figure 17. Database schema
11.1.3.4 REST APIs
REST APIs are endpoints resolving to unique URIs which can be called by client to fetch or update the data in application. The application exposes various such REST APIs. Every API performs a specific task and are independent of each other. This approach is helpful because now the client-side code becomes independent of the server-side code. There is no hard-coupling between the two. This principle is called Separation of Concerns (SoC) [59]. All the APIs, except for few are authenticated APIs and requires a valid session ID. The login API returns a session ID after successful authentication and all the subsequent API calls in that session should pass that session ID in the request.
11.1.3.5 Client-Side Implementation
AngularJS and Bootstrap are used as the frameworks to develop the frontend of the system. Bootstrap helps in creating responsive layouts for the application which makes it usable on all screen sizes without writing additional code. AngularJS is JavaScript framework used for developing applications with Model-View-Controller (MVC) architecture [60].
The front-end of the application is divided into various pages. Each page represents a different view on the browser. These pages are:
- Login
- Signup
- Home
- Match details
- User profile
Each page is divided into one or more reusable elements called components. Each component represents an independent element on a page like header or side-bar. All the components are independent of each other and can be used in any of the pages except for Login and Signup pages as the APIs used in these components are authenticated and must contain a valid session ID. This approach has helped immensely in the development process because it becomes very easy to try out various layouts of the application without changing any code.
Figure 18 contains the folder structure of various pages and components.

11.1.3.6 Fitbit Integration
Court Vision can connect to Fitbit APIs to fetch personal data. This data will be personal to individual users only and coaches also won’t be able to view it. There is no option to allow access to Fitbit data to anyone else. Integration with Fitbit is a two-step process:
1. Create a Fitbit account and register an app –
This is a very simple process where the user first needs to first create a Fitbit account from [https://www.fitbit.com/uk/signup](https://www.fitbit.com/uk/signup). Once the account has been created he/she needs to register an app with Fitbit. Registering an app is a straightforward process where he/she needs to fill a simple form. This can be done from the URL - [https://dev.fitbit.com/apps/new](https://dev.fitbit.com/apps/new). Sample app form is shown in Figure 19. Important thing to keep in mind is to select OAuth 2.0 Application Type as **Personal**, callback URL should be [http://<SERVER_URL>/cv/components/fitbit/fitbit-success.html](http://<SERVER_URL>/cv/components/fitbit/fitbit-success.html) where <SERVER_URL> is the web server URL of the deployment and Default Access Type should be **Read-Only** as shown in Figure 19. Once the app is registered, Fitbit will provide a OAuth 2.0 Client ID. Figure 20 shows the app credentials page with OAuth 2.0 Client ID on top. Copy this Client ID and paste it to the Fitbit Client ID field of profile page of Court Vision (See Figure 15). Once added, save the profile.
2. In the header of Court Vision, click on the Fitbit link (See Figure 21). This will launch the Fitbit login page, asking you to login. After successful login, it will ask you to allow access to the Fitbit app created in step one. Please select Allow All checkbox and click on Allow button. Default access is provided for 1 day. This is increased to 1 year from the dropdown on top (Figure 22). After clicking on allow, the user will be redirected to a success page (Figure 23). This means the authentication is successful and user can close this window. This is a one-time configuration and is not needed for every access.


After successful authentication, user can see Fitbit data visualizations on the graph page like the heart rate visualization (Figure 11).
12. References
2. https://iwbf.org/about-us/who-we-are/
22. https://angularjs.org/
38. https://www.eis2win.co.uk/expertise/performance-analysis/
41. Interplay sports - http://www.interplay-sports.com/
42. Stats - https://www.stats.com/basketball/
47. Fiorilli G, Aquino G, Battaglia, C, Giombia, GC, di Cagno A. Mental health and social participation skills of wheelchair basketball players: A controlled study. Research and
51. https://stats.nba.com
55. https://www.patrick-wied.at/static/heatmapjs/
56. http://animejs.com
57. https://developers.google.com/chart/
58. https://dev.fitbit.com/
68. https://cloud.estimote.com/docs/#api-IndoorGroup
69. https://www.pubnub.com/developers/tech/key-concepts/
73. http://www.britishwheelchairbasketball.co.uk/gbwba/index.cfm/the-league/live-stats/
74. https://opencv.org/
75. https://rtsw.co.uk/supported-hardware/
85. https://github.com/yvettepinder/214P_Website
|
{"Source-Url": "https://uclic.ucl.ac.uk/content/2-study/4-current-taught-course/1-distinction-projects/12-18/jain_ayush_2018.pdf", "len_cl100k_base": 15544, "olmocr-version": "0.1.50", "pdf-total-pages": 40, "total-fallback-pages": 0, "total-input-tokens": 98631, "total-output-tokens": 20947, "length": "2e13", "weborganizer": {"__label__adult": 0.0024814605712890625, "__label__art_design": 0.004489898681640625, "__label__crime_law": 0.0025615692138671875, "__label__education_jobs": 0.00803375244140625, "__label__entertainment": 0.0013885498046875, "__label__fashion_beauty": 0.00209808349609375, "__label__finance_business": 0.0008597373962402344, "__label__food_dining": 0.002834320068359375, "__label__games": 0.025726318359375, "__label__hardware": 0.00983428955078125, "__label__health": 0.01227569580078125, "__label__history": 0.002285003662109375, "__label__home_hobbies": 0.0011119842529296875, "__label__industrial": 0.002353668212890625, "__label__literature": 0.001399993896484375, "__label__politics": 0.0016384124755859375, "__label__religion": 0.001293182373046875, "__label__science_tech": 0.279296875, "__label__social_life": 0.00101470947265625, "__label__software": 0.0211181640625, "__label__software_dev": 0.3203125, "__label__sports_fitness": 0.29150390625, "__label__transportation": 0.0032482147216796875, "__label__travel": 0.0009169578552246094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 89763, 0.03544]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 89763, 0.28954]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 89763, 0.93585]], "google_gemma-3-12b-it_contains_pii": [[0, 630, false], [630, 4414, null], [4414, 4953, null], [4953, 8453, null], [8453, 12241, null], [12241, 16051, null], [16051, 20098, null], [20098, 23826, null], [23826, 25880, null], [25880, 29149, null], [29149, 31102, null], [31102, 32635, null], [32635, 34295, null], [34295, 37204, null], [37204, 40526, null], [40526, 43725, null], [43725, 43795, null], [43795, 43929, null], [43929, 43966, null], [43966, 46919, null], [46919, 47122, null], [47122, 50051, null], [50051, 51401, null], [51401, 54949, null], [54949, 55026, null], [55026, 57414, null], [57414, 61310, null], [61310, 65054, null], [65054, 67401, null], [67401, 70314, null], [70314, 72425, null], [72425, 74100, null], [74100, 74127, null], [74127, 76399, null], [76399, 78301, null], [78301, 78439, null], [78439, 81670, null], [81670, 85111, null], [85111, 88131, null], [88131, 89763, null]], "google_gemma-3-12b-it_is_public_document": [[0, 630, true], [630, 4414, null], [4414, 4953, null], [4953, 8453, null], [8453, 12241, null], [12241, 16051, null], [16051, 20098, null], [20098, 23826, null], [23826, 25880, null], [25880, 29149, null], [29149, 31102, null], [31102, 32635, null], [32635, 34295, null], [34295, 37204, null], [37204, 40526, null], [40526, 43725, null], [43725, 43795, null], [43795, 43929, null], [43929, 43966, null], [43966, 46919, null], [46919, 47122, null], [47122, 50051, null], [50051, 51401, null], [51401, 54949, null], [54949, 55026, null], [55026, 57414, null], [57414, 61310, null], [61310, 65054, null], [65054, 67401, null], [67401, 70314, null], [70314, 72425, null], [72425, 74100, null], [74100, 74127, null], [74127, 76399, null], [76399, 78301, null], [78301, 78439, null], [78439, 81670, null], [81670, 85111, null], [85111, 88131, null], [88131, 89763, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 89763, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 89763, null]], "pdf_page_numbers": [[0, 630, 1], [630, 4414, 2], [4414, 4953, 3], [4953, 8453, 4], [8453, 12241, 5], [12241, 16051, 6], [16051, 20098, 7], [20098, 23826, 8], [23826, 25880, 9], [25880, 29149, 10], [29149, 31102, 11], [31102, 32635, 12], [32635, 34295, 13], [34295, 37204, 14], [37204, 40526, 15], [40526, 43725, 16], [43725, 43795, 17], [43795, 43929, 18], [43929, 43966, 19], [43966, 46919, 20], [46919, 47122, 21], [47122, 50051, 22], [50051, 51401, 23], [51401, 54949, 24], [54949, 55026, 25], [55026, 57414, 26], [57414, 61310, 27], [61310, 65054, 28], [65054, 67401, 29], [67401, 70314, 30], [70314, 72425, 31], [72425, 74100, 32], [74100, 74127, 33], [74127, 76399, 34], [76399, 78301, 35], [78301, 78439, 36], [78439, 81670, 37], [81670, 85111, 38], [85111, 88131, 39], [88131, 89763, 40]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 89763, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
c1e03feb19715debe737f23349a83a0403ce48ad
|
Towards a correct and efficient implementation of simulation and verification tools for Probabilistic ntcc
Mauricio Toro Bermúdez
mauriciotoro@cic.javerianacali.edu.co
August 11, 2009
Abstract
Using process calculi one can verify properties of a system and simulate the system as well. One should be able to do these operations at least semi-automatically. There is a tool to simulate the Non-deterministic Timed Concurrent Constraint (ntcc) calculus in the Ntccrt framework, but there are not tools for verification. We present a new simulation tool for Probabilistic ntcc (pntcc) and a prototype for verification of pntcc models. We include these tools in the Ntccrt framework. We also show the formal basis for correctness of the ntcc simulation tool and we show that the execution times of the simulation are still acceptable for real-time interaction using pntcc.
1 Introduction
Using process calculi one can simulate a model and also verify logical properties over it. For instance, the Non-deterministic Timed Concurrent Constraint (ntcc) [NPV02] calculus is as an extension of the Saraswat’s concurrent constraint programming (ccp) [Sar92] to model new phenomena, in particular non-deterministic and timed behavior. The ntcc calculus is based on solid mathematical principles and it has succeed in a wide range of applications in emergent areas such as Security, Biology and Multimedia Semantic Interaction according to [Ola09]. Ntcc provides rich verification techniques allowing the inference of important temporal properties satisfied by the encoded applications. For instance, security breaches in cryptographic protocols [OV08], prediction of organic malfunctions [GPRV07] and rhythmic coherence in music improvisation [RV04].
It is also argued in [Ola09] that in spite of its modeling success, at present ntcc does not provide for the automatic, or even machine-assisted, verification of system properties. Since they deal with complex and large systems, machine-assisted verification is essential to our intended applications. However, this issue has not been deeply considered for ccp formalisms. To the best of their knowledge only Villanneva et al [MV09] have addressed automatic verification, but only in the context of finite-state ccp systems. Several interesting applications of ntcc are, however, inherently infinite-state according to [Ola09]. Automatic verification of large systems, not to mention infinite systems, represents a fundamental challenge because of the state explosion problem it poses because the number of states a system has is exponential in the number of concurrent processes. For that reason, it is proposed in [Ola09] to rise to this challenge by identifying ntcc fragments appropriate for automatic verification and developing efficient techniques and tools to machine assist the verification of system properties in ntcc.
Multiple tools have been developed for the simulation of ntcc models. For instance, the Ntccrt framework \cite{TBAAR09}. However, it has not been proved formally the correctness of the framework’s tools, thus, users cannot be sure that a simulation obtained using the ntcc simulation tool corresponds to the semantics of the calculus. In addition, Ntccrt does not provide tools for automated verification.
In this report we describe a formalization of the principles used by Ntccrt to simulate models. We also present the extension of the ntcc simulation tool for Probabilistic ntcc (pntcc) \cite{PR08} models and we prove the correctness of the simulation tool for ntcc. In addition, we developed a verification tool for pntcc models. Using this verification tool, we can prove properties such as “the system will go to a successful state with probability $p$ under $t$ discrete time-units”.
In what follows, we present in chapter 1 the formalization of the ntcc simulation tool. Then, in chapter 2 we explain the implementation of the frameworks’ tools. In chapter 3, we present some applications ran using the framework’s tools. Finally, we give some concluding remarks, current and future work in chapter 4.
2 Formal basis for simulation and verification for ntcc
In this chapter we explain the formal basis of our tool for simulation of ntcc models. Since pntcc is an extension of ntcc, some of these results could be later applied for pntcc.
2.1 Encoding a fragment of ntcc as a Constraint Satisfaction Problem
In this section we show how a star-free fragment of ntcc can be encoded as a Constraint Satisfaction Problem (CSP). We prove that the solutions of the CSP have a relation with the store computed in a single time unit. In such fragment, we do not not include the asynchronous operator ($^*$) and we present a different operational semantic based on the concept of a scheduler or adversary (proposed in pntcc semantics).
Definition 1. A Constraint Satisfaction Problem (CSP) is defined as a triple $\langle X, D, C \rangle$ where $X$ is a set of variables, $D$ is a set of domains and $C$ is a set of constraints. A solution for a CSP is an evaluation that satisfies all constraints.
The following star-free fragment of ntcc is parametrized by a Finite Domain FD[232] constraint system. Thirty-two is the size of an integer on a 32-bits computer architecture.
Definition 2. A star-free fragment of ntcc parametrized by FD[232] where $P, Q ::=
P \parallel Q \mid \text{tell}(c) \mid \text{local } x \text{ in } P \mid \sum_{i \in I} \text{when } c_i \text{ do } P_i \mid \text{next } P \mid \text{unless } c \text{ next } P \mid !P$
Definition 3. A Constraint System (CS) is a pair $\langle \Sigma, \Delta \rangle$ where $\Sigma$ is a signature specifying constants, functions and predicate symbols, and $\Delta$ is consistent first-order theory over $\Sigma$ (i.e., a set of first-order sentences over $\Sigma$ having at least one model). We say that $c$ entails $d$ in $\Delta$, written $c \models_{\Delta} d$ iff the formula $c \Rightarrow d$ is true in all models of $\Delta$. We write $\models$ instead of $\models_{\Delta}$ when $\Delta$ is unimportant \cite{Val02}.
Definition 4. Let $n > 0$. A Finite Domain FD(n) is a CS such that:
- $\Sigma$ is given by constant symbols $0..n - 1$ and the equality.
- $\Delta$ is given by the axioms of equational theory $x = x, x = y \rightarrow y = x, x = y \land y = z \rightarrow x = z,$ and $v = w \rightarrow \text{false}$ for each two different constants $v, w$ in $\Sigma$ \cite{Val02}.
In order to define an encoding for a process given by Def. 2 into a CSP, we need to define a function to calculate the set of the non-local variables of a process and a function to solve non-deterministic choices for each \( \sum \) process.
**Definition 5.** Let \( \text{vars}(P) \): “ntcc process” → “set of variable names” be recursively defined
\[
\begin{align*}
\text{vars}(\text{tell}(c)) &= C\text{vars}(c), \text{the variables contained in a constraint}.
\text{vars}(P|Q) &= \text{vars}(P) \cup \text{vars}(Q)
\text{vars}(\sum_{i \in I} \text{when } c_i \text{ do } P_i) &= \bigcup_{i \in I} \text{vars}(P_i)
\text{vars}(\text{local } x \text{ in } P) &= \text{vars}(P) - \{x\}
\text{vars}(\text{unless } c \text{ next } P) &= \text{vars}(\text{next } P) = \emptyset
\text{vars}(1P) &= \text{vars}(P)
\end{align*}
\]
Before defining our function to solve non-determinism, let us introduce how the non-determinism is solved according to the ntcc semantics based on a Probabilistic Automata.
**Definition 6.** A Probabilistic Automata (PA) is a tuple \((Q, q, A, T)\), where \(Q\) is a countable set of states, \(q \in Q\) is the start state, \(A\) is a countable set of actions, and \(T \subseteq Q \times \text{Probs}(A \times Q)\) defines the transition groups of the automaton. In ntcc semantics, we do not need actions, thus, in this report we discard the set of actions. On the other hand, since we are describing non-probabilistic processes in this section, all the probabilities in the transitions are 1.
We recall from the ntcc paper that a scheduler is a function \(S_j : TM_i \to TM_i\) that takes a set of transition groups and returns a set of transition groups where we can only observe probabilistic choice.
One may think about defining a particular scheduler for each model one defines. This posses two problems: the person defining the model must be aware of the transition groups generated by each process involving non-determinism (parallel and non-deterministic choice processes); and the person has to consider all the possible inputs for a process, since the transition groups may be different according to the input.
In order to make things easier, we propose to define define a function \(\text{FND} : \text{"Process, Set of } \mathbb{N} \text{" } \to \mathbb{N}\) to solve the non-determinism on each \( \sum \) process. \(\text{FND}\) takes the set of indexes of the guards that hold in a non-deterministic process and returns one index. Choosing an index with the function \(\text{FND}\) is equivalent to selecting a transition group generated by a \( \sum \) process. The non-determinism generated by the parallel processes (after removing the non-determinism generated by the \( \sum \) processes) is confluent (i.e., independent from the scheduling strategy) according to Falaschi et al. To clarify the purpose of \( \text{FND} \), consider the execution of the first time unit of an improvisation process that chooses between playing a note or not.
\[
\begin{align*}
P &\overset{\text{def}}{=} \text{tell}(\text{playnote} = \text{true}) + \text{tell}(\text{playnote} = \text{false})
\text{Improv} &\overset{\text{def}}{=} \text{tell} (\text{dur}=250) \parallel P
\end{align*}
\]
In the process \( P \), both guards hold. Then, the purpose of the function \(\text{FND}\) is to solve the non-deterministic choice. For instance, a function \(\text{FND}(P, I) = \text{min}(I)\) chooses the process that plays the note. On the other hand, the function \(\text{FND}(P, I) = \text{max}(I)\) chooses not to play the note. According to Falaschi et al., we get the same results executing \text{tell} (dur=250) and \( P \) in any order once the non-deterministic choices are solved.
Let us explore the concept of scheduler defined in the operational semantics. Consider a store \( d \) as the input for the \( \text{Improv} \) process. Then, the probabilistic automata \( M_i \) represents the transitions for the first time unit of the improvisation process.
\[
M_i = (T_i, \gamma_0, TM_i)
\]
\[
T_i = \{ \gamma_1 = \langle \text{skip}, \text{dur} = 250 \& \text{playnote} \& d \rangle, \gamma_2 = \langle \text{skip}, \text{dur} = 250 \& \neg \text{playnote} \& d \rangle \}
\]
\[
\gamma_0 = \langle \text{Improv}, d \rangle
\]
\[
TM_i = \{ \{ \gamma_0 \rightarrow \gamma_1, \gamma_0 \rightarrow \gamma_2 \} \}
\]
In the example above, the scheduler returns \( \{ \gamma_0 \rightarrow \gamma_1 \} \) if the function \( \text{FND}(P, I) = \text{min}(I) \) or \( \{ \gamma_0 \rightarrow \gamma_2 \} \) if the function \( \text{FND}(P, I) = \text{max}(I) \).
In what follows, we use the function \( \text{FND} \) to make an encoding of the star-free fragment of \( \text{ntcc} \) given by Def. \( 2 \) into a CSP. In order to define the encoding, we assume a constraint \( C \leftrightarrow b \) where \( b \) does not occur free in \( C \) in the constraint system for each constraint used as guard in the \( \sum \) processes. These constraints are called \textit{reified constraints}. Using constraints as guards for \( \sum \) processes are limited by the reified constraints supplied by the constraint solving tool.
**Definition 7.** \textit{Reification} represents the validity of a constraint into a 0/1-variable. Therefore, constraints can be combined using 0/1-variables. The reification of a constraint \( C \) with respect to a variable \( x \) is the constraint \( (C \leftrightarrow b) \land b \in \{0, 1\} \) where it is assumed that \( b \) does not occur free in \( C \). The operational semantics of a propagator for the reification of a constraint \( C \) with respect to \( b \) is given by the following rules \[\text{Korab}\]l:
- If the constraint store entails \( b = 1 \), the propagator for the reification reduces to a propagator for \( C \).
- If the constraint store entails \( b = 0 \), the propagator for the reification reduces to a propagator for \( C \).
- If a propagator for \( C \) would realize that the constraint store entails \( C \), the propagator for the reification tells \( b = 1 \) and ceases to exist.
- If a propagator for \( C \) would realize that the constraint store is inconsistent with \( C \), the propagator for the reification tells \( b = 0 \) and ceases to exist.
Next, we define the encoding of a \( \text{ntcc} \) process given by Def. \( 2 \) into a constraint. The encoding is parametrized by the function \( \text{FND} \).
**Definition 8.** Let \( \llbracket P \rrbracket_{\text{FND}} \) \text{”ntcc process”} \text{“constraint” be defined recursively.}
\[
\llbracket \text{tell}(c) \rrbracket_{\text{FND}} = c
\]
\[
\llbracket \sum_{i \in I} \text{when } c_i \text{ do } P_i \rrbracket_{\text{FND}} = \begin{cases} \llbracket P_j \rrbracket_{\text{FND}} & I \neq \emptyset \\
\text{true} & I = \emptyset \end{cases}
\]
where \( j = \text{FND}(P, I) \) and \( I = \{ i | \exists b.i \in I \land c_i \leftrightarrow b \land b = 1 \} \)
\[
\llbracket Q | R \rrbracket_{\text{FND}} = \llbracket Q \rrbracket_{\text{FND}} \& \llbracket R \rrbracket_{\text{FND}}
\]
\[
\llbracket \text{local } x \text{ in } Q \rrbracket_{\text{FND}} = \exists x.\llbracket Q \rrbracket_{\text{FND}}
\]
\[
\llbracket \text{next } Q \rrbracket_{\text{FND}} = \llbracket \text{unless } c \text{ next } Q \rrbracket_{\text{FND}} = \text{true}
\]
\[
\llbracket !Q \rrbracket_{\text{FND}} = \llbracket Q \rrbracket_{\text{FND}}
\]
**Definition 9.** A scheduler \( S_j \) defined by a function \( FND \) is a function \( S_j : TM \rightarrow TM \), such that a transition group \( \gamma_i \{ \rightarrow_1 \gamma_{i+1} \} \in S_j(TM) \) if \( \langle P, c \rangle = \gamma_i, \langle Q, d \rangle = \gamma' \), \([P]_{FND} \wedge c = d \), it exists a path from \( \gamma_{i+1} \) to \( \gamma' \) in \( TM \), and \( \gamma' \) has no more successors. Non-determinism in parallel processes can be discarded because it is confluent in this context.
It exists a path from \( A \) to \( B \) in a set of transition groups \( TM \) iff the following groups belong to the set \( A \{ \rightarrow_1 A_1 \} \ldots \{ \rightarrow_1 A_i \} \{ \rightarrow_1 A_{i+1} \} \ldots \{ \rightarrow_1 B \} \). \( B \) has not successors in a set of transition groups \( TM \) iff there is not a group \( B \{ \rightarrow_1 X \} \) in \( TM \).
To prove the correctness of the encoding presented above, we need to prove three properties. (1) All the solutions for a CSP given by the constraint computed by the previous encoding implies the store calculated by a process at the end of a time unit. (2) The future function, calculated using the previous encoding, corresponds to the future function defined in the semantics. (3) The store calculated by a process at the end of a time unit has a connection to the solutions of the CSP. Before presenting the proposition (1), we present some theorems taken from the ntcc operational semantics.
**Lemma 1.** Every sequence of internal sequences is terminating (i.e., there are not infinite sequences) [Val02].
**Property 1. Internal Extensiveness** if \( \langle P, c \rangle \rightarrow \langle Q, d \rangle \) then \( d = c \). [Val02].
**Proposition 1.** Let \( P, FND \) and \([P]_{FND}\) be a process in the ntcc fragment given by Def. 2, a function \( FND : \text{set of } \mathbb{N} \rightarrow \mathbb{N} \) and the encoding of \( P \) given by Def. 10. Then, for every constraint \( c \), it exists a constraint \( d \) such that
\[ \forall x . x \in \text{Solutions of the CSP} \]
\[ \text{Variables : } \text{Vars}(P) \]
\[ \text{Domain for each variable : } [0..2^{32} - 1] \]
\[ \text{Constraints : } \{ [P]_{FND} \wedge c \} \]
then, in any time unit, it holds that \( \langle P, c \rangle \{ \rightarrow_1 \} \langle Q, d \rangle \}_{S_j} \rightarrow \) and \( x \Rightarrow d \), where \( S_j \) is a scheduler defined by \( FND \) according to Def. 9.
**Proof.** \( \langle P, c \rangle \{ \rightarrow_1 \} \langle Q, d \rangle \}_{S_j} \rightarrow \) holds by lemma 1. We have left to prove that for all \( x \) in the solutions of the CSP, where the constraints are given by \([P]_{FND} \wedge c\), it holds that \( x \Rightarrow d \). The proof proceeds by induction on the structure of \( P \).
- \( P = \text{tell}(e) \)
By Def. 10 we have \([P]_{FND} \wedge c = e \wedge c \) and it holds that \( \langle \text{tell}(e), c \rangle \{ \rightarrow_1 \} (\langle \text{skip}, c \wedge e \rangle) \}_{S_j} \rightarrow \) according to the TELL rule. Then, \( d = e \wedge c \) and it holds that \( x \Rightarrow c \wedge e \).
- \( P = \sum_{i \in I} c_i \) when \( c_i \) do \( P_i \)
By the inductive hypothesis, we assume that the proposition holds for each \( i \in I \): for all \( x_i \) in the solutions of the CSP given by the constraint \([P_i]_{FND} \wedge c \), then it holds that \( x_i \Rightarrow d_i \).
We have to prove that for all \( x \) in the solutions of the CSP given by the constraint \([P]_{FND} \wedge c \) it holds that \( x \Rightarrow d \). There are two cases:
- Case where all the guards are false or they cannot be deduced from the store:
We know that \([P]_{FND} = \text{true} \) by Def. 10 and \( \langle P, c \rangle \rightarrow \) by the semantics of \( \sum \).
Then, for all \( x \) in the solutions for the CSP given by the constraint \( \text{true} \wedge c \), it holds that \( x \Rightarrow c \).
− Case where at least one guard holds.
Let \( I \) be the set of the indexes whose guards holds, \( j = F N D(P, I) \) and \( S_j \) the scheduler defined by \( F N D \), then it holds that \( \langle P, c \rangle \rightarrow_{1} \langle P_j, c_j \rangle \) \( S_j \).
We know by the inductive hypothesis that \( \langle P_j, c_j \rangle \rightarrow_{1} \langle Q_j, d_j \rangle \) \( S_j \) and for all \( x \) in the solutions of \( [P_j]_{F N D} \wedge c \) it holds that \( x \Rightarrow d_j \).
By the property \([1] \) \( e \models c \), then \( e \models c \) by Prop. \([1] \). In the same way, \( e \models d_j \), then \( e \Rightarrow d_j \), therefore \( e \Rightarrow d_j \).
Finally, since \( [P]_{F N D} = [P_j]_{F N D} \) by Def. \([10] \) then it holds for all \( x \) in the solutions of the CSP given by the constraint \( [P]_{F N D} \wedge c \) that \( x \Rightarrow d_j \).
\[ \bullet \quad P = Q \parallel R \]
By the inductive hypothesis, we assume that the proposition holds for each \( Q \) and \( R \).
We have to prove that for all \( x \) in the solutions of the CSP given by the constraint \( [Q]_{F N D} \wedge [R]_{F N D} \wedge c \) it holds that \( x \Rightarrow d \).
We know that \( d \models [Q]_{F N D} \wedge [R]_{F N D} \wedge c \models [Q]_{F N D} \wedge [R]_{F N D} \wedge c \), but how can we prove that \( [Q]_{F N D} \wedge [R]_{F N D} \wedge c \models d \)?
\[ \bullet \quad P = \text{local } x \text{ in } Q \]
By the inductive hypothesis, the assume that the proposition holds for \( Q \). This means that \( \langle Q, e \wedge \exists x.c \rangle \rightarrow \langle Q', e \rangle \rightarrow^* \langle Q'', d' \rangle \rightarrow \) and for all \( x \) in the solutions in the CSP given by \([Q]_{F N D} \), it holds that \( x \Rightarrow d' \).
We have to prove that for all \( x \) in the solutions of the CSP given by the constraint \( [P]_{F N D} \wedge c \), it holds that \( x \Rightarrow d \). We have \([P]_{F N D} = \exists x.[Q]_{F N D} \) by Def. \([10] \). By lemma \([1] \) and the LOC rule, we know that \( \langle \text{local } (x, c) \text{ in } P, c \rangle \rightarrow \langle \text{local } (x, c') \text{ in } P', e \wedge \exists x.c \rangle \rightarrow^* \langle Q, f \wedge \exists x.c' \wedge \exists x.c'' \wedge \ldots \exists x.c^n \rangle \rightarrow^* \). Then \( d = f \wedge \exists x.c' \wedge \exists x.c'' \wedge \ldots \exists x.c^n \). What is the relation between \( d \) and \( f \)?
\[ \bullet \quad P = \text{next } Q \text{ and } P = \text{unless } c \text{ next } Q \]
By Def. \([10] \) \( [P]_{F N D} = \text{true} \). We also know that \( \langle P, c \rangle \rightarrow^* \). Then, \( d = c \) and for all \( x \) in the solutions of \( c \land \text{true} \), it holds that \( x \Rightarrow d \).
\[ \bullet \quad P = !Q \]
We assume by the inductive hypothesis that the proposition holds for \( Q \). Since we know that \([P]_{F N D} = [Q]_{F N D} \) by Def. \([10] \) then the proposition holds for \( P \).
\[ \square \]
In what follows, we define a function \( F \) that returns the process to be executed in the next time unit.
**Definition 10.** Let \( F(P)_{F N D,d} \): “ntcc process” → “ntcc process” be defined recursively.
\[
F(\text{tell}(c))_{F N D,d} = \text{skip}
\]
\[
F(\sum_{i \in I} \text{when } c_i \text{ do } P_i)_{F N D,d} =
\begin{cases}
F(P_j)_{F N D,d} & ||I|| \neq 0 \\
\text{skip} & ||I|| = 0
\end{cases}
\]
where \( j = F N D(P, I) \) and \( I = \{i | \exists b. i \in I \land c_i \leftrightarrow b \land b = 1\} \).
\[ F(Q|R)_{FND,d} = F(Q)_{FND,d}||F(R)_{FND,d} \]
\[ F(\text{local } x \text{ in } Q)_{FND,d} = \text{local } x \text{ in } F(Q)_{FND} \]
\[ F(\text{next } Q)_{FND,d} = Q \]
\[ F(\text{unless } c \text{ next } Q)_{FND} = \begin{cases} Q, & d \models c \\ \text{skip}, & d \not\models c \end{cases} \]
\[ F(!Q)_{FND,d} = F(Q)_{FND,d}||!Q \]
To prove proposition (3), we have to prove that the process calculated by the function \( F \) is equivalent to the process calculated by the future function defined in the operational semantics of ntcc.
3 Implementation of the tools for ntcc and pntcc
In the implementation, we use Gecode as the constraint-solving library. Gecode is an efficient library using state-of-the-art algorithms for propagation. We do not use search for our tools, thus, our implementation heavily relies on propagation. Gecode has a great advantage, it is easily extensible: we can define new propagators without recompiling it.
We use Gecode for concurrency control. Although threads are a common way to represent concurrency, we do not use them in our implementation. Instead, we rely on the scheduler of Gecode propagators to execute all the parallel processes concurrently. In the previous section, we show how we can encode all the processes as constraints, the intuition of the simulation and verification tools is to use a propagator for each of those constraints and let Gecode schedule those propagators.
Tools for Ntccrt are written in C++ because they run faster than using other programming languages and using a wrapper for Gecode. In addition, all the processes have to be represented as propagators and at the end Gecode propagators are written in C++. We also provide interfaces for Common Lisp, OpenMusic [BA08], Max/MSP and Pure Data [PA98]. The reader may find more information about the implementation of Ntccrt at [TB09] and [TB08]. In what follows, we explain how to represent each ntcc process as a propagator and how to extend the ntcc simulation tool for the simulation and verification of pntcc models.
3.1 Representing each ntcc process as a propagator
Processes are represented by classes. These classes inherit from a class Process declaring a virtual Execute method.
Tell classes have an Execute method to post a Gecode propagator. For instance, a process \( \text{tell}(a = b) \) is represented by a class, which execute method posts an equality-relation propagator. Objects of the Parallel class contain a list of processes. Its Execute method calls the Execute method for each object in the list.
In Local processes, local variables are fresh variables created on execution time. Variables are classes wrapping Gecode variables. Gecode variables cannot be used directly because they only exist during a single time unit, instead we create a an instance of our Variable class that creates a new instance of a Gecode variable for each time unit. Non-local variables are created at the beginning of the simulation.
Non-deterministic-choice classes have an Execute method that creates a non-deterministic-choice propagator. This propagator randomly chooses a process from those whose guards
holds. We use reification to represent the conditions and we use an array of reified variables as a parameter for the non-deterministic-choice propagator. This propagator is the implementation of one possible scheduler. However, this propagator can be changed to establish other policies of scheduling.
Temporal processes interact with a sequence of time units. Time units are represented by a list of queues of processes. For instance, the execution of the Process object inside a Next object is postponed for the next time unit. The execution of a Bang object calls the Execute method of its nested process. It also duplicates the Bang object for the next time unit.
Finally, unless $c$ do $P$ is represented by a class, which execution is postponed until all the propagators for the processes (except unless processes) achieve a common fixpoint. We recall that a propagator is a function $f: store \rightarrow store$, thus, a common fixpoint for all the propagators is a state such that none of the propagators can perform an action that changes the store. After the fixpoint is calculated, the unless Execute method postpones the execution of $P$ for the next time unit if $c$ cannot be deduced from the store.
3.2 Extending the simulation tool for pntcc
In order to extend the ntcc simulation tool for pntcc, we only need to add a new class for probabilistic choice inheriting from the Process class. This class takes an array of Process objects; an array of boolean variables, used to represent the reified constraints of the guards; and an array of integers, used to represent the probabilities.
To avoid errors produced by float-number calculations, users must represent the probabilities as integers. For instance, $[0.3, 0.4, 0.3]$ can be represented as $[30, 40, 30]$ or $[3, 4, 3]$. Precision of the probabilities is limited by the size of non-signed integers (32 bits in a 32-bits computer architecture). Users also need to provide a reified constraint for each guard in the process.
**Definition 11.** A Discrete-Time Markov Chain (DTMC) is a tuple $(Q_{OBS}, q, T_{OBS}, LM)$, where $Q_{OBS}$ is a finite set of states (with initial state $q \in Q_{OBS}$); $T_{OBS}: Q_{OBS} \times Q_{OBS} \rightarrow [0, 1]$ is a transition, such that $\forall q \in Q_{OBS}: \sum_{q' \in Q_{OBS}} T_{OBS}(q, q') = 1$; and the labeling function $LM: Q_{OBS} \rightarrow 2^A$ assigns atomic propositions to states.
There is a connection between a pntcc process and a DTMC. We recall the following proposition from the pntcc paper.
**Proposition 2.** Given a pntcc process $P_0$, for every $P_n$ reachable from $P_0$ through an observable sequence, in the DTMC given by $DTMC((P_0, true))$ there exists a path from $(P_0, true)$ to $(P_n, d)$, for some constraint $d$.
In order to make a simulation for a pntcc model, we only need to calculate a single path of the DTMC produced by a pntcc process. In order to achieve that, we solve non-determinism using the user-defined FND function. On the other hand, in order to solve probabilistic choice, we perform a simple algorithm. (1) Calculate the sum of the list of integers (representing probabilities) for the indexes whose guards that holds. (2) Using a random-number-generator library, calculate a number between 0 and $\text{sum} - 1$. (3) According to the number generated by the library, choose the appropriate process and call its Execute method.
3.3 A verification tool for pntcc
The purpose of our verification tool is calculating a DTMC based on three things: a list of inputs (i.e., constraints), a pntcc model and a function FND to solve non-determinism.
Then, the DTMC is saved as a PRISM input file. Finally, using PRISM, the tool can verify properties for the model.
According to \textsc{pntcc} authors, there is a straightforward connection with model-checking procedures for \textsc{pntcc}: “The rationale given by the language and the support provided by operational semantics make it possible a natural relation between \textsc{pntcc} and the probabilistic logic PCTL \cite{CG04}. Formulas in PCTL express soft deadlines, statements explicitly involving a time bound and a probability. Hence, they allow for including quantitative parameters directly in the properties of interest. The relation between \textsc{pntcc} and PCTL is based on the fact that the observable behavior of a process can be interpreted as the discrete time Markov chain (DTMC) defining satisfaction in PCTL. This way, model checking for tcp process specifications becomes possible” \cite{PR08}
PRISM can verify Probabilistic Computational Tree Logic (PCTL) properties for a DTMC. Therefore, if we can construct a DTMC for a \textsc{pntcc} process using our verification tool, the verification is straightforward. In order to create a DTMC, we need to extend the simulation tool. First, we need to extend the definition of the variables, since a variable with the same name can be in different time units in the simulation tool, but now, there are several instances of a time unit. We also need to extend the way how temporal process add processes to the next time unit, since there are several instances of a time unit.
The execution of a time unit in the verification tool is slightly different from the simulation tool. It proceeds in the following way. First, we create a state $\langle S, c \rangle$. For every time unit, $P||Q$, and local are executed as described for the simulation tool. Temporal processes create a new state and a transition from the current state to the new state. Probabilistic processes create a state and a transition for each guard that holds, except the first guard, which process is executed in the current state.
The last step is to reduce the DTMC-tree into a DTMC by reducing repeated states. There is a configuration $\langle P, C \rangle$ associated to each state by the means of the labeling function. We consider that two configurations are equal if their processes are structural congruent and they have logical equivalent stores.
To check structural congruence, Valencia proposes in \cite{Val02} to construct a syntax tree for each process and check whether they are isomorphic. This feature is still experimental in our tool.
4 Applications
In this section we present some applications ran with the simulation and verification tools for \textsc{pntcc} models.
4.1 Probabilistic Ccfomi
Concurrent Constraint Factor Oracle Model for Music Improvisation (Ccfomi) \cite{RAD06} is a \textsc{pntcc} model for music improvisation, where improvisation is made non-deterministically. Probabilistic Ccfomi \cite{PR08} extends the choice in the improvisation process probabilistically. We ran Probabilistic Ccfomi in our tool and we defined constants for the probabilities of the probabilistic choice process.
4.2 The zigzag robot
Zigzagging is a task on which a robot can go either forward, left, or right, but (1) it cannot go forward if its preceding action was to go forward, (2) it cannot turn right if its
second-last action was to go right, and (3) it cannot turn left if its second-last action was
to go left. Valencia models this problem by using cells $a_1$ and $a_2$ to “look back” and three
different distinct constants $f, r, l \in D - \{0\}$ and the predicate symbols forward, right, left
\cite{Val02}.
Using our ntcc simulation tool, we obtain the following data
\begin{center}
\begin{tabular}{|c|c|c|}
\hline
direction & last direction & second-last direction \\
\hline
1 & 0 & 0 \\
3 & 1 & 0 \\
1 & 3 & 1 \\
2 & 1 & 3 \\
2 & 2 & 1 \\
1 & 2 & 2 \\
3 & 1 & 2 \\
3 & 3 & 2 \\
1 & 3 & 3 \\
2 & 1 & 3 \\
2 & 2 & 1 \\
3 & 2 & 2 \\
1 & 3 & 2 \\
\hline
\end{tabular}
\end{center}
where $f = 1, r = 2, l = 3$.
Valencia verified that the model eventually goes right or left. For this model, we proved
that the robot does not go forward twice, the robot does not go right more than twice,
the robot does not go left more than twice, the robot always makes a good move.
We also provide a probabilistic extension of this model where the direction is chosen
probabilistically. We also keep track of the cartesian coordinate $(x,y)$ of the robot. Using
our pntcc simulation tool, we obtain the following data data
\begin{center}
\begin{tabular}{|c|c|c|c|c|}
\hline
direction & last direction & second-last direction & $x$ & $y$ \\
\hline
2 & 0 & 0 & 0 & 0 \\
1 & 2 & 0 & 1 & 0 \\
3 & 1 & 2 & 1 & 1 \\
1 & 3 & 1 & 0 & 1 \\
2 & 1 & 3 & 0 & 2 \\
2 & 2 & 1 & 1 & 2 \\
1 & 2 & 2 & 2 & 2 \\
3 & 1 & 2 & 2 & 3 \\
\hline
\end{tabular}
\end{center}
For this model, we use the verification tool to find a probability distribution for the
position $(x,y)$ of the robot. We also provide a graphical simulation using “ardilla python”
(a visual programming environment based on robot moving on a two-dimensional board’).
\subsection*{4.3 Herman stabilization protocol}
A self-stabilizing protocol (according to PRISM website) for a network of processes is a
protocol which, when started from some possibly illegal start configuration, returns to a
legal/stable configuration without any outside intervention within some finite number of
steps.
The network is a ring of identical processes. The stable configurations are those where
there is exactly one process designated as ”privileged” (has a token). This privilege (token)
should be passed around the ring forever in a fair manner. For further details on self-
stabilization see http://www.prism.org.
An interesting property for these protocols is to compute the minimum probability of reaching a stable configuration and the maximum expected time (number of steps) to reach a stable configuration (given that the above probability is 1) over every possible initial configuration of the protocol.
We modeled Herman’s protocol [Her90]. This protocol is described in PRISM website as follows: “The protocol operates synchronously, the ring is oriented, and communication is unidirectional in the ring. In this protocol the number of processes in the ring must be odd.
Each process in the ring has a local boolean variable \( x_i \), and there is a token in place \( i \) if \( x_i = x_{i-1} \). In a basic step of the protocol, if the current values of \( x_i \) and \( x_{i-1} \) are equal, then it makes a (uniform) random choice as to the next value of \( x_i \), and otherwise it sets it equal to the current value of \( x_{i-1} \).
For instance, consider a simulation for the protocol for three nodes and an initial state where \( x_0 = 0, x_1 = 0, x_2 = 0 \). Using the simulation tool, we obtain the following data:
<table>
<thead>
<tr>
<th>number of tokens</th>
<th>( x_0 )</th>
<th>( x_1 )</th>
<th>( x_2 )</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>1</td>
<td>0</td>
<td>1</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>1</td>
<td>1</td>
<td>0</td>
</tr>
</tbody>
</table>
We can also create a DTMC model for PRISM and then perform a simulation (fig. 1).

**Figure 1: Simulation**
In the same way as it is done for PRISM study cases, we check the correctness of the protocol, namely that: from any configuration, a stable configuration is reached with probability 1 and the minimum probability of reaching a stable configuration within \( K \) steps (from any configuration). In figure 2, we present the chart obtained on PRISM study cases and then, the graph obtained using our tool in joint work with PRISM.
5 Results, conclusions and future work
In a previous work [TBAAR09], we ran Ccfomi as an stand-alone application over an Intel 2.8 GHz iMac using Mac OS 10.5.2 and Gecode 2.2.0. Each time-unit took an average of
20 ms, scheduling around 880 processes per time-unit. We simulated 300 time-units and we ran each simulation 100 times in our tests.
In this work, we compared the performance of CCFOMI and Probabilistic CCFOMI. The probabilistic model was around 50% slower than CCFOMI. Although, we still can do multiple optimizations to the \textit{pntcc} simulation tool, we conjecture that the performance is still acceptable for real-time interaction.
Pachet argues in [Pac02] that an improvisation system able to learn and produce sequences in less than 30ms is appropriate for real-time interaction. Since our implementation of \textit{Ccfomi} has a response time of 20ms in average, we conclude that it is capable of real-time interaction for a 300 (or less) time-units simulation. There is not enough data to conclude if the simulation of Probabilistic Ccfomi is also appropriate for real-time interaction.
For this work, we made all the test under Mac OS X using Pd. However, we also ran successfully the tools on Linux. Since we are using Gecode and Fl ext to generate the externals, they were easily compiled to Linux. In the future, we will also compile them to use Max/MSP. This is due to Gecode and Fl ext portability.
In this report, we presented the formal basis of the \textit{ntcc} simulation tool of the Ntcert framework. We presented two new tools for the framework: a simulation tool for \textit{pntcc} and a verification tool for \textit{pntcc}. We also discussed some application ran using the simulation and verification tools.
We want to encourage the use of process calculi to develop reactive systems. For that reason, this research focuses on developing real-life applications with \textit{ntcc} and \textit{pntcc} and
showing how we can verify properties of those systems with a tool, from which we also prove its correctness. In a previous work, we showed that our interpreter Ntccrt is a user-friendly tool, providing a graphical interface to specify ntcc models and compiling them to efficient C++ programs capable of real-time interaction in Pd. In this report, we show that the new framework’s tools are also user friendly and efficient. Furthermore, they have a formal basis.
In the International Colloquium on Emergent Trends in Concurrency Theory in Paris in honor of Turing-award winner Robin Milner [VP08], leading researchers reflected about strategic directions in concurrency theory, but we adhere (as well as presented on [Ola09]) in particular to Garavel’s position statement [Gar08]: “The times have gone, where formal methods were primarily a pen-and-pencil activity for mathematicians. Today, only languages properly equipped with software tools will have a chance to be adopted by industry. It is therefore essential for the next generation of languages based on process calculi to be supported by compilers, simulators, verification tools, etc. The research agenda for theoretical concurrency should therefore address the design of efficient algorithms for translating and verifying formal specifications of concurrent systems”.
In the future, we want to extend our implementation to fully support pntcc simulation and verification. We also want to support rtcc [Sar08], and to generate an input for Spin [Hol97] based on a ntcc model for verification of temporal properties in ntcc.
6 Acknowledgments
In first place, we want to thank Camilo Rueda and Jorge Pérez for supervising this research. We also want to thank Gerardo Sarria, Yamil S. Perchy, Víctor Rivera and Jorge Victoria for their valuable comments during this research.
References
|
{"Source-Url": "http://ingenieria.puj.edu.co/wiki/lib/exe/fetch.php?media=grupos%3Aavispa%3Apapers%3Ator09c.pdf", "len_cl100k_base": 10992, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 48663, "total-output-tokens": 13337, "length": "2e13", "weborganizer": {"__label__adult": 0.0005507469177246094, "__label__art_design": 0.0013427734375, "__label__crime_law": 0.0005688667297363281, "__label__education_jobs": 0.0015058517456054688, "__label__entertainment": 0.00046539306640625, "__label__fashion_beauty": 0.00023043155670166016, "__label__finance_business": 0.00043320655822753906, "__label__food_dining": 0.0007333755493164062, "__label__games": 0.0014820098876953125, "__label__hardware": 0.0014486312866210938, "__label__health": 0.0009531974792480468, "__label__history": 0.0005049705505371094, "__label__home_hobbies": 0.0001704692840576172, "__label__industrial": 0.0008420944213867188, "__label__literature": 0.0007967948913574219, "__label__politics": 0.0006103515625, "__label__religion": 0.0008101463317871094, "__label__science_tech": 0.297607421875, "__label__social_life": 0.00017464160919189453, "__label__software": 0.00881195068359375, "__label__software_dev": 0.67822265625, "__label__sports_fitness": 0.00042724609375, "__label__transportation": 0.0009622573852539062, "__label__travel": 0.0002715587615966797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44449, 0.03514]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44449, 0.34727]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44449, 0.83174]], "google_gemma-3-12b-it_contains_pii": [[0, 2874, false], [2874, 6439, null], [6439, 10158, null], [10158, 13858, null], [13858, 17846, null], [17846, 21409, null], [21409, 24558, null], [24558, 28183, null], [28183, 31562, null], [31562, 34002, null], [34002, 36472, null], [36472, 38208, null], [38208, 41081, null], [41081, 43671, null], [43671, 44449, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2874, true], [2874, 6439, null], [6439, 10158, null], [10158, 13858, null], [13858, 17846, null], [17846, 21409, null], [21409, 24558, null], [24558, 28183, null], [28183, 31562, null], [31562, 34002, null], [34002, 36472, null], [36472, 38208, null], [38208, 41081, null], [41081, 43671, null], [43671, 44449, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44449, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44449, null]], "pdf_page_numbers": [[0, 2874, 1], [2874, 6439, 2], [6439, 10158, 3], [10158, 13858, 4], [13858, 17846, 5], [17846, 21409, 6], [21409, 24558, 7], [24558, 28183, 8], [28183, 31562, 9], [31562, 34002, 10], [34002, 36472, 11], [36472, 38208, 12], [38208, 41081, 13], [41081, 43671, 14], [43671, 44449, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44449, 0.03704]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
51b49245e9f2423a5c4113293aa463d73ed56c02
|
Routing in Barrellfish
Barrellfish Technical Note 006
Akhilesh Singhania, Alexander Grest
01.12.2013
Systems Group
Department of Computer Science
ETH Zurich
CAB F.79, Universitätstrasse 6, Zurich 8092, Switzerland
http://www.barrellfish.org/
# Revision History
<table>
<thead>
<tr>
<th>Revision</th>
<th>Date</th>
<th>Author(s)</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.0</td>
<td>09.06.2010</td>
<td>AS</td>
<td>Initial version</td>
</tr>
<tr>
<td>1.01</td>
<td>14.06.2010</td>
<td>AS</td>
<td>Added discussion of design and unresolved issues</td>
</tr>
<tr>
<td>1.02</td>
<td>23.07.2010</td>
<td>AS</td>
<td>More work on design and API</td>
</tr>
<tr>
<td>2.0</td>
<td>31.05.2011</td>
<td>Alexander Grest</td>
<td>Multi-hop messaging</td>
</tr>
<tr>
<td>2.1</td>
<td>01.12.2013</td>
<td>TR</td>
<td>Some explanation</td>
</tr>
</tbody>
</table>
Chapter 1
Motivation
This technical note describes a set of design proposals (and prototype implementation) of multi-hop message routing in Barrelfish – how to send messages between cores which do not have a direct connection between them. This arises in, for example, Ethernet communication with a fully-distributed Barrelfish instance, or between multiple cores spread out over a PCIe bus (as is the case with Xeon Phi or Intel SCC).
All inter-core communication in Barrelfish is performed using explicit messages, which are carried over Interconnect Drivers (ICDs), specialized messaging subsystems that carry data between cores. At present, all communication happens over direct point-to-point ICD links. However, there are multiple motivations for extending this. In this note, we motivate the introduction of a routing layer in Barrelfish.
1.1 Partial connectivity
Most current multicore machines are fully connected via shared memory. This means that any core in the system can communicate with any other core in the system by using shared memory. Most applications are also designed accordingly. However, this assumption is not necessarily true on modern hardware, as the following two examples illustrate:
- On the Intel Single Chip Cloud Computer (SCC), the set of memory a core can access is determined by the setup of its Look Up Tables (LUTs). It is possible that these tables are set-up in such a manner that two or more cores do not have access to the same region of memory. In such cases to communication these cores will have to route via another set of cores if such a path exists.
- If Barrelfish is operated on a cluster of machines, there is only an Ethernet-based ICD link between the core(s) where the network stack is running. In order to allow every core to communicate with every other core, the available link must be multiplexed.
This are two examples of current set-ups which lead to partial connectivity. A routing layer akin to the one in IP routing will allow applications to communicate in such environments, without having to worry about the concrete path a message takes from one core to another. The routing layer will properly route messages in a transparent way.
1.2 Resource usage
ICD links require resources. In particular, a link uses the following resources:
- **Memory**: Any ICD link will require some memory to buffer unsent messages and messages that have been received but not yet delivered. Some links will require additional memory for the
channel itself. For instance, the shared-memory UMP driver on x86 requires two pages of physical memory per binding. In general, the amount of memory required is governed by the number of messages in flight and the number of messages in buffer.
- **CPU**: Some ICDs, as for example the UMP driver on x86, require explicit polling to check for incoming messages. The more links a core has, the more time it has to spend polling.
- **Cache**: If an ICD uses polling to check for incoming messages, the polled cache line will be placed in the cache. If the core has many ICD links, a significant part of its cache will be flushed due to polling.
The more ICD links a core has, the more of its resources will be used for them. This is detrimental to a high-performance system. By limiting the number of links, we will limit the amount of resources required. One way to limit the number of links is to multiplex multiple channels over one ICD link and therefore not construct a fully connected network.
### 1.3 Heterogeneous IDC
Barrelfish supports various IDC mechanisms. Different mechanisms provide different semantics and guarantees such as maximum frame size, notification mechanism, synchrony, etc.
An application can utilize multiple IDC mechanisms. This can happen if a homogeneous machine supports multiple IDC mechanisms or if the application runs on a heterogeneous machine. To avoid the need for the application to understand the different semantics of all IDC, it can conform to the semantics provided by the routing library.
The semantics provided by the routing layer are discussed in section 4.2.
### 1.4 Group communication
Various parallel computing abstractions such as barriers require communication among a group of threads. When any thread enters a barrier, it waits for all other threads to enter the barrier as well before continuing.
Various distributed communication abstractions such as achieving consensus also require communication among a group of nodes. A group of nodes that want to come to agreement on some value need to communicate with each other.
It has been shown [3, 1] that even in a fully connected machine, using some form of routing can improve the performance of group communication. The sender sends the message to a subset of nodes it wishes to communicate with. The subset will in turn forward it to the remaining set of nodes. The work has also shown that the order in which messages are sent also matters. The optimal route and ordering of messages is machine dependent.
If applications were written with the abstraction of a group layer, it will allow the library sufficient flexibility in selecting the optimal route based on the machine type.
Chapter 2
Multi-hop messaging
Multi-hop messaging is an important part of the routing layer. It gives applications a possibility to create a logical channel between two cores, that is routed over multiple nodes. This requires that available ICD links are multiplexed.
A multi-hop channel can only be set up between two dispatchers running on different cores. It always leads through the two monitors running on each dispatcher’s core. Between those two monitors the multi-hop channel can lead through an arbitrary number of additional monitors. We call all the monitors that lie on a multi-hop channel nodes. All the nodes of a multi-hop channel must be connected by means of other ICD-links (such as LMP or UMP ICD-links).
Once a multi-hop channel is set up, it can be used to exchange messages between the two dispatchers. The multi-hop channel transports messages by passing them to the underlying interconnect driver on each link between the nodes of the multi-hop channel.
The multi-hop interconnect driver consists of
- A mechanism to set up new multi-hop channels between dispatchers addressed by end-point identifiers
- A mechanism to send messages along a multi-hop channel
- A mechanism to receive messages from the channel
2.1 Design goals
2.1.1 Independence of the underlying interconnect driver
The multi-hop interconnect driver was designed to be independent of the type of the underlying ICD links between the nodes on the multi-hop channel. This means that it uses the common flounder interface supported by all ICDs when interacting with the underlying ICD link and uses no ICD-specific knowledge. This design involves a performance penalty: Interacting directly with the underlying ICDs instead of via the common flounder-interface would certainly perform better. Nevertheless, we chose this design, as it gives us more flexibility: The multi-hop interconnect channel can run over all present and future interconnect drivers in Barrelfish, as long as they support the common flounder interface.
2.1.2 Reliability
Interconnect drivers in Barrelfish generally provide a reliable messaging service: A message is delivered only once and each message sent is eventually delivered and its content is not corrupted. Furthermore,
messages are delivered in FIFO order. The multi-hop interconnect driver is designed to provide a reliable messaging service in principle. However, contrary to the end-to-end argument, it does not provide any end-to-end reliability, but builds on the reliability provided by the interconnect drivers of the underlying links. We accept that the multi-hop interconnect driver can fail in case any of the interconnect drivers of the underlying link fail.
2.1.3 Resource usage
Because it is our goal to optimize resource usage, the multi-hop interconnect driver is designed to perform considerably better in terms of resource usage compared to the scenario where we only use direct point-to-point ICD links. In particular, we save memory, because the multi-hop driver has a comparably small memory footprint.
2.2 Design overview
Messaging in Barrelfish is connection-oriented: messages are passed via an explicit binding object, which encapsulates one half of a connection, and such a binding must be established in advance. Therefore, we have decided to support only connection-oriented multi-hop messaging (for now). The multi-hop interconnect driver is designed in such a way that channel set-up is collapsed into the binding phase.
We use virtual circuit switching in order to multiplex multiple multi-hop channels over the available ICD links. Virtual circuit switching has several advantages over a packed-switched approach. It ensures that all messages take the same path and thereby FIFO delivery of messages (as long as the underlying ICD links provide FIFO delivery). Moreover, it allows to create per-circuit state on the nodes of a virtual circuit.
Each monitor maintains a forwarding table. For each multi-hop channel, entries are created in the forwarding tables at all the nodes of that channel. Messages that are sent over the channel are forwarded at each node according to its forwarding table. Those entries in the forwarding tables can be seen as per-channel created hard state: It is explicitly created at channel set-up and deleted at channel tear-down. Additionally to the entries in the forwarding table, per-channel created state includes bindings to the neighbouring nodes on the multi-hop channel.
In addition to the forwarding table, each node maintains a routing table. The routing table is used for channel set-up: If a node receives a channel set-up request, it determines where to forward the request with the help of its routing table.
The virtual circuit switching approach would also allow to reserve some resources on the nodes for each channel. Per-channel reserved resources could include buffer space to save received, but not yet forwarded messages, or bandwidth on the ICD links. This is potentially very useful for congestion and flow control. Note that we cannot simply drop messages in case of congested links, as we want to provide a reliable messaging service. As of now, we do not reserve resources on the nodes, but allocate required resources dynamically.
2.3 Additional monitor bindings
A multi-hop channel is multiplexed over the available ICD links. However, for each multi-hop channel, there will be two additional ICD links: Two additional LMP channels will be created between the client’s dispatcher and the monitor running on its core and between the service’s dispatcher and the monitor on its core. LMP channels are rather cheap - they do not require polling and require only a small amount of memory. Therefore, this does not compromise our goal of optimizing resource usage. Figure 2.1 shows an example set-up of a multi-hop channel with the two additional LMP channels.
Those additional channels are needed to ensure that the default monitor binding is not congested or even blocked by multi-hop messages. For example, suppose that a client’s dispatcher receives a lot of multi-hop messages within a short period of time. The client reacts to this by allocating more memory. If multi-hop messages are sent over the default monitor binding, the message coming from the memory server will be blocked, therefore this will result in a deadlock. By creating new monitor bindings and not using the default monitor binding, we can prevent such a scenario.
2.4 Virtual circuit identifiers
Multi-hop messages carry a virtual circuit identifier (VCI). Virtual circuit identifiers allow nodes to identify the particular multi-hop channel a message belongs to. Each node on a multi-hop channel maintains a forwarding table, which maps VCIs to the next hop on that particular channel. A node forwards multi-hop messages based on this forwarding table. At channel end-points, a VCI allows to identify the binding belonging to the multi-hop channel the message was sent over. Virtual circuit identifiers are not only local to a specific link, but also to a direction on that link. Figure 2.2 shows an example assignment of VCIs.
We assign virtual circuit identifiers at random. At each node, we use a hash table to map virtual circuit identifiers to a pointer to the channel state. The use of a hash table allows efficient message forwarding. When a message arrives, it can be determined where to forward this message by means of a simple look-up in the hash table. The complexity of this lookup is linear in the number of virtual circuit identifiers that map to the same hash bucket (the number of buckets in the hash table is a compile time constant).
An attacker sending messages with manipulated virtual circuit identifiers may be able to send messages on channels not belonging to him. By assigning virtual circuit identifiers at random, we make it very unlikely for an attacker to find valid virtual circuit identifiers of channels not belonging to him.
This design requires that each node on a multi-hop channel tells its neighbours what virtual circuit identifier they should use for messages sent over that particular channel. This happens in the set-up phase of a multi-hop channel (see section 2.5).
2.5 Channel set-up
If two dispatchers want to communicate with the help of the multi-hop interconnect driver, they have to create a multi-hop channel first. During channel-set up, one dispatcher must act as the client and the
The channel set-up process can be initiated by invoking the \texttt{multihop\_chan\_bind} function of the multi-hop interconnect driver. It has to be remarked that normally a user does not interact directly with the multi-hop interconnect driver, but only over the flounder generated stubs (see chapter 3).
The channel set-up process works as follows:
1. A client dispatcher initiates the set-up process by calling the bind function of the multi-hop interconnect driver. This function forwards the bind request to the monitor running on the client dispatcher’s core. The bind request includes various parameters, including the iref of the service and the client’s (ingoing) virtual circuit identifier.
2. The monitor running on the client dispatcher’s core determines (from the iref) the core on which the service resides. It then forwards the bind request to another monitor, which is determined based on the routing table.
3. Monitors receiving the bind request check whether the service is running on the same core as they are. If so, they determine the local dispatcher which has exported this iref and forward the request to it. Otherwise, the bind request is forwarded to another monitor in the same way as in step two.
4. As soon as the service’s dispatcher receives the bind request, it runs the user provided connection callback. Based on the return value of this callback, it either accepts the connection or rejects it. In any case, the bind reply is sent back to the monitor.
5. The monitor proxies the bind replay back to where it received the bind request from.
6. If the client dispatcher receives the bind reply, it will run the user provided bind callback.
In order to support setting up connections between dispatchers, the existing messaging interfaces between dispatchers and their local monitor, and between monitors has been extended.
As described in section 2.4, it is necessary that each node on the multi-hop channel tells its neighbouring nodes what virtual circuit identifier they should use for messages sent over that particular channel. Therefore, each message contains the virtual circuit identifier of the sender. The two response-messages additionally contain the VCI of the receiver. This allows the receiver of a response-message to identify the multi-hop channel the message belongs to.
2.6 Message forwarding
Once the multi-hop channel is set-up, messages can be sent in both directions. A message can be sent by invoking the \texttt{multihop_send_message} function of the interconnect driver. This function requires that the message payload is passed as one (char) array. If a user-defined message contains multiple arguments that are not stored in continuous memory locations, either the user-defined message must be split up in multiple multi-hop messages, or a new array must be allocated and all message arguments must be copied into the newly allocated array (see chapter 3 for a discussion).
In order to support sending messages, the existing messaging interfaces between dispatchers and their local monitor, and between monitors has been extended. Each multi-hop message contains a VCI, a field encoding the direction of the message and the message payload (as a dynamic array). Furthermore, it contains one field encoding message flags and another field used to acknowledge received messages. Those two fields are used for flow control (see section 2.10).
As a multi-hop channel allows to send messages in two directions, the direction field is needed to identify the direction of a particular message. Currently we assign direction “1” to all messages going from the dispatcher who initiated the multi-hop channel to the other dispatcher, and direction “2” for messages going the opposite way.
This definition of a multi-hop is motivated by the fact that it must be possible to transport an arbitrary message within one (or more) multi-hop messages. By using a dynamic array argument for the message payload, we can transfer data of an arbitrary size in a multi-hop message.
Internally, multi-hop messages are forwarded at every node of a multi-hop channel until they reach the receiver. We make sure that multi-hop messages cannot overtake other multi-hop messages at the nodes by enqueuing messages in the order they arrive and forwarding them in a FIFO order.
2.7 Capability forwarding
Because capabilities are maintained as references to per-core state in the CPU drivers, only the LMP interconnect driver which traverses kernel-mode code can directly deliver a capability along with message payload. In the multi-hop interconnect driver, capabilities travel out-of-band from other message payload.
To send a capability, the monitor sends a \texttt{multihop_cap_send} message to its local monitor, containing the capability. The monitor determines whether the capability can be sent to the remote dispatcher. In general, capabilities referring to inherently local state (such as LMP endpoint) may not be sent, nor may capabilities that are currently being revoked. If the capability cannot be sent, a \texttt{multihop_cap_reply} message is sent back to the local dispatcher containing the error code. Otherwise, the capability is serialised and forwarded along the multi-hop channel.
The monitor running on the receiver’s core reconstructs the capability from its serialised representation and forwards it to the destination dispatcher. This dispatcher identifies the binding to which the capability belongs and invokes a callback on that binding.
The capability sender only receives a reply message in case an error occurs. An error can occur if for example the capability cannot be sent or the receiver has no space left to accommodate an additional capability.
2.8 Receiving messages
In order to receive messages sent over a multi-hop channel, message handlers must be registered with that multi-hop channel. In particular, three message handlers must be registered: one message handler
for “normal” messages, one handler for incoming capabilities and one handler for capability reply messages (that are sent in case an error occurred while sending a capability).
The flounder generated stubs for the multi-hop interconnect driver (see chapter 3) register those message handlers, not the application itself (normally).
2.9 Routing tables
The routing tables are used to determine where to forward a connection set-up request. Each monitor needs its own routing table. We currently support the automatic generation of routing tables for three basic modes of routing:
1. **Direct**: All set-up requests are immediately forwarded to the end-receiver.
2. **Ring**: We route over all cores of a system. Core $i$ forwards a request to core $i + 1 \mod \text{num\_cores}$.
3. **Fat tree**: We route directly between the cores that are located on the same CPU socket. On each socket, we choose a “leader” and route directly between all leaders. A set-up request for a core on a different socket is always forwarded over the local leader to the leader on that socket.
For the routing modes “ring” and “fat tree” we need information from the system knowledge base: We need to know the number of cores in the system for the “ring” routing mode. For the “fat tree” mode, we additionally need to know the number of cores per CPU socket (note that we assume here that sockets are continuously numbered).
We decided that there should be no direct communication between the monitor and the system knowledge base, because it is not always present. For some architectures, such as Microsoft’s experimental Beehive architecture or to a certain extend the Intel Single Chip Cloud Computer, the system knowledge base is not available. Therefore, a dependency of the monitor on the system knowledge base should be avoided.
For this reason, we decided to create a separate module, called the **routing table set-up dispatcher** (RTS) that talks to the system knowledge base and to the initial monitor (the monitor that is first booted). The routing table set-up dispatcher will retrieve the required information from the system knowledge base in order to construct the routing table. Once it has constructed the routing table, it will send it to the initial monitor.
The initial monitor will forward the (relevant parts of the) routing table to the other monitors once they are booted. This is necessary because we want to avoid having to create a channel between each monitor and the routing table set-up dispatcher.
It must be noted that the routing table set-up dispatcher can only generate the routing tables for the cores of a single system. It cannot handle set-ups like an Intel single chip cloud computer connected to a x86 machine over a PCIe-based channel.
2.10 Flow control
It is possible that one dispatcher on a multi-hop channel is sending at a faster rate than the receiving dispatcher can handle incoming messages and process them. Because we want to provide a reliable messaging service, we cannot just drop messages in such a case, but have to buffer them and deliver them eventually. To limit the space needed to buffer undelivered messages, we decided to implement a flow control mechanism within the multi-hop interconnect driver. The flow control mechanism allows the receiving dispatcher to control the transmission speed, so that it is not overwhelmed with messages.
We decided to use a credit-based flow control mechanism: The number of messages in flight at any given time is limited. Once a sender has reached this limit, he has to wait until he receives an acknowledgement that the receiver has processed previously sent messages. We call this limit the **window size**.
The flow control mechanism is completely transparent to applications. It is entirely handled by the multi-hop interconnect driver. On each message sent by a dispatcher over a multi-hop channel an acknowledgement for all messages previously received over this channel is piggy-backed.
If an application uses a one-way communication schema, i.e. one dispatcher is always sending while the other is only receiving, it is not possible to piggy-back acknowledgements on messages sent the other way. In such a case, the multi-hop interconnect driver sends a dummy message. A dummy message contains no message payload, but acknowledges all received messages. This approach ensures that acknowledgements are, whenever possible, piggy-backed on messages. Only if it is absolutely necessary, an acknowledgement is sent in its own message.
Chapter 3
Flounder support for multi-hop messaging
Flounder is a stub compiler which generates stubs for defined interfaces. To support multi-hop messaging, we created a new back-end code generator for the flounder stub compiler that generates code to use the multi-hop interconnect driver. Applications do not interact with the multi-hop interconnect driver directly, but only over the generated stubs. The stubs for the multi-hop interconnect driver have the exact same interface as stubs for other interconnect drivers. This makes application code independent of the interconnect driver used for communication.
The generated stubs can be seen as an “adaptor” to the multi-hop interconnect driver. They translate calls to the common flounder interface to the interface of the multi-hop interconnect driver. Supported functionality mainly includes binding, sending and receiving of multi-hop messages and some control operations.
3.1 Binding
If two dispatchers want to communicate with the help of the multi-hop interconnect driver, they must acquire binding objects for each endpoint of the channel. In any binding attempt, one dispatcher must act as the client and the other as the service (however, once a binding is established, the communication process on both sides of the binding is indistinguishable). The binding phase is merged with channel set-up, i.e. a new multi-hop channel will be created during the binding process.
In order to initiate a binding, a client dispatcher calls the bind function for a given interface. Because Barrelfish features multiple interconnect drivers, the interface’s bind function will have to decide which interconnect driver to use in order to establish the binding. Currently, it “asks” the different interconnect drivers to establish a binding in a predefined order (for example, the LMP driver is always first). As soon as an interconnect driver manages to establish the binding, the binding process is finished. Should one interconnect driver fail, the next one in order is tried.
If an application wants to create a new multi-hop channel, it can pass the flag IDC_BIND_FLAG_MULTIHOP as an argument to the interface’s bind function. This changes the order of the interconnect drivers: The multi-hop interconnect driver will come in second place, directly after the LMP driver. The LMP driver is first, because it is preferable to the multi-hop interconnect driver if client and service are running on the same core. If the multi-hop interconnect driver fails to establish a binding for some reason, the binding process continues as normal with the other interconnect drivers.
The result of the binding process on the client’s and service’s side is a binding object which is the abstract interface to the multi-hop interconnect driver for a specific interface type.
3.2 Sending messages
A message may be sent on the binding by calling the appropriate transmit function. We distinguish between user-defined messages and multi-hop messages. User-defined messages are those messages defined by the user in the interface. Multi-hop messages are messages that are sent over a multi-hop channel.
As pointed out in section 2.6, the multi-hop interconnect driver requires that the message payload is passed as one char array. If a user-defined message contains dynamic arguments (arguments whose size is only known at run-time), such as a string or a dynamic array, it is generally not possible to pass the message payload as one char array to the multi-hop interconnect driver. There are three possible approaches to send such a message:
1. Allocate a region of memory capable of holding all message arguments and copy the message arguments to this region. A pointer to it can then be passed to the multi-hop interconnect driver as message payload.
2. Split a user-defined message into multiple multi-hop messages. Each argument of the multi-hop message is transported in its own multi-hop message.
3. Use a combination of the above approaches. For instance, all fixed size arguments could be sent in one message, and each dynamically sized argument could be sent in an extra multi-hop message.
In comparison to approach 1, approach 2 saves the cost of allocating a region of memory and copying all the arguments of the message to that region. In exchange for that, it needs to split a user-defined message and transport it via multiple multi-hop messages. The preferable approach depends on the type of messages that are sent. However, we think that the performance penalty involved in sending each message argument in its own multi-hop message is not acceptable for most message types. Therefore, the flounder-generated stubs for the multi-hop interconnect driver use approach 1. Approach 3 might be a possible performance optimization, but is currently not in use.
3.2.1 Implementation
All message arguments are copied to continuous memory locations in order to send the whole user-defined message in one multi-hop message. When sending a user-defined message, we first calculate the size of its payload. The size of a message’s payload is only known at compile-time if the message definition does not contain any dynamic arguments. Otherwise, the size of the payload has to be computed each time such a message is sent. After having computed the payload size, we allocate a memory region of that size and copy the message arguments to that region of memory. Finally, we pass a pointer to this memory region to the multi-hop interconnect driver.
We include the size of every dynamically sized argument in the message payload. This tells the receiver about the size of those arguments and allows him to retrieve them from the received message payload. Currently, we use 8 bytes to transfer the size of a dynamic argument. This ensures that we do not get an overflow. We account for those size fields when calculating the size of the message payload.
Capabilities are never sent as message payload. They are always sent out-of-band from “normal” message payload. A discussion of this can be found in section 2.7.
There is one issue regarding communication in heterogeneous systems of our implementation: To be consistent with the common flounder interface, we have to use a variable of type size_t to represent the size of a dynamic array. The type size_t is architecture dependent. On a 32-bit system it will likely be at least 32-bits wide. On a 64-bit system it will likely be at least 64-bit wide. If a dispatcher on a 64-bit system communicates with a dispatcher on a 32-bit system, this can lead to a problem: The dispatcher on the 64-bit system can potentially send dynamic arrays that are bigger than the dispatcher on the 32-bit system can receive. This is a problem of the current Barrelfish version and remains unsolved.
3.2.2 Send continuation
Each transmit function takes as an argument a pointer to a continuation closure. The closure will be executed after the message has successfully been sent. If another transmit function is called on the same binding before the continuation is executed, it will return the FLOUNDER_ERR_TX_BUSY error code, indicating that the binding is currently unable to accept another message. In this case, the user must arrange to retry the send.
The send continuation is the only way to know when a message has been sent over the multi-hop channel and it is safe to send the next message. Note that even if an application uses a ping pong communication scheme, i.e. it sends a message back and forth between two dispatchers, it is not guaranteed to not get a FLOUNDER_ERR_TX_BUSY error code, unless it serialises all sends with the continuation. This somewhat unintentional behaviour is caused by the fact that the multi-hop channel internally relies on other ICD-links to transport messages. The multi-hop channel itself uses send continuations on the underlying ICD-links to determine when it can accept another message. Those send continuations are always executed after a message is sent. Therefore it is possible (although unlikely) that a message is sent and the reply for that message is received, before the multi-hop channel can accept the next message.
3.3 Receiving messages
The flounder-generated stubs register a callback function with the multi-hop interconnect driver at channel set-up time in order to be notified when a message arrives. As we send a user-defined message within a single multi-hop message, we therefore also receive a user-defined message in one multi-hop message.
Upon receiving a multi-hop message, we have to extract the original user-defined message from it and pass it on to the user-provided receive handler. It is a fatal error if a message arrives on a multi-hop channel and the receive handler function for that message type is not set.
If the user-defined message contains dynamic arguments, we have to allocate space for each of those arguments separately and copy them from the received multi-hop message. This is necessary, because all dynamic message arguments are passed by reference to the user and become property of the user. The user must be able to free those arguments separately, therefore they must be copied to separately allocated memory. Fixed-size arguments are simply passed on the stack to the user.
Chapter 4
Group Communication
4.1 Terminology
Groups: The set of all nodes on the machine form a universe group. The set of nodes in the universe group that wish to communicate with each other form an application group. An application group is a subset of the universe group. A subset of nodes in the application group can form a multicast group.
It is possible to join and leave any multicast and application group.
IDs: Each application group is identified by a group ID. The group ID in turn identifies the instance of routing library to use. The group ID is unique within the universe group.
Each multicast group is identified by multicast ID. The multicast ID is unique within the application group.
When nodes join an application group, they are assigned a node ID. The node ID is unique within the application group.
Each node is also given an application broadcast ID. These may or may not be unique and are drawn from a set that may just have a single element.
The union of the set of node ID, multicast ID, and application broadcast ID is called the destination ID. The set of node IDs, multicast IDs, and application broadcast IDs are disjoint.
Messaging: It is not possible to communicate with nodes in the universe group that are not in the application group.
A node can send a message to another node in the application group by sending a message to the appropriate node ID. A node can send a message to all nodes in the application group by sending a message to the application broadcast provided to it. A node can send a message to all nodes in a multicast group by sending a message to the multicast ID provided to it when it joined the multicast group.
Types of messages: Unicast: Send a message to a single node in the application group. Broadcast: Send a message to all nodes in the application group. Multicast: Send a message to all nodes in the multicast group.
4.2 Semantics
The routing layer will provide a uniform set of semantics to the application layer regardless of the set of semantics the IDC mechanisms below it provide. It can provide different semantics to suit the needs of different application scenarios.
Below, we discuss the different set of semantics it can provide.
### 4.2.1 Set 1: Single source FIFO
The set of semantics provided are as follows:
- **Reliability**: A message is delivered only once and only if it was sent earlier. Each message is eventually delivered and the contents are not corrupted.
- **Single source FIFO ordering**: If a sender sends $m$ before $m'$ then $m$ is delivered before $m'$ at all receivers.
- **Failure**: The routing library will not fail.
- **Payload**: The IDC can deliver an arbitrarily sized message.
### 4.2.2 Set 2: Causal order
The set of semantics provided are as follows:
- **Reliability**: A message is delivered only once and only if it was sent earlier. Each message is eventually delivered and the contents are not corrupted.
- **Causal ordering**: If the delivery of message $m$ depends upon the delivery of message $m'$ as per the happened before relationship [2], then $m$ is not delivered till $m'$ has been delivered.
- **Failure**: The routing library will not fail.
- **Payload**: The IDC can deliver an arbitrarily sized message.
### 4.2.3 Set 3: Total order
The set of semantics provided are as follows:
- **Reliability**: A message is delivered only once and only if it was sent earlier. Each message is eventually delivered and the contents are not corrupted.
- **Total order**: All messages are delivered to all nodes in the same order.
- **Failure**: The routing library will not fail.
- **Payload**: The IDC can deliver an arbitrarily sized message.
It is possible to order messages using various types of ordering mechanisms. Investigation of this remains future work.
### 4.2.4 Additional sets
In future, if we choose to provide additional set of semantics, they will be listed here. They could include weaker semantics than above if the underlying IDC mechanism are too expensive. Some example are just reliability, or not even providing reliability.
### 4.3 Interface
We discuss the interface for group management and sending/receiving of messages.
4.3.1 Group management
**Creating groups:** Before nodes can join a group, they need to be created. Any dispatcher in the system can create a new application group and any node in an application group can create a new multicast group within the application group.
The library will return to application a group ID or multicast ID of the created group.
**Updating a group:** A dispatcher can join any application group by calling join on the application group ID. A node can join any multicast group within the application group it is part of. When the join has finished, the node gets the join callback from the library. When a dispatcher is done joining an application group, it can query the library for its node ID and application broadcast ID.
Similarly a node can leave a group at anytime by calling leave on the group ID. When the leave is done, the application will get a leave callback. A dispatcher should call leave before it exits the system.
The behavior of the group is undefined while membership is in flux. New links are being created and old links are being torn down. Messages may not reach their proper destination. If such guarantees are required at all times in the application, the application must refrain from sending messages while group member is in flux.
4.4 Flow control
The IDC mechanisms that the routing library operates over are asynchronous. When a message is sent over them, it will eventually be delivered to the receiver. Undelivered messages are maintained in a queue of fixed length. If the sender tries to send messages too quickly the queue can fill up. If the queue is full, the sender must wait till the queue has room for more messages. IDC mechanisms allow senders to register callbacks in such situations. When a send fails with the transient error that the queue is full, the sender can register a callback which will be called when the next send should not fail. While the sender waits for the callback, it has to handle the unsent message.
We discuss the simple scenario of two nodes and then a more complex scenario of many nodes.
4.4.1 Client-server model
Figure 4.1 shows a simple client-server model of two nodes that are directly connected. The weights on the edges is the length of the queue. The client sends messages to the server, the server processes them.
and sends replies to the client. It is possible that link1 becomes full maybe because the client has not been handling replies on it. At this point the server has some options:
- Drop the message. The server can simply drop the message if the queue is full. This will result in an unreliable channel.
- Allocate some resources and queue the message up. This implies unbounded resource requirement.
- Apply back pressure on the client. The server at this point can stop processing messages from the client till it is able to send messages to it again.
In this model the last option works well as it will force the client to slow down and process replies before sending more requests.
### 4.4.2 Multihop route
In this scenario the problem is more complex. Figure 4.2 shows a group of 5 nodes, the link weights specifies the queue length of the link. If node1 and node2 are sending messages to node4, link34 will fill up before link13 or link23 does. Node3 cannot send additional messages to node4. At this point, node3 has the following options:
- Continue to process incoming messages on link13 and link23. If they are destined for node4, drop them. This will result in an unreliable channel.
- Continue to process incoming messages and if they are destined for node4, queue them up locally. This implies unbounded resource requirement.
- Stop processing messages on link13 and link23. This will delay messages on those links that were not destined to node4. In literature, this is called *Head of line blocking* [?].
None of these solutions are particularly desirable. Flow control in the context different types of networks has been studied previously.
Relevant existing work includes:
- Credit based flow control: The endpoints dictate maximum number of messages in flight.
- TCP flow control
- Ethernet flow control
- Datacenter ethernet flow control
• Related work in routing between sockets on a machine
• QoS (DiffServ and IntServ).
Some applications may not be willing to pay the cost of flow control. Further, a flow control mechanism that guarantees reliability may not scale well with number of nodes. We discuss some abstract ideas we have for flow control below.
4.5 Open questions
Some open questions
4.5.1 Reservation of resources with end-to-end flow control
The essential idea is that when a route is established, reservations for some number of in flight messages are made for the route. Even though the links might be shared, no other routing path is allowed to use the reserved resources. The endpoints must then limit the number of in flight messages. If they exceed it, the library can deliver an error at the endpoint or try to optimistically deliver the message and drop the message if it is unable to.
For example, in figure 4.2, if reservations for two messages is made for the routing path from node1 to node4, node1 and node3 each will maintain a queue of size 2. Whenever they receive a message from the application in node1 destined to node4 and they are not able to send it on the link, they can locally store the message. Eventually, when the link has space in it, they can try to send the message again.
It remains to be seen if the approach can work and scale well. [Cite work on switching networks and other works that make reservations and give guarantees.]
This approach works when the nodes that are sharing the links cooperate with one another. However, if the link is shared between distrustful nodes then additional guarantees of fairness and no starvation maybe required.
Figure 4.3 shows a network of two monitors. Each monitor is connected to two clients. Clients A1 and A2 are cooperating and client B1 and B2 are cooperating. The clients want to send some messages that must go through the monitors such as transferring capabilities. If one pair of client is aggressive in sending messages, it may fill up the link between the monitors and impact the performance of the other pair of clients. In this scenario, the link between the monitor can be seen as a common system resource that is being multiplexed between the users. The monitors should guarantee some fairness to the users in using this link.
4.5.2 Discovering node IDs
When a set of dispatchers join an application group, each of them is assigned a node ID. The nodes need some mechanism of discovering the IDs of each other so that they can message each other.
The discovery service will be built on top of the routing library and can be designed in multiple ways. Nodes can send broadcasts to each other informing each other of their node IDs, they can use the name service, etc.
Figure 4.3: A network of monitor with clients
Chapter 5
Interesting benchmarks
Some benchmarks that validate the claims of above and show the performance of the library.
[Costs of one-to-many channels. One sender, multiple readers.]
[Comparison of routes with no forwarding and routes with forwarding]
[Resource requirements for channels, memory and cpu time.]
[Cost of the discussion group membership update mechanism.]
Chapter 6
Fun research questions
- Flow control
- Link state vs. distance vector routing
References
|
{"Source-Url": "http://www.barrelfish.org/publications/TN-006-Routing.pdf", "len_cl100k_base": 9350, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 41516, "total-output-tokens": 10437, "length": "2e13", "weborganizer": {"__label__adult": 0.0003333091735839844, "__label__art_design": 0.0003387928009033203, "__label__crime_law": 0.00030684471130371094, "__label__education_jobs": 0.0005946159362792969, "__label__entertainment": 0.00010520219802856444, "__label__fashion_beauty": 0.00015628337860107422, "__label__finance_business": 0.0002536773681640625, "__label__food_dining": 0.0003542900085449219, "__label__games": 0.0007829666137695312, "__label__hardware": 0.0059661865234375, "__label__health": 0.00041031837463378906, "__label__history": 0.0004014968872070313, "__label__home_hobbies": 0.0001081228256225586, "__label__industrial": 0.0007548332214355469, "__label__literature": 0.00022470951080322263, "__label__politics": 0.00026416778564453125, "__label__religion": 0.0005779266357421875, "__label__science_tech": 0.1434326171875, "__label__social_life": 7.212162017822266e-05, "__label__software": 0.020904541015625, "__label__software_dev": 0.822265625, "__label__sports_fitness": 0.00031757354736328125, "__label__transportation": 0.0008792877197265625, "__label__travel": 0.0002493858337402344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46556, 0.02896]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46556, 0.261]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46556, 0.91457]], "google_gemma-3-12b-it_contains_pii": [[0, 246, false], [246, 1030, null], [1030, 3530, null], [3530, 6232, null], [6232, 8483, null], [8483, 12119, null], [12119, 14678, null], [14678, 17010, null], [17010, 20640, null], [20640, 24342, null], [24342, 25172, null], [25172, 27992, null], [27992, 31961, null], [31961, 34441, null], [34441, 36598, null], [36598, 38628, null], [38628, 40952, null], [40952, 42814, null], [42814, 45559, null], [45559, 45605, null], [45605, 45983, null], [45983, 46074, null], [46074, 46556, null]], "google_gemma-3-12b-it_is_public_document": [[0, 246, true], [246, 1030, null], [1030, 3530, null], [3530, 6232, null], [6232, 8483, null], [8483, 12119, null], [12119, 14678, null], [14678, 17010, null], [17010, 20640, null], [20640, 24342, null], [24342, 25172, null], [25172, 27992, null], [27992, 31961, null], [31961, 34441, null], [34441, 36598, null], [36598, 38628, null], [38628, 40952, null], [40952, 42814, null], [42814, 45559, null], [45559, 45605, null], [45605, 45983, null], [45983, 46074, null], [46074, 46556, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46556, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46556, null]], "pdf_page_numbers": [[0, 246, 1], [246, 1030, 2], [1030, 3530, 3], [3530, 6232, 4], [6232, 8483, 5], [8483, 12119, 6], [12119, 14678, 7], [14678, 17010, 8], [17010, 20640, 9], [20640, 24342, 10], [24342, 25172, 11], [25172, 27992, 12], [27992, 31961, 13], [31961, 34441, 14], [34441, 36598, 15], [36598, 38628, 16], [38628, 40952, 17], [40952, 42814, 18], [42814, 45559, 19], [45559, 45605, 20], [45605, 45983, 21], [45983, 46074, 22], [46074, 46556, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46556, 0.02929]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
7f3ddf1b44717b99cfd01f95dd04c2191df877c1
|
[REMOVED]
|
{"len_cl100k_base": 10620, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 52745, "total-output-tokens": 13501, "length": "2e13", "weborganizer": {"__label__adult": 0.0005841255187988281, "__label__art_design": 0.0005478858947753906, "__label__crime_law": 0.0007114410400390625, "__label__education_jobs": 0.0011034011840820312, "__label__entertainment": 0.00016188621520996094, "__label__fashion_beauty": 0.0003132820129394531, "__label__finance_business": 0.0003991127014160156, "__label__food_dining": 0.0006184577941894531, "__label__games": 0.0016937255859375, "__label__hardware": 0.002201080322265625, "__label__health": 0.002101898193359375, "__label__history": 0.0006165504455566406, "__label__home_hobbies": 0.0001964569091796875, "__label__industrial": 0.0007681846618652344, "__label__literature": 0.0005245208740234375, "__label__politics": 0.00046896934509277344, "__label__religion": 0.0009398460388183594, "__label__science_tech": 0.212890625, "__label__social_life": 0.0001266002655029297, "__label__software": 0.007221221923828125, "__label__software_dev": 0.763671875, "__label__sports_fitness": 0.0006036758422851562, "__label__transportation": 0.0010290145874023438, "__label__travel": 0.0003535747528076172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39428, 0.04652]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39428, 0.13156]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39428, 0.80312]], "google_gemma-3-12b-it_contains_pii": [[0, 1789, false], [1789, 5480, null], [5480, 9497, null], [9497, 12444, null], [12444, 16745, null], [16745, 18945, null], [18945, 22321, null], [22321, 25789, null], [25789, 29182, null], [29182, 32591, null], [32591, 35642, null], [35642, 38344, null], [38344, 39428, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1789, true], [1789, 5480, null], [5480, 9497, null], [9497, 12444, null], [12444, 16745, null], [16745, 18945, null], [18945, 22321, null], [22321, 25789, null], [25789, 29182, null], [29182, 32591, null], [32591, 35642, null], [35642, 38344, null], [38344, 39428, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39428, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39428, null]], "pdf_page_numbers": [[0, 1789, 1], [1789, 5480, 2], [5480, 9497, 3], [9497, 12444, 4], [12444, 16745, 5], [16745, 18945, 6], [18945, 22321, 7], [22321, 25789, 8], [25789, 29182, 9], [29182, 32591, 10], [32591, 35642, 11], [35642, 38344, 12], [38344, 39428, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39428, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
96eb8e8fb69ffab97866ad505d0bf55350c52577
|
A Semantic Analysis Method for Scientific and Engineering Code
Mark E.M. Stewart
NYMA, Inc., Brook Park, Ohio
Prepared under Contract NAS3–27816
National Aeronautics and Space Administration
Lewis Research Center
April 1998
This paper develops a procedure to statically analyze aspects of the meaning or semantics of scientific and engineering code. The analysis involves adding semantic declarations to a user's code and parsing this semantic knowledge with the original code using multiple expert parsers. These semantic parsers are designed to recognize formulae in different disciplines including physical and mathematical formulae and geometrical position in a numerical scheme. In practise, a user would submit code with semantic declarations of primitive variables to the analysis procedure, and its semantic parsers would automatically recognize and document some static, semantic concepts and locate some program semantic errors. A prototype implementation of this analysis procedure is demonstrated. Further, the relationship between the fundamental algebraic manipulations of equations and the parsing of expressions is explained. This ability to locate some semantic errors and document semantic concepts in scientific and engineering code should reduce the time, risk, and effort of developing and using these codes.
2. Introduction
2.0 Motivation
With revolutionary increases in computer speed, scientific and engineering simulation has moved from the manual calculation of problems to computer simulation codes. Across a wide range of disciplines including aeronautics, astrophysics, combustion, geophysics, molecular dynamics, structural analysis, and weather and climate modeling, computer simulations inexpensively explore important problems that researchers previously studied only with experimental and theoretical methods. However, these scientific and engineering codes involve
a large number of semantic details including the implementation of formulae and manipulation of geometrical concepts. Even with current testing techniques, identifying errors in these semantic details is a problem that significantly hinders scientific code development.
The available software for developing and maintaining this scientific and engineering software includes modern computer languages, syntactic analysis (lint [14], ftnchek [18]), compilation control (make [6]), source debug tools (dbx), and version control (sccs). Further, there are widely accepted techniques for testing scientific programs—solution comparison with available analytic test cases, comparison with available experimental results, examination of the formal and observed order of accuracy of the numerical scheme, as well as verification of convergence. However, these are tests of an ensemble of details that may detect the presence of an error but cannot identify the faulty detail. A program containing either of the errors (2.0)
\[ P = \text{RHO} \times (E - (U \times U + V \times V)) \times (\text{GAM} - 1.0) \]
(2.0)
(pressure is incorrectly calculated from density, total energy (intensive), velocity, and the ratio of specific heats) or (2.1)
\[ FS(I,J,N) = DW(I+2,J,N) - 2.0 \times DW(I,J,N) + DW(I-1,J,N) \]
(2.1)
(the second difference is geometrically incorrect) will fail these traditional testing methods. However, finding these errors can be very difficult. In practise, developers use their knowledge and skill to devise diagnostic tests which narrow a manual search.
In manual checking, developers examine code, interpret its meaning and verify it is correct. However, manual checking is frequently incomplete and incorrect, always time consuming, and limited by the individual's semantic knowledge. To aid in manual interpretation, developers encode some semantic information in variable names, comments, and written documentation which must, however, still be processed manually.
What are the semantic details being checked? They include program execution order and logic which are not considered here. They also include mathematical and geometrical con-
cepts including derivatives, integrals, points, and vectors. Further, simulations use the physical principles and formulae of individual disciplines. For example, in aerodynamics the gasdynamics and Navier-Stokes equations are fundamental formulae. These mathematical, geometrical, and physical equations are an unambiguous domain of knowledge in contrast to the knowledge of other fields. Further, the representation of this mathematical and physical knowledge, in the form of mathematical notation, formulae, and specific terminology has evolved to be simple yet exacting. These properties make equations more suitable for implementation in a rule system than many other domains of knowledge.
This paper exploits these properties to perform automatic testing and documentation of some semantic concepts by using well established compiler techniques. Users must declare in their code some semantic information about primitive code variables. However, the current method parses this embellished code to recognize the patterns of stored mathematical, geometrical, and physical formulae. In this way, the code's semantic implementation is partially checked and documented. In particular, the code lines (2.0) and (2.1) can be recognized as incorrect.
The benefits of automated analysis and verification of code semantics include reduced time, risk, and effort during original code development, subsequent maintenance, second party modification, and reverse engineering of undocumented code. A satisfactory semantic analysis would also provide a useful but not sufficient test for correctness. Further, semantic recognition results are code documentation. These benefits should apply to codes in a wide range of scientific and engineering disciplines.
In the next subsections, related technology is explained, and some basic concepts and notation from compiler parsing are presented. The semantic analysis procedure and a prototype implementation are described in Section 3, some theoretical analyses of the problem are presented in Section 4, and finally, three test problems are shown in Section 5.
2.1 Related Technology
Currently, automatic code testing is largely limited to syntactic testing. Lint [14] and ftnchek [18] test programs for conformance with language syntax and portability rules. However, there are some basic semantic tests performed by these testing codes, such as type checking, which can reveal semantic errors. There are also efforts to organize and manage code
A body of work exists [17,19] in computer science where predicate logic is extended and used for Pascal program verification. Assertions are placed at crucial points in a Pascal code including entry and exit points. These assertions specify the code by defining relationships between program variables which must be true when execution passes the assertion's position in the code. The assertions are parsed with the code into verification conditions which are logical expressions. If all these verification conditions can be proven to be true with a theorem prover, then the program is consistent with its specification. Physical formulae and their geometrical interpretation do not enter this work. However, many practical concepts are similar including the need for parsing, program annotations, and a body of rules.
An influential approach to documentation is WEB [15] which allows natural language documentation to be embedded within a program. Different processors produce either compilable code or a natural language document. In this way, program documentation accompanies a code and is more readily updated when code is modified.
Influential and insightful work exists in fields other than program testing and documentation. Natural language analysis is concerned with dissecting the semantics of written and spoken language. Lexical analysis and parsing are computer algorithms used to automate this analysis [3].
Expert system techniques [12] also provide a means to encode and organize knowledge and to synthesize results from this knowledge. A classic expert system is INTERNIST [20,21], a program which attempts to duplicate the diagnostic reasoning of human medical clinicians. A number of other domain specific expert systems exist [12,23]. Bobrow [4] contains a number of papers on qualitative reasoning about physical systems and in particular about the diagnosis and verification of electronic circuits. The capabilities of expert systems pattern matching differ from programming language parsing. More complex rules can be constructed in an expert system than in a parser as will be explained in section 4. The pattern matching algorithm of choice for expert systems is the Rete algorithm [8].
2.2 Underlying Technology
The semantic analysis procedure developed in the next section uses well established compiler
In a compiler, a parser recognizes from the words and punctuation of a program which grammar rule of the programming language is being used. The acceptable programming language order is the syntax of the language, and it is represented by a set of grammar rules called a syntactic grammar. These compiler parsing techniques arose from a need for efficient, easily implemented methods for transforming an expressive, high-level programming language, such as FORTRAN or C, into machine code. Following the introduction of the first FORTRAN compiler [22], considerable theoretical and practical efforts were directed at improving parsers. LALR(1) parsing [1,2] emerged as a prominent method of implementing a compiler parser since the allowed grammar rules are expressive enough for most programming languages, and a set of grammar rules, called a grammar, can also be automatically converted to a parsing subroutine. In particular, the parser generator YACC [13,16] automatically transforms a set of grammar rules into a very fast parsing subroutine.
The words and punctuation of a programming language are represented by tokens and, like a natural language grammar rule, an LALR(1) syntactic grammar rule specifies a way these tokens can be placed in order. Two grammar rules are shown in (2.2). Grammar rules in this paper use a notation similar to YACC's. Unlike the sequential execution of C or FORTRAN code, a rule in a grammar executes when the rule pattern matches the input sequence. With these properties LALR(1) grammar rules are general enough to recognize more than programming language syntax rules, and in Section 3 they will be used to recognize code semantics.
\[
\begin{align*}
\text{var} & : \text{var} * \text{var} \\
& \quad \{ \text{calc_prod()}; \} \\
& \mid \text{var} + \text{var} \\
& \quad \{ \text{check_add()}; \} \\
\end{align*}
\]
Each LALR grammar rule (2.2) always has left- and right-hand sides and is terminated with a semicolon. The pattern to be matched is a sequence of one or more tokens, for example, \text{var} + \text{var} or \text{var} * \text{var} in (2.2), which is located to the right of the colon or vertical bar. To
the left of the colon is a single token called a non-terminal symbol, for example, \texttt{var} in (2.2). Action code may follow the pattern and is enclosed in braces, for example, \texttt{calc\_prod()} or \texttt{check\_add()}. Action code is supplied by the grammar rule writer and is executed when the rule pattern matches. Multiple grammar rules with the same left-hand side may be combined by replacing the colon with a vertical bar, as in (2.2). Every token in a grammar rule has an associated data structure which stores information about the token and may be used by action code. Among other functions, action code can be used to create and manipulate data structures representing the code. Compiler theory is explained by Aho [1,2].
The tokens and their associated concepts are represented in a hierarchical form resulting from token replacement. When the tokens in the input sequence match the pattern of a grammar rule, they are replaced in the sequence with the left-hand side token, for example, \texttt{var} in (2.2). This left-hand token can then be part of yet another pattern match, for example, in the case \texttt{var * var + var}. This hierarchy is not only structural but also semantic with leaves involving details and branches involving substantive concepts. In particular, with semantic grammar rules, one can move from an expression containing program variables to a derivative or integral and to a term in a differential equation.
3. Semantic Analysis Procedure
In this section, the details of an automatic semantic analysis procedure are developed. In particular, it is explained how semantic declarations and program code are represented and translated into semantic statements which can be recognized by semantic parsers. Further, the representation, organization, and storage of mathematical, physical, and geometrical equations in multiple semantic parsers is explained. Finally, prototype software for this semantic analysis procedure is demonstrated.
3.0 Semantic Declarations
A program’s primitive semantic quantities must be identified to the semantic analysis procedure, and this is done by including \textbf{Semantic declarations} within a user’s code. For example, the sample user program line
\[
\begin{align*}
C & \quad \text{VAR} = \text{EI} + \frac{P}{\text{RHO}} + 0.5 \times V \times V \\
C & \quad \text{VAR} = \text{EI} + P / \text{RHO} + 0.5 \times V \times V
\end{align*}
\]
might be supplemented with semantic declarations to become
\[
\begin{align*}
\text{C?} & \quad P &= \text{pressure\_static}, \ RHO &= \text{density\_static} \\
\text{C?} & \quad V &= \text{Speed}, \ EI &= \text{internal\_energy\_intens} \\
\text{C} & \quad \text{VAR} = EI + P / RHO + 0.5 \times V \times V \\
\end{align*}
\]
The semantic terms assigned to program variables, for example, pressure\_static or density\_static in (3.1), are distinct from tokens and come from a lexicon of semantic terms which are similar to the English technical terms. Since these semantic declarations depend on the user’s program they must be provided by the user. However, they are the sole adjustment to a user’s code. The declarations are distinguished by “C?” in the first two columns and appear to be comments to a FORTRAN compiler.
The user’s program (3.0 or 3.1) is syntactically parsed by the semantic analysis procedure into a parse tree (Figure 1) based on the syntactic grammar for a programming language. This syntactic parser could be many established programming languages including C, however, FORTRAN is used here.
\[
\begin{align*}
&= \\
&\quad \text{VAR} + \\
&\quad \text{EI} + \\
&\quad \text{\_\_} \\
&\quad \text{\_\_} \\
&\quad \text{\_\_} \\
&\quad \text{\_\_} \\
&\quad P \quad RHO \quad 0.5 \times V \times V \\
\end{align*}
\]
Figure 1 A parse tree representation of the code statement \( \text{VAR} = EI + P / RHO + 0.5 \times V \times V \).
3.1 Semantic Initialization—The Annotated Parse Tree
Each leaf and branch node of the parse tree contains a data structure with semantic information. In (3.2) two sample leaf data structures for the variables \( P \) and \( RHO \) of Figure 1 are shown. A number of specialized slots or members are included in each data structure and
these members correspond to semantic properties of the variable or node. For example, the physical quantity, stencil-wise location, and physical dimensions are some members shown in (3.2). Token values representing semantic concepts are stored in these leaf members, that is, the parse tree is annotated.
As a program's semantic declarations are syntactically parsed, the syntactic grammar rule actions transfer the semantic declarations into the corresponding structure members. For example, the declaration of the variable $P$ as $\text{pressure\_static}$ in (3.1) results in the static pressure semantic token, $\text{static\_pressure}$, being loaded into the quantity member of the leaf data structure for variable $P$. The physical dimensions of static pressure, $ML^{-1}T^{-2}$, are known from a semantic program table and are placed in the dimensions member. $RHO$ is handled similarly. Unknown or undeclared information is represented by the token, $\text{unknown}$.
3.2 Translation of Code to Semantic Statements
Just as the user’s program (3.0) may be converted to the parse tree of Figure 1, a branch of the parse tree may be converted back to the original sequence of program elements (3.0). This conversion is a depth-first traversal of the branch while reading the data structure’s string member. However, by changing which data structure member (3.2) is read and placed in the token sequence, it is possible to transform the original FORTRAN statements into semantic statements. For example, the term $P/RHO$, which is the parse tree branch beyond '/' in Figure 1 (with the member values of (3.2)), is transformed by substitution of
\begin{itemize}
\item string: $P$
\item quantity: $\text{static\_pressure}$
\item units: $\text{unknown}$
\item location: $\text{unknown}$
\item dimensions: pointer to $ML^{-1}T^{-2}$
\item string: $RHO$
\item quantity: $\text{static\_density}$
\item units: $\text{unknown}$
\item location: $\text{unknown}$
\item dimensions: pointer to $ML^{-3}$
\end{itemize}
the physical quantity member of the leaf structure into the sequence
\( \text{static\_pressure}, \, /, \, \text{static\_density}, \, \text{EOS}. \) (3.3)
The sequence is terminated with the punctuation \( \text{EOS} \). By substituting different members of the leaf structure, a variety of input sequences may be generated. For example, if the dimensions slot is read as the parse tree is traversed, then the token sequence would be
\( M^1 L^{-1} T^{-2}, \, /, \, M^1 L^{-3} T^0, \, \text{EOS}. \) (3.4)
In this way, tokens can be formed into semantic expressions which express different aspects of the code statement, including physical dimensions, grid location, and physical formulae.
3.3 Semantic Grammar Rules
Just as the original program statement (3.0) is parsed by the FORTRAN grammar rules which recognize the acceptable FORTRAN order, the transformed statements, (3.3) and (3.4), may be parsed by grammar rules which recognize semantic patterns. For example, a grammar containing rules (3.5a-f) can recognize the use of a particular formula in the statement fragment (3.3).
\[
\begin{align*}
\text{speed\_squared} & : \text{speed} \ast \text{speed} \\
\text{kinetic\_energy\_ints} & : \text{half} \ast \text{speed\_squared} \\
\text{work\_ints} & : \text{static\_pressure} / \text{static\_density} \\
\text{enthalpy\_ints} & : \text{work\_ints} + \text{internal\_energy\_ints} \\
\text{sound\_speed\_squared} & : \text{gamma} \ast \text{work\_ints} \\
\text{total\_enthalpy\_ints} & : \text{enthalpy\_ints} + \text{kinetic\_energy\_ints}
\end{align*}
\] (3.5a-f)
In particular, if the branch of the parse tree in Figure 1 rooted at /'+' were transformed to (3.3) and submitted to a parser with the grammar rules (3.5a–f), then rule (3.5c) would recognize this expression. To register this observation, the data structure at the root of the branch being tested—'+/' in Figure 1—is annotated by placing the left-hand side token, \text{work\_ints}, in the quantity member.
There is considerable flexibility about which branches can be translated, parsed, and annotated in this manner. In practice, program translations such as (3.3) and (3.4) are performed
during the syntactic parse as the parse tree is constructed. Consequently, subsets of the code statement, corresponding to branches of the parse tree, are compared to the semantic rules. For example, for the parse tree in Figure 1 one would translate and semantically parse the branches corresponding to $V^2$, $\frac{1}{2}V^2$, $\frac{E}{\rho}$, $\frac{P}{\rho}$, and $EI + \frac{E}{\rho} + \frac{1}{2}V^2$ at the corresponding points in the syntactic parse. While the syntactic parsing routine is called once for the whole program, a semantic parsing routine is called many times to parse branches involving relatively short token sequences.
3.4 Expert Grammars
Since each rule incorporated into a semantic parser (3.5a-f) will only recognize a specific formula, to increase recognition capabilities, rules must be included which represent fundamental equations, their derivations, and certain variations. The inclusion of rules is perhaps the biggest challenge of developing this analysis procedure.
It is impractical to incorporate the necessary mathematical and physical formulae into a single semantic parsing routine. For simplicity of organization and maintenance, each semantic parsing routine is restricted to the semantic grammar rules for a particular area of expertise, for example, gasdynamics. This set of semantic rules is called a semantic grammar or expert grammar, and YACC automatically converts it into a subroutine for an expert parser or expert. Further, any number of areas of expertise can be simultaneously represented with their own expert parsers. Since the semantic grammar rules for an area of expertise can be implemented with some generality, an expert parser can be written once and used by all users.
Annotation of the parse tree with an expert’s conclusions stores, organizes, and communicates the semantic information produced by these expert parsers. Each expert parser can study a branch before the branch is enlarged, and any annotation may be used by another expert to recognize a larger portion of an expression. Further, the application of rules to the conclusions of other rules allows a hierarchy of semantic concepts to be constructed which naturally connects details with substantial semantic issues. For example, in the discrete derivative code (3.6) experts would first recognize the differences in $U$ and $X$, and then the ratio of these differences.
$$DUDX(I) = \frac{(U(I+1) - U(I))}{(X(I+1) - X(I))}$$
(3.6)
Further experts could recognize the use of this discrete derivative in many different equations. Due to its specialization, an expert grammar must parse unfamiliar tokens from outside its area of expertise. Further, there may be undeclared semantic quantities in the parse tree. The token sequence sent to an expert parsing routine is filtered so that unfamiliar or undeclared tokens are translated to the unknown token, unknown. Each grammar contains rules (3.7) to parse these unknown quantities.
\[
\text{notknown} : \text{unknown} \\
\text{notknown} * \text{sem_expr} \\
\text{notknown} + \text{sem_expr} \\
\text{notknown} - \text{sem_expr} \\
\text{notknown} / \text{sem_expr} \\
\text{sem_expr} * \text{notknown} \\
\text{sem_expr} + \text{notknown} \\
\text{sem_expr} - \text{notknown} \\
\text{sem_expr} / \text{notknown} \\
( \text{notknown} )
\] (3.7)
3.5 Development of Expert Parsers
In the following subsections, three expert parsers are described for analyzing different semantic aspects of physical formulae. Aspects are distinctly different semantic properties of code which must be satisfied. The first expert analyzes the physical dimensions aspect of program statements. Although this test is relatively simple, it provides a very useful test of correctness. The second aspect is recognition of physical formulae, and it is demonstrated with a gasdynamics expert using rules similar to (3.5a-f). Third, geometrical location is determined for array variables defined on a structured grid.
3.5.1 Dimensional Analysis Expert Parser
Physical dimensional analysis provides a necessary semantic test for the correct use of all physical formulae. The code (3.8)
\[
\begin{align*}
\text{C} \\
\text{C?} \quad \text{CC} &= \text{sound.speed.squared}, \ \text{GAM} &= \text{ratio.of spécifique.heats} \\
\text{C?} \quad \text{RHO} &= \text{density.static}, \ \text{PROFIL} &= \text{total.enthalpy.intens} \\
\text{C} \\
\text{C} \quad \text{H} &= \text{RHO} \times \text{PROFIL} - \text{CC} / \text{GAM}
\end{align*}
\] (3.8)
would be flagged by this expert as incorrect since the two right-hand side terms have different dimensions. The proper code should have parentheses starting before PROFIL and ending
The dimensional analysis parser's input token sequence contains operators, the token var for a known dimension and unknown for an unknown one, and this sequence is generated as explained in Section 3.2. Var's data structure includes a pointer to its physical dimensions that is available to action code in each grammar rule. The prototype dimensional analysis grammar is the combination of the rules in (3.7) and Figure 2.
```plaintext
sem_stmt : sem_expr
| notknown
| sem_stmt sem_expr
| sem_stmt notknown
sem_expr : var
| var = var
| { check dimensional equality of operands }
| notknown = var
| { assign right-hand side dimensions to notknown }
| sem_expr EOS
var : var
| var * var
| { calculate dimensions of product }
| var / var
| { calculate dimensions of quotient }
| var + var
| { check dimensional equality of operands }
| var - var
| { check dimensional equality of operands }
| var ** var
| { check exponent dimensionless;
| calculate dimensions of result }
```
Figure 2 Grammar rules for the dimensional analysis expert parser. The rules (3.7) also appear in this expert parser.
In this grammar, action code calculates the dimensions of products and quotients and verifies the equality of operand dimensions on addition, subtraction, and assignment. Unit checking is a potential extension of dimensional analysis.
3.5.2 Formula Recognition Expert Parsers
The formula expert parsers are designed to recognize the use of physical formula in different areas of expertise. In the code
if it has been specified or deduced elsewhere that RHO is static density, E is total energy (intensive), U and V are x- and y-velocity, and GAM is the ratio of specific heats, then this code is dimensionally correct. However, (3.9) is not the proper formula for static pressure in two dimensions. If P is declared to be static pressure the expert parser would note an error, and if P is undeclared the code would be noted as misunderstood.
The expert's input token sequence is generated by reading the quantity member during depth-first traversal of a parse tree branch. Each expert grammar has a filter which translates unfamiliar or undeclared tokens to unknown. One grammar corresponding to the gasdynamics formulae (3.5a–f) includes the rules in (3.7) and Figure 3. The prototype expert grammar which recognizes gasdynamics equations contains many more rules; however, its structure remains the same. Although Figure 3 excludes the action code, each formula rule has an annotation action which is to annotate the parse tree with the left hand side token.
3.5.3 Location Analysis Expert Parser
The location analysis expert parser recognizes and analyzes the discrete geometrical location of variables and expressions on a structured grid. This information is necessary for recognition and checking of spatial formulae such as spatial derivatives and integrals and the analysis of their accuracy. The expert parser recognizes a subscript notation used by many numerical methods to represent both the physical formulae and, with the subscript, the discrete geometry. For a discrete second difference of a variable, \( \phi \), the notation would be
\[
\phi_{i+1} - 2\phi_i + \phi_{i-1}
\]
(3.10a)
where \( i \) indexes both a discrete coordinate line of points on a structured grid and an array containing a structured grid.
Figure 3 A subset of grammar rules for the gasdynamics expert parser. The rules (3.7) also appear in this expert parser.
The code (3.10) contains an indexing error,
\[ FS(I,J,N) = DW(I+2,J,N) + DW(I-1,J,N) - 2.0*DW(I,J,N) \]
(3.10b)
and it would not be recognized as a discrete second difference by this expert parser. Depending on the declaration of FS, an error would be declared, or the code would be declared not understood.
Semantic declaration of an array is different than for a scalar variable since the array may have multiple semantic definitions depending on an array index value. The LIST construct is used to create a list or vector of semantic definitions for the index of an array. In (3.11) the LIST construct attaches to the indices of arrays P and X semantic variables representing lines of centroid and vertex coordinates in a structured grid.
\[
\begin{align*}
C & : I.C.INDEX == \text{LIST} \{ \text{centroid.line.i} \} \\
C & : J.C.INDEX == \text{LIST} \{ \text{centroid.line.j} \} \\
C & : P[I.C.INDEX, J.C.INDEX] \\
C & : I.V.INDEX == \text{LIST} \{ \text{vertex.line.i} \} \\
C & : J.V.INDEX == \text{LIST} \{ \text{vertex.line.j} \} \\
C & : X[I.V.INDEX, J.V.INDEX] \\
\end{align*}
\] (3.11)
A separate grammar must interpret this semantic declaration for each array reference in a program and determine a stencil-wise location, for example, East_centroid or North_West_vertex. The parse tree is annotated with this result, and the location analysis grammar (Figure 4) uses the value in its input token sequence. In particular, for (3.10b) the indices and expression would be translated to \text{East\_East\_centroid} + \text{West\_centroid} - \text{two} \times \text{Center\_centroid}, and this expression cannot be simplified to the intended result, \text{Center\_centroid}.
The grammar shown in Figure 4 is a subset of the prototype location analysis grammar; however, it shows the essence of the location analysis rules. An annotation action is associated with each rule of Figure 4.
3.6 Prototype Semantic Analysis Procedure
A prototype semantic analysis procedure has been constructed by integrating the methods explained in Section 3. In particular, this software uses a syntactic parser to build the parse tree for a user's code. Further, it uses the semantic declarations as initial annotations of this parse tree, and generates semantic statements from these annotations. Extensions of the expert parsers described in Section 3.5 examine the semantic statements and further annotate the parse tree with their conclusions. These elements are accessed and controlled by a graphical user interface (GUI).
Figure 4 A subset of the grammar rules for the location analysis expert parser. The rules (3.7) also appear in this expert parser.
In practise, users submit their code and its semantic declarations through the GUI. The result of the analysis is an annotated parse tree, that is, the parse tree with the node data structures (3.2) completed with declared and deduced information. The GUI allows the user to display this information which includes the physical quantity represented by a variable or expression, as well as its physical dimensions, location, and the formula it was recognized.
from. A dictionary provides definitions for the semantic tokens. Of course, the available information is limited by the extent of semantic declarations and expert grammar rules as will be explained in Section 4.
This semantic analysis software not only detects some semantic errors but also documents some semantic aspects of the code. The code lines (3.12)
\[
C \quad \begin{align*}
PY &= (PX \cdot GXY + QXY) \cdot SX(J) \\
P(IWOUT,J) &= \text{DIM}(P(IWALIN,J),PY)
\end{align*}
\]
are obscure since they involve derived quantities, and it is not clear which formulae are used. However, the GUI allows the user to display what has been defined and deduced about a variable or expression.
4. Theory
In this section theoretical analyses are used to move beyond specific application and implementation details and understand more general properties of this semantic analysis procedure. Several of the experts have a very simple theoretical analysis. The physical dimensions expert (Figure 2) parses token sequences composed of only seven tokens where five are operators, and it requires no more than a few rules. However, geometrical location analysis (Figure 4) is more complex due to the larger number of potential locations in a stencil and the ways they may be combined. Formula analysis (Figure 3) is the most complex due to the number of physical quantities involved, the algebraic rules satisfied and the equations which can be derived. The following analysis is specialized to formula analysis. In particular, this section demonstrates that the transformations permitted by an LALR(1) grammar are a subset of the fundamental transformations for algebraic equations. The limited capabilities of these grammar rules has implications for what equations must be included in an expert parser, error detection, and computational complexity.
4.1 Rewrite and Reduction Substitution Rules
A grammar rule which specifies the transformation of a sequence of tokens satisfying one pattern into a sequence of tokens satisfying another pattern is a rewrite rule—the token sequence is rewritten. LALR(1) grammar rules are a specialized type of rewrite rules, referred
to here as reduction substitution rules since they rewrite and reduce one or more input tokens to a single token, never increasing the number of tokens in the token sequence as it is recognized and simplified with token replacement. The rule (4.1a) is a reduction substitution rule; however, rules (4.1b,c) are not, and could not be implemented in an LALR(1) parser.
\[
speed \text{ squared} : speed \times speed \quad (4.1a)
\]
\[
speed \times speed : speed \text{ squared} \quad (4.1b)
\]
\[
enthalpy + \text{ kinetic energy} : \text{ kinetic energy} + enthalpy \quad (4.1c)
\]
Rules (4.1a–c) can be implemented with an expert system.
4.2 Transformation of Equations
The equations represented by LALR(1) grammar rules in expert parsers are generally neither reduction substitution rules nor order dependent. The expressions comprising the left- and right-hand sides of equations have the algebraic properties (4.2) [10].
\[
\begin{align*}
a + b &= b + a & \text{Commutative Law of } + (x) \\
(a + b) + c &= a + (b + c) & \text{Associative Law of } + (x) \\
a \times (b + c) &= a \times b + a \times c & \text{Distributive Law}
\end{align*}
\]
Further, equations satisfy the reflexive, symmetric, and transitive properties as well as (4.3a–e) [10],
\[
\begin{align*}
\text{If } E_1 = E'_1, E_2 = E'_2 \text{ then } E_1 &= E_2 \text{ and } E'_1 = E'_2 \quad (4.3a) \\
\text{If } E_1 = E_2, \exists E_3 \text{ then } E_1 + E_3 &= E_2 + E_3 \quad (4.3b) \\
\text{If } E_1 = E_2, \exists E_3 \text{ then } E_1 - E_3 &= E_2 - E_3 \quad (4.3c) \\
\text{If } E_1 = E_2, \exists E_3 \text{ then } E_1 \times E_3 &= E_2 \times E_3 \quad (4.3d) \\
\text{If } E_1 = E_2, \exists E_3 \neq 0 \text{ then } E_1/E_3 &= E_2/E_3 \quad (4.3e)
\end{align*}
\]
where \( E_1, E_2, E_3, E'_1 \) and \( E'_2 \) are expressions with identical domains of definition. These properties are fundamental to the manual derivation of expressions and equations. Further, the capabilities of a semantic recognition procedure depend on both the fundamental equations and these transformations.
4.2 Commutative and Distributive Laws
Since the pattern of each grammar rule is order dependent, the pattern matching of formulae must allow for the commutative and distributive laws (4.2). For example, for the code
fragment $P \cdot GAMMA/RHO$ the branch representation may be the left-hand side of Figure 5, but the corresponding token sequence, static_pressure * gamma / static_density, cannot be parsed by the rules (3.5a–f) due to token order. One commutative transformation of the branch is the right-hand side of Figure 5,

Figure 5 Commutative transformations of the parse tree representation of the code fragment $P \cdot GAMMA/RHO$
and the resulting token sequence, gamma * static_pressure / static_density, can be parsed by (3.5a–f).
A multiplicative or additive expression involving $n$ tokens can be rearranged by the commutative law in up to $n!$ ways. To include all permutations of a formula as grammar rules is impractical for formulae involving a large number of terms. In this paper, an expression's tree representation is transformed into each of the possible permutations, and formula recognition is attempted by each expert. It may be possible to define a normal form [9] for each grammar rule, where a function, $O(token)$, provides an ordering of tokens which determines the recognizable permutation. However, the token ordering, $O(token)$, depends on all the grammar rules and their combinations.
The distributive law (4.2) is accounted for by transforming an expression's tree representation into each possible alternate form, and formula recognition is attempted by each expert. For example, for the code $2p_1 - 2p_2$, the binary tree representation may be the LHS of Figure 6, and the distributive transformation would be the right-hand side for which formula recognition is possible.
4.3 Equation Equivalence Transformations
The equation properties (4.3) are identical to the substitution and solve equation manipulations (4.6a,b)
\[
\begin{align*}
\text{If } E_1 &= E_2, \exists F + E_1 \quad &\text{then } F + E_1 &= F + E_2 & \text{Substitution (4.6a)} \\
\text{If } E_1 &= E_2 + E_3, \exists E_2 \text{ inverse} \quad &\text{then } E_3 &= E_1 - E_2 & \text{Solve (4.6b)}
\end{align*}
\]
where \( E_1, F \) are expressions containing one or more terms. These rules apply similarly for subtraction, multiplication and division. A special case of the substitution manipulation is the reduction substitution
\[
\text{If } T = E, \exists F + E \quad \text{then } F + E = F + T & \quad \text{Reduction Substitution (4.6c)}
\]
where \( T \) is a single term, and the rule is also valid for subtraction, multiplication and division.
The transformations (4.2) and (4.6a,b) allow general algebraic derivations. For example, the code (4.7)
\[
\begin{align*}
C? & \quad \text{G} == \text{ratio_of_specific_heats}, \text{M1} == \text{mach} \\
C & \quad \text{G} = 1.4 \\
& \quad \text{GAM1} = 0.5 * ( \text{G} - 1. ) \\
C & \quad \text{ZED} = \text{SQRT( 1. - 2.*(G + 1.) * ( M1**2 * (1. + GAM1 * M1 * M1) / ( 1. + G * M1 * M1 )**2))} \\
C & \quad \text{M2} = \text{SQRT( (1. - ZED) / ( 1 + G * ZED ) )}
\end{align*}
\]
represents the equation
\[
\begin{align*}
z &= \left( 1 - 2(\gamma + 1) \frac{M_f^2(1 + \frac{x-1}{2}M_f^2)}{1 + \gamma M_f^2} \right)^{\frac{1}{2}} \quad \text{(4.8)}
\end{align*}
\]
\[ M_2 = \left( \frac{1 + z}{1 + \gamma z} \right)^{\frac{1}{2}} \]
which is derived from basic aerodynamics and fluid mechanics formulae [7] with the algebraic transformations (4.2) and (4.6a,b).
4.4 Consequences of Using the Reduction Substitution
Choosing to recognize semantic expressions with a LALR(1) parser has a number of consequences for designing rules for expert parsers, error detection, computational complexity, and finite termination of the expert parsers.
The basic physical formulae for the derivation of (4.8) are contained in the prototype expert parser of Section 3.5.2. However, an LALR(1) grammar allows only the reduction substitution (4.6c), and the derivation of (4.8) requires all the transformations (4.6a–c). Consequently, (4.7) cannot be recognized from basic physical formulae by the expert parsers, and the equation (4.8) must be included in the expert parser for recognition to occur. Further, without the theoretical ability to recognize all conceivable derivable physical formulae, it is not guaranteed that the expert parsers can distinguish between an incorrect expression and an unrecognizable yet correct expression. For example, without (4.8) included in an expert parser, the code (4.7) could not be recognized. Consequently, the equations included in an expert parser must be carefully written and more extensive than the fundamental physical equations of a field.
Manual derivation of (4.8) from fundamental aerodynamic and fluid flow equations is a non-trivial search even with the guidance of a derivation. Several substitutions must be manually attempted for each step of the derivation. Consequently, including all the transformations (4.6a–c) and allowing general derivations could lead to expensive searches. Currently, it is preferable to include equations, for example (4.8), in an expert parser once and avoid expensive searches each time the formula is encountered.
Precluding expensive derivations by using only reduction substitutions is not sufficient to yield a linear computational performance. Although the execution time of the expert parsing routines generated by YACC is linear in the number of input tokens, because of the commutative and distributive properties (4.2), the expert parsers may need to see transformations of an expression before recognizing it. Since there could be \( n! \) distinct commutative permuta-
tions of \( n \) terms in an additive or multiplicative expression, the computational complexity of a semantic analysis can increase beyond linear performance. The worst case performance occurs for expressions which are not recognized, since all possible commutative and distributive transformations of the expression will be considered.
A further consequence of using the reduction substitution is the finite termination of the expert parser. Assuming the reduction substitution rules of the expert parser do not rewrite one token as another single token, then each application of a reduction substitution rule will reduce the number of tokens until termination. At termination either all the tokens have been completely parsed and a single token remains, or some token sequence remains where no patterns are recognized. For rule systems involving general rewrite rules (4.1a–c), it is not as obvious that a sequence will be reduced or that the application of rewrite rules will terminate after a finite number of steps. Considerable theoretical analysis has been applied to this problem [5] for computer algebra systems.
5. Results
In this section the procedure for semantic checking is demonstrated with three test problems. The first problem (Figure 7) demonstrates the gasdynamics expert’s ability to recognize gasdynamics equations. The second problem (Figure 8) involves code for the calculation of the discrete, integral convective terms of the Euler equations in a computational fluid dynamics code. The expert for determining geometrical location within a structured grid stencil works with the expert for recognizing integral quantities and the terms of Euler’s equations. The third case (Figure 9) is a set of discrete, one-dimensional differential equations taken from fluid dynamics and applied mathematics. Each of these test cases run on engineering workstations in less than a second of CPU time.
The result of each analysis is an annotated parse tree which cannot be completely displayed in a figure. Instead, the right most column of each figure displays the physical quantity deduced for each code line. More detailed information is contained in the annotated parse tree, including the analysis of variables and sub-expressions. The suffixes pure, put, and nd represent per-unit-mass, per-unit-time, and non-dimensional respectively.
C? P == pressure_static, RHO == density_static
C? GAM == ratio_of_specific_heats
C? U == speed
C? M == mach
C? C == sound_speed
C? T == temperature_static
C? R == gas_constant
C? VOL == volume
C? CP == specific_heat_cp
C? CV == specific_heat_cv
C? A == area
C? E == energy_internal_pum
\[
\begin{align*}
\text{vara} &= (GAM / (GAM - 1.)) \\
\text{varb} &= M*U \\
\text{varc} &= RHO*U*U + P \\
\text{vard} &= (GAM / (GAM - 1.))* P / RHO + 0.5 * U*U \\
\text{vare} &= 1. + 0.5*(gam-1.)*M*M \\
\text{varf} &= 1. + gam*M*M \\
\text{varg} &= 1. + M*gam*M \\
\text{varh} &= RHO * U * A \\
\text{vari} &= GAM * P / RHO \\
\text{varj} &= P / RHO \\
\text{vark} &= P / RHO + P / (RHO * (GAM-1.)) \\
\text{varl} &= P / RHO + (1. /((GAM-1.)) * P / RHO \\
\text{varm} &= E + 0.5 * U*U \\
\text{varo} &= RHO * R * T \\
\text{varp} &= R * T / VOL \\
\text{varq} &= CP - CV \\
\text{varr} &= CP / CV \\
\text{vars} &= c - 0.5 * u*( gam - 1. ) \\
\text{vart} &= c + 0.5 * u*( gam - 1. ) \\
\text{varu} &= P / (RHO**GAM)
\end{align*}
\]
Figure 7 The first semantic analysis test case contains gasdynamics equations. The right column displays the physical quantity deduced for the expression.
The first problem (Figure 7) demonstrates one expert's ability to recognize gasdynamics equations. The semantic declarations precede the code, and the equations involve scalar variables without specified locations. Commutative variations of several gasdynamics formulae are included to demonstrate the role of the commutative law in formula recognition. As a result of the analysis, each code expression is recognized by the gasdynamics expert as an instance of a particular gasdynamics formula. Further, a dimensional analysis is per-
formed. These conclusions are stored as annotations of the parse tree. In a Graphical User Interface (GUI) associated with this semantic analysis, these semantic conclusions may be examined.
```
C? I.C_INDEX == LIST { centroid_line_i }
C? J.C_INDEX == LIST { centroid_line_j }
C? I.V_INDEX == LIST { vertex_line_i }
C? J.V_INDEX == LIST { vertex_line_j }
C
C? COORDS == LIST { x.coord, y.coord }
C? VECTOR == LIST { density_static, x.momentum_puv,
y.momentum_puv, energy.total_puv }
C
C? W[I.C_INDEX,J.C_INDEX,VECTOR]
C? P[I.C_INDEX,J.C_INDEX]
C? X[I.V_INDEX,J.V_INDEX,COORDS]
C? P == pressure
C
C? I == counter, J == counter
C
DIMENSION W(20,20,4), P(20,20), X(20,20,2)
C
ZZ = X(I,J,2) - X(I,J-1,2) + P(I,J)
XY = X(I,J,1) - X(I,J-1,1)
YY = X(I,J,2) - X(I,J-1,2)
PA = 0.5 * ( P(I+1,J) + P(I,J) )
QSP = (YY*W(I+1,J,2) - XY*W(I+1,J,3))/W(I+1,J,1)
QSM = (YY*W(I,J,2) - XY*W(I,J,3))/W(I,J,1)
FS1 = 0.5*( QSP*W(I+1,J,1) +QSM*W(I,J,1) )
FS2 = 0.5*( QSP*W(I+1,J,2) +QSM*W(I,J,2) ) + YY*PA
FS3 = 0.5*( QSP*W(I+1,J,3) +QSM*W(I,J,3) ) - XY*PA
FS4 = 0.5*( QSP*(W(I+1,J,4)+P(I+1,J)) +
QSM*(W(I,J,4)+P(I,J)))
C
```
Figure 8 The second semantic analysis test case represents finite volume calculations for the Euler equations. The right column displays the physical quantity deduced for the expression.
The second problem (Figure 8) demonstrates the analysis of discrete integral equations and associated grid locations. It includes an error in the first code line, and demonstrates the use of array notation. In particular, the LIST construct introduced in Section 3.5.3 is used to define a semantic variable, COORDS, as the vector (x-coordinate, y-coordinate). When COORDS is associated with an array index as in X[I_INDEX,J_INDEX,COORDS], the third array index of X is defined to have two values: x- and y-coordinate. The semantic variable VECTOR is similar and is defined to represent the vector of dependent variables of fluid dynamics equations, \( (\rho, p_u, p_v, \rho E) \). The semantic variables I.V_INDEX et al. are
defined as in Section 3.5.3 to represent coordinate lines in a general structured grid. These semantic variables are used to define the indices of arrays W, P, and X, and associate semantic definitions with each index value.
With these array definitions, the semantic analysis process is able to recognize the variables and the use of physical formulae, in particular that XY and YY are differences in x- and y-coordinates, QSP and QSM are the fluid volumes flowing through the face per unit time, and FS1–4 are the components of a discrete approximation to the integral \( \int F \cdot nds \) where \( F = (f, g) \), \( f = (\rho u, \rho u^2 + p, \rho uv, \rho uH) \), and \( g = (\rho v, \rho uv, \rho v^2 + p, \rho vH) \). A dimensional analysis is also performed. All of these conclusions are stored as annotations of the parse tree and are available for examination in the GUI. The analysis also notes that the line involving the variable ZZ is neither dimensionally correct nor a known formula.
The third problem (Figure 9) demonstrates the recognition of several discrete, one-dimensional differential equations from fluid dynamics. Again, array variables are involved and provide stencil locations for use in the analysis, particularly in the recognition of differences and first and second derivatives. In each case the expert recognizes the mathematical formula. As always, a dimensional analysis is performed simultaneously.
6. Conclusions
This paper is motivated by a need for improved tools for verification and documentation of scientific and engineering codes, and it investigates methods for automatically recognizing, checking, and documenting semantic concepts used in these codes. In particular, a scheme and prototype code are presented that recognize and check some mathematical, physical and geometrical formulae. A theoretical analysis of this approach is also presented, and the method is demonstrated with three test cases.
The prototype semantic analysis procedure proves the basic principles of this semantic analysis technique, however additional work is required and a number of issues remain unexplored. First, additional semantic knowledge must be incorporated into the expert parsers to expand recognition capabilities. This semantic knowledge is equations and formulae from additional scientific and engineering fields. Second, there are several semantic aspects which have not
Figure 9 The third semantic analysis test case includes one-dimensional finite difference approximations for several fluid dynamics equations. The right column displays the physical quantity deduced for the expression.
been explored, including the accuracy of discrete approximations, the consistency of physical assumptions, more complex geometrical concepts, the counting arguments of program loops, conditional statements, and branching. Further work is necessary to bring this technique to users with sufficient utility and convenience.
8. Acknowledgements
This work supported by the Propulsion Systems Base Program at NASA Lewis Research Center through the Computing and Interdisciplinary Systems Office (contract NAS3-27816). Greg Follen and Austin Evans were the monitors. The lexical analysis and FORTRAN syntactic analysis routines are taken from Ftnchek [18]. Wilma Graham has patiently proofread this manuscript. The author thanks Edmane Envia, Rodrick Chima, Jay Horowitz, and Jack Wilson for fruitful discussions. Ambady Suresh, Kevin Lamb and Scott Townsend are due many thanks for considerable direction, advice, and constructive criticism.
9. Bibliography
**Title and Subtitle**
A Semantic Analysis Method for Scientific and Engineering Code
**Authors**
Mark E.M. Stewart
**Performing Organization**
NYMA, Inc.
2001 Aerospace Parkway
Brook Park, Ohio 44142
**Sponsoring Agency**
National Aeronautics and Space Administration
Lewis Research Center
Cleveland, Ohio 44135-3191
**Abstract**
This paper develops a procedure to statically analyze aspects of the meaning or semantics of scientific and engineering code. The analysis involves adding semantic declarations to a user's code and parsing this semantic knowledge with the original code using multiple expert parsers. These semantic parsers are designed to recognize formulae in different disciplines including physical and mathematical formulae and geometrical position in a numerical scheme. In practice, a user would submit code with semantic declarations of primitive variables to the analysis procedure, and its semantic parsers would automatically recognize and document some static, semantic concepts and locate some program semantic errors. A prototype implementation of this analysis procedure is demonstrated. Further, the relationship between the fundamental algebraic manipulations of equations and the parsing of expressions is explained. This ability to locate some semantic errors and document semantic concepts in scientific and engineering code should reduce the time, risk, and effort of developing and using these codes.
**Subject Terms**
Software engineering; Computational fluid mechanics
<table>
<thead>
<tr>
<th>Number of Pages</th>
<th>35</th>
</tr>
</thead>
<tbody>
<tr>
<td>Price Code</td>
<td>A03</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19980185793.pdf", "len_cl100k_base": 12266, "olmocr-version": "0.1.49", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 75286, "total-output-tokens": 14901, "length": "2e13", "weborganizer": {"__label__adult": 0.0003659725189208984, "__label__art_design": 0.0003833770751953125, "__label__crime_law": 0.0004475116729736328, "__label__education_jobs": 0.00115203857421875, "__label__entertainment": 8.547306060791016e-05, "__label__fashion_beauty": 0.0001996755599975586, "__label__finance_business": 0.00035190582275390625, "__label__food_dining": 0.0004248619079589844, "__label__games": 0.0006251335144042969, "__label__hardware": 0.0015382766723632812, "__label__health": 0.000598907470703125, "__label__history": 0.0003371238708496094, "__label__home_hobbies": 0.0001704692840576172, "__label__industrial": 0.000919342041015625, "__label__literature": 0.0003879070281982422, "__label__politics": 0.0003151893615722656, "__label__religion": 0.00057220458984375, "__label__science_tech": 0.1463623046875, "__label__social_life": 0.00011754035949707033, "__label__software": 0.01097869873046875, "__label__software_dev": 0.83203125, "__label__sports_fitness": 0.00038313865661621094, "__label__transportation": 0.0009717941284179688, "__label__travel": 0.00021696090698242188}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55160, 0.02961]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55160, 0.79402]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55160, 0.86296]], "google_gemma-3-12b-it_contains_pii": [[0, 229, false], [229, 229, null], [229, 1908, null], [1908, 4080, null], [4080, 6568, null], [6568, 8922, null], [8922, 11087, null], [11087, 13516, null], [13516, 15313, null], [15313, 17346, null], [17346, 19519, null], [19519, 21985, null], [21985, 24210, null], [24210, 25882, null], [25882, 27714, null], [27714, 27952, null], [27952, 30363, null], [30363, 30954, null], [30954, 33120, null], [33120, 35441, null], [35441, 37062, null], [37062, 38581, null], [38581, 40971, null], [40971, 43329, null], [43329, 45062, null], [45062, 47095, null], [47095, 49511, null], [49511, 50053, null], [50053, 50669, null], [50669, 53365, null], [53365, 53572, null], [53572, 55160, null]], "google_gemma-3-12b-it_is_public_document": [[0, 229, true], [229, 229, null], [229, 1908, null], [1908, 4080, null], [4080, 6568, null], [6568, 8922, null], [8922, 11087, null], [11087, 13516, null], [13516, 15313, null], [15313, 17346, null], [17346, 19519, null], [19519, 21985, null], [21985, 24210, null], [24210, 25882, null], [25882, 27714, null], [27714, 27952, null], [27952, 30363, null], [30363, 30954, null], [30954, 33120, null], [33120, 35441, null], [35441, 37062, null], [37062, 38581, null], [38581, 40971, null], [40971, 43329, null], [43329, 45062, null], [45062, 47095, null], [47095, 49511, null], [49511, 50053, null], [50053, 50669, null], [50669, 53365, null], [53365, 53572, null], [53572, 55160, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55160, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55160, null]], "pdf_page_numbers": [[0, 229, 1], [229, 229, 2], [229, 1908, 3], [1908, 4080, 4], [4080, 6568, 5], [6568, 8922, 6], [8922, 11087, 7], [11087, 13516, 8], [13516, 15313, 9], [15313, 17346, 10], [17346, 19519, 11], [19519, 21985, 12], [21985, 24210, 13], [24210, 25882, 14], [25882, 27714, 15], [27714, 27952, 16], [27952, 30363, 17], [30363, 30954, 18], [30954, 33120, 19], [33120, 35441, 20], [35441, 37062, 21], [37062, 38581, 22], [38581, 40971, 23], [40971, 43329, 24], [43329, 45062, 25], [45062, 47095, 26], [47095, 49511, 27], [49511, 50053, 28], [50053, 50669, 29], [50669, 53365, 30], [53365, 53572, 31], [53572, 55160, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55160, 0.00698]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
4f8bd57ba629c350fc0b9c5b44f35d3ff83fc800
|
[REMOVED]
|
{"len_cl100k_base": 11386, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 39941, "total-output-tokens": 14435, "length": "2e13", "weborganizer": {"__label__adult": 0.00039005279541015625, "__label__art_design": 0.0006127357482910156, "__label__crime_law": 0.0004646778106689453, "__label__education_jobs": 0.0013322830200195312, "__label__entertainment": 0.00020039081573486328, "__label__fashion_beauty": 0.0002651214599609375, "__label__finance_business": 0.0005168914794921875, "__label__food_dining": 0.0004355907440185547, "__label__games": 0.0009584426879882812, "__label__hardware": 0.0019931793212890625, "__label__health": 0.000935077667236328, "__label__history": 0.0005359649658203125, "__label__home_hobbies": 0.0001838207244873047, "__label__industrial": 0.0007185935974121094, "__label__literature": 0.00047397613525390625, "__label__politics": 0.0004200935363769531, "__label__religion": 0.0006251335144042969, "__label__science_tech": 0.48291015625, "__label__social_life": 0.0001900196075439453, "__label__software": 0.017974853515625, "__label__software_dev": 0.48681640625, "__label__sports_fitness": 0.0002963542938232422, "__label__transportation": 0.0005550384521484375, "__label__travel": 0.000232696533203125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55250, 0.03308]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55250, 0.34139]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55250, 0.89492]], "google_gemma-3-12b-it_contains_pii": [[0, 5778, false], [5778, 10730, null], [10730, 15872, null], [15872, 21967, null], [21967, 25851, null], [25851, 31480, null], [31480, 37788, null], [37788, 41331, null], [41331, 47028, null], [47028, 55250, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5778, true], [5778, 10730, null], [10730, 15872, null], [15872, 21967, null], [21967, 25851, null], [25851, 31480, null], [31480, 37788, null], [37788, 41331, null], [41331, 47028, null], [47028, 55250, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55250, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55250, null]], "pdf_page_numbers": [[0, 5778, 1], [5778, 10730, 2], [10730, 15872, 3], [15872, 21967, 4], [21967, 25851, 5], [25851, 31480, 6], [31480, 37788, 7], [37788, 41331, 8], [41331, 47028, 9], [47028, 55250, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55250, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
b104cd611433f56e14e06d2d96d90761fff548df
|
[REMOVED]
|
{"Source-Url": "https://www.research.ed.ac.uk/portal/files/439946/The_Synthesis_of_Logic_Programs_from_Inductive_Proofs.pdf", "len_cl100k_base": 11201, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 56073, "total-output-tokens": 12973, "length": "2e13", "weborganizer": {"__label__adult": 0.00038909912109375, "__label__art_design": 0.00048470497131347656, "__label__crime_law": 0.0005826950073242188, "__label__education_jobs": 0.001870155334472656, "__label__entertainment": 0.00012576580047607422, "__label__fashion_beauty": 0.0002033710479736328, "__label__finance_business": 0.0003485679626464844, "__label__food_dining": 0.0005774497985839844, "__label__games": 0.000965118408203125, "__label__hardware": 0.0010766983032226562, "__label__health": 0.0008172988891601562, "__label__history": 0.0003342628479003906, "__label__home_hobbies": 0.0001825094223022461, "__label__industrial": 0.0008440017700195312, "__label__literature": 0.0007429122924804688, "__label__politics": 0.00044608116149902344, "__label__religion": 0.0007700920104980469, "__label__science_tech": 0.1351318359375, "__label__social_life": 0.00013387203216552734, "__label__software": 0.00835418701171875, "__label__software_dev": 0.84423828125, "__label__sports_fitness": 0.00037217140197753906, "__label__transportation": 0.0008244514465332031, "__label__travel": 0.0001959800720214844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 43268, 0.0157]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 43268, 0.60726]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 43268, 0.85302]], "google_gemma-3-12b-it_contains_pii": [[0, 1246, false], [1246, 3701, null], [3701, 7014, null], [7014, 10097, null], [10097, 12748, null], [12748, 15354, null], [15354, 19188, null], [19188, 22938, null], [22938, 25773, null], [25773, 28642, null], [28642, 31195, null], [31195, 34498, null], [34498, 37039, null], [37039, 39356, null], [39356, 42305, null], [42305, 43268, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1246, true], [1246, 3701, null], [3701, 7014, null], [7014, 10097, null], [10097, 12748, null], [12748, 15354, null], [15354, 19188, null], [19188, 22938, null], [22938, 25773, null], [25773, 28642, null], [28642, 31195, null], [31195, 34498, null], [34498, 37039, null], [37039, 39356, null], [39356, 42305, null], [42305, 43268, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 43268, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 43268, null]], "pdf_page_numbers": [[0, 1246, 1], [1246, 3701, 2], [3701, 7014, 3], [7014, 10097, 4], [10097, 12748, 5], [12748, 15354, 6], [15354, 19188, 7], [19188, 22938, 8], [22938, 25773, 9], [25773, 28642, 10], [28642, 31195, 11], [31195, 34498, 12], [34498, 37039, 13], [37039, 39356, 14], [39356, 42305, 15], [42305, 43268, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 43268, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
1d6a6a78ef616665279aff4b0ba6084ced3e17ad
|
Leslie Lamport's logical clocks : a tutorial
Citation for published version (APA):
Document status and date:
Published: 01/01/2002
Document Version:
Publisher’s PDF, also known as Version of Record (includes final page, issue and volume numbers)
Please check the document version of this publication:
• A submitted manuscript is the version of the article upon submission and before peer-review. There can be important differences between the submitted version and the official published version of record. People interested in the research are advised to contact the author for the final version of the publication, or visit the DOI to the publisher’s website.
• The final author version and the galley proof are versions of the publication after peer review.
• The final published version features the final layout of the paper including the volume, issue and page numbers.
Link to publication
General rights
Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights.
• Users may download and print one copy of any publication from the public portal for the purpose of private study or research.
• You may not further distribute the material or use it for any profit-making activity or commercial gain
• You may freely distribute the URL identifying the publication in the public portal.
If the publication is distributed under the terms of Article 25fa of the Dutch Copyright Act, indicated by the “Taverne” license above, please follow below link for the End User Agreement:
www.tue.nl/taverne
Take down policy
If you believe that this document breaches copyright please contact us at:
openaccess@tue.nl
providing details and we will investigate your claim.
Leslie Lamport’s Logical Clocks: a tutorial
Rob R. Hoogerwoord
29 january 2002
Contents
0 Introduction 1
1 Causal precedence and logical clocks 2
1.0 Processes, states, and events 2
1.1 Naming conventions, and some more 3
1.2 Sequential precedence 4
1.3 Causal precedence 5
1.4 Local and global states 8
1.5 Time stamps 10
1.6 An implementation 11
1.7 Afterthoughts 14
2 Distributed Mutual Exclusion 16
2.0 Synchronisation 16
2.1 Mutual exclusion for two processes 17
2.2 Distributed implementation 21
2.3 Many processes 22
2.4 Keeping the values different 23
2.5 Progress and fairness 23
3 Epilogue 25
Bibliography 26
Chapter 0
Introduction
In 1978 the American computing scientist Leslie Lamport published a paper [2] in which he introduced so-called logical clocks to synchronize processes in a distributed system. These logical clocks can be used to record (information about) the causal order in which events in the distributed system take place: some events always “occur before” other ones, independent of the (relative) speeds of the processes. In his paper Lamport used this in a fair algorithm for distributed mutual exclusion; here, “fair” means that the order in which requests (to obtain the exclusive right) are granted complies with the causal order of these requests.
This note is mainly written for tutorial reasons, not in the least to develop my own understanding of the subject. A minor reason is my dissatisfaction with the cumbersome notation and nomenclature in the existing presentations, not only in Lamport’s original paper but also in recent publications like one by Raynal and Singhal [3]. In addition, this is an exercise in separation of concerns.
This note consists of two parts that can be read independently, as these parts are rather self-contained. In Section 1 we introduce causal precedence and Lamport’s logical clocks to record information about causal precedence. In Section 2 we present an algorithm for distributed mutual exclusion. This is not Lamport’s algorithm: to fully understand his algorithm I decided to design it myself, but it so happened that I came up with a simpler, and somewhat more efficient, algorithm. This turned out to be the algorithm designed by Ricart and Agrawala [4].
The connection between the two stories is rather thin: some variables used in the algorithm for mutual exclusion may be viewed as logical clocks, but to understand (the correctness of) the algorithm one does not need to know this.
Chapter 1
Causal precedence and logical clocks
1.0 Processes, states, and events
An event is a change of state in a (single) process. This process can be part of a distributed collection of processes. The adjective “distributed” means that the state of the system, as a whole, is distributed over the individual processes: each process can only change its own state. Moreover, the state of the system consists exclusively of the states of its processes.
The processes communicate by exchanging messages. We assume that sending a message by one process and receiving it by another is not an invisible (atomic) action, that is, message transmission is not instantaneous; in this case all messages sent but not yet received are also part of the state of the system. Mathematically, we could model this by introducing additional processes, so-called channels, whose states would represent the messages sent but not yet received. This is, however, not necessary, because we can also, for every process proper, view the states of its outgoing channels as part of the state of that process. Phrased differently, if we equip every process with two auxiliary variables, one representing the set of messages sent by that process and one representing the set of messages received by that process, then the differences between the “sent sets” and the “received sets” represent the states of the (directed) channels connecting the processes.
In this way, the above view of the state of a distributed system is equally well applicable to systems with non-instantaneous — also called asynchronous — communication.
Because both sending a message and receiving a message affect the state
of the sending or receiving process, both sending a message and receiving a message are events, in the above meaning of the word. Notice that the representation with sent sets and received sets complies with the view that each process only changes its own state: a sending process changes its state by adding the message to its sent set, whereas a receiving process changes its state by adding the message to its received set. Hence, the channel state is distributed over sender and receiver in a way that is consistent with our view of a distributed system.
1.1 Naming conventions, and some more
To distinguish the processes we assume that they have been properly named. In this note we will use variables $p, q, r$ to range over the process names.
In the course of a process the same state transition may occur several times, but such multiple occurrences of the same state transition are considered different events. So, for example, a state transition like $x := x + 1$ may occur many times within a process but each individual occurrence of $x := x + 1$ is a separate event. To distinguish all events in the system we assume that the events have been properly named, thus making each event unique; in what follows we will use variables $e, f, g$ to denote (names of) events.
An event is a state transition in a single process, so each event uniquely identifies the process in which it occurs. This is formally rendered by means of a function $pr$, from events to processes, with the interpretation:
$$ pr \cdot e = \text{"the process in which event } e \text{ occurs"}.$$
Possible events are “sending a message” and “receiving a message”, and for our purposes these are the only events of interest. We shall ignore so-called internal events, representing purely local state changes of processes; if so desired, internal events can be treated as send events.
Every message is sent by exactly one process – its sender – and what follows is based upon the assumption that every message is also received by exactly one process – its receiver –. We only make this assumption here to keep the notation as simple as possible, but the assumption is not essential: it is perfectly admissible to have the same message being received by many (or all) processes in the system – so-called broadcast messages –.
Every send event and every receive event involves a unique message; therefore, these events can be represented by their messages: we also assume that the messages have been properly named. We will use variables $l, m, n$ to denote (names of) messages. So, every message represents two events, namely
the event of sending it and the event of receiving it. To formalize this we introduce, for every message \( m \):
\[
\begin{align*}
\text{snd}\cdot m &= \text{“the event of sending message } m\text{”} \\
\text{sdr}\cdot m &= \text{“the process that sends message } m\text{”} \\
\text{rcv}\cdot m &= \text{“the event of receiving message } m\text{”} \\
\text{rvr}\cdot m &= \text{“the process that receives message } m\text{”}
\end{align*}
\]
This nomenclature is redundant, but this is an advantage: whenever we wish to take the nature of events into account we use messages to identify events and whenever the nature of events is irrelevant we identify them by their own names. Because of this redundancy we can also formulate a few relations that reflect the above interpretations. Because we consider no other events than sending and receiving, we have, for every event \( e \):
\[
(\exists m:: e = \text{snd}\cdot m \lor e = \text{rcv}\cdot m)
\]
Furthermore, functions \( \text{sdr} \) and \( \text{rvr} \) are related to \( \text{snd} \), \( \text{rcv} \), and \( \text{pr} \) as follows – for all \( m \):
\[
\begin{align*}
\text{sdr}\cdot m &= \text{pr}\cdot (\text{snd}\cdot m) \\
\text{rvr}\cdot m &= \text{pr}\cdot (\text{rcv}\cdot m)
\end{align*}
\]
A complete formalisation also requires formulae expressing that all send events differ from all receive events and that different messages represent different events, but for the time being I feel no urge to write down these formulae.
1.2 Sequential precedence
We assume that every single process in the distributed system is sequential; a sequential process is one in which any two different events can be ordered: either the one event occurs before the other event or it occurs after it. For any two events \( e, f \) we use \( e \triangleright f \) to denote sequential precedence of \( e \) and \( f \).
\textbf{sequential precedence:} for all events \( e, f \):
\[
e \triangleright f \equiv \text{pr}\cdot e = \text{pr}\cdot f \land \text{“} e \text{ occurs before } f \text{”}
\]
We shall not further formalize the notion “occurs before”, because we do not need it; in what follows \( \triangleright \) can be considered as primitive. For every process the relation \( \triangleright \) is a total order on the events in that process:
\((\forall e, f : pr \cdot e = pr \cdot f : e = f \lor e \triangleright f \lor f \triangleright e)\).
The sequential history of event \(f\) is the set \(H_f\) of all events (sequentially) preceding \(f\), that is, for all events \(e, f\) we have:
\[ e \in H_f \iff e \triangleright f. \]
The history of an event can be viewed as (a representation of) the state of the process immediately before occurrence of that event. This enables us to formulate preconditions for events: a precondition for an event thus is a proposition about its history. Also, we can now formulate that processes, which may be infinite – non-terminating –, have, at any moment in time, been in existence for a finite amount of time only.
**postulate:** For all \(f\) set \(H_f\) is finite.
\(\Box\)
**aside:** A sequential process could also be defined as an infinite sequence \(x_i(i : 0 \leq i)\) of events, such that \(x_j\) is the event with exactly \(j\) sequentially preceding events; that is, the events would be identified here by their ordinal numbers. Then we would have, for all natural \(i, j\):
\[ x_i \triangleright x_j \iff i < j. \]
In these terms all properties attributed to \(\triangleright\) could be proved as theorems: the (representation by an) infinite sequence can be viewed as an underlying model. For example, the history of event number \(j\) then consists of all events with ordinal numbers less than \(j\), which is definitely finite.
In a system of many sequential processes events cannot so easily be numbered; we could, of course, identify every event by a pair containing the name of its process and its local ordinal number, but this is technically awkward and needlessly overspecific.
\(\Box\)
### 1.3 Causal precedence
In a concurrent computation the best we can say is that some events are causally ordered: one event causally precedes another means that, independent of the relative speeds of the processes, the one event certainly occurs before
the other. Not every pair of events can thus be ordered: causal precedence is a partial order.
In its simplest form, event \( e \) causally precedes event \( f \) either if \( e \) and \( f \) occur in the same (sequential) process and \( e \) occurs before \( f \), or if \( e \) is the sending of a message and \( f \) is that message’s reception: messages are always received after they have been sent. In addition, causal precedence is transitive: if \( e \) precedes \( f \) and \( f \) precedes \( g \) then it is reasonable to state that \( e \) precedes \( g \) as well.
Notice that the notion of time plays no role here: we are only concerned with the relative order in which events take place, not in the exact moments at which they occur. Of course, we may conclude that one event precedes the other if the one occurs at an earlier time than the other, but in this way time is introduced into the discussion in an artificial way. This observation is particularly relevant for (truly) distributed systems, where it is physically meaningless to compare times in different processes.
Causal precedence can be used to implement distributed arbitration, such as in a mutual exclusion protocol, in a fair way: we now can specify that arbitration requests are granted in an order that respects the causal order of these requests. This may, for instance, be needed to maintain the consistency of a distributed data base.
Causal precedence is the transitive closure of a basic precedence relation. Event \( e \) basically precedes event \( f \), notation \( e \prec f \), either if \( e \) sequentially precedes \( f \) or if \( e \) and \( f \) are the sending and receiving of the same message (or both).
**basic precedence:** for all events \( e, f \):
\[
\begin{align*}
e \prec f & \equiv e \triangleright f \lor (\exists m :: e = \text{snd}\cdot m \land \text{rcv}\cdot m = f) .
\end{align*}
\]
This definition can be rewritten into the following equivalent, but more manageable, form; this is the form we will be using.
**basic precedence:** \( \rightarrow \) is the strongest relation satisfying:
\[
(\forall e, f :: e \triangleright f \Rightarrow e \rightarrow f) \land (\forall m :: \text{snd}\cdot m \rightarrow \text{rcv}\cdot m) .
\]
**causal precedence:** \( \Rightarrow \) is the transitive closure of \( \rightarrow \).
It may seem somewhat overdone to introduce the basic precedence relation as a separate concept, but, as we will see, it so happens that the discussion can be carried out largely in terms of basic precedence, which is simpler. In particular, the following little lemma is relevant.
**Lemma:** For any transitive relation $R$ we have:
$$
(\forall e, f :: e \rightarrow f \Rightarrow e R f) \Rightarrow (\forall e, f :: e \rightarrow f \Rightarrow e R f).
$$
In words: to prove that causal precedence implies some transitive relation $R$, it suffices to prove that basic precedence implies $R$, and the latter is weaker.
Causal precedence is a partial order: not every two events need be related. Events that are not causally related are called concurrent, notation $e || f$.
**Concurrency:** for all events $e, f$:
$$
e || f \equiv \neg(e \rightarrow f) \land \neg(f \rightarrow e).
$$
Because causal precedence is not a total order, we do not have:
$$(\forall e, f :: e = f \lor e \rightarrow f \lor f \rightarrow e)
$$
but we do have the weaker relation:
$$(0) \quad (\forall e, f :: e || f \lor e \rightarrow f \lor f \rightarrow e).
$$
As we did with sequential precedence, we can now define the causal history of an event $f$ as the set $G_f$ of all events causally preceding it:
$$e \in G_f \equiv e \rightarrow f.$$
Just as the sequential history of an event represents the state of the process just before occurrence of the event, we can now view the causal history of an event as (the relevant part of) the state of the whole system just before occurrence of the event. From the axiom that the sequential histories of all events are finite it follows, via the above definitions, that causal histories are finite as well. Moreover, it is now possible to prove that every event $snd\cdot m$ is an element of the (causal) history of the event $rcv\cdot m$, which is a formal rendering of the property that no message is received before it has been sent. (This also explains the use of the adjective “causal”.)
property:
$$(\forall m :: \text{snd} \cdot m \in G_{\text{rev}} \cdot m)$$.
\[ \square \]
### 1.4 Local and global states
In a (partially or totally) ordered universe we call a subset *closed* if, for every element of that subset, all values smaller than that element are contained in the subset as well.
**definition:** A subset $V$ (of some universe) is *closed with respect to* relation $<$ (on that universe) means:
$$(\forall x, y :: x < y \land y \in V \Rightarrow x \in V)$$.
\[ \square \]
Closedness of sets is connected to transitivity of the relation $<$, in the following way. For every $y$ we can define a set $V_y$ by:
$$x \in V_y \equiv x < y \ , \text{ for all } x \ .$$
Then, transitivity of $<$ is equivalent to “$V_y$ is closed, for all $y$”.
Because the sequential precedence relation $>$ is transitive, the sequential history $H_f$ of an event $f$ is *closed with respect to* $>$ . In Section 1.2 we have called such a set a *state*; in view of the presence of other processes, and of the (yet to be introduced) notion of *global state*, we call such a set a *local state*.
**definition:** A *local state* is a finite set of events, all part of one and the same process, that is closed with respect to $>$.
\[ \square \]
In a very similar way, because the causal precedence relation $\rightarrow$ is transitive too, the causal history $G_f$ of every event $f$ is closed with respect to $\rightarrow$. The causal history of an event is (the relevant part of) the *global state* of the system just before that event takes place, and any finite set closed with respect to $\rightarrow$ represents some global system state.
**definition:** A *global state* is a finite set of events that is closed with respect to $\rightarrow$.
\[ \square \]
Not every finite set of events is a global state: the requirement of closedness is essential. In some of the literature, like [1], the phrase “consistent global state” is used; here the (somewhat redundant) adjective “consistent” just reminds of this closedness requirement.
We now introduce an (auxiliary) variable $\Sigma_p$ to represent the local state of process $p$. Its value is the set of all events that have occurred in process $p$ “thus far”. Notice that the order of these events is represented by $\triangleright$, which is why we only need a set (instead of a sequence). The initial value of $\Sigma_p$ is $\phi$, and the effect on $\Sigma_p$ of occurrence of event $f$ in process $p$ is:
$$\Sigma_p := \Sigma_p \cup \{ f \} .$$
Set $\Sigma_p$ contains the whole history of process $p$ and from a mathematical point of view this is convenient; in any practical implementation, however, the state of the process will only contain that part of its history that is relevant for its future. In view of such implementations $\Sigma_p$ is best considered an auxiliary variable.
If event $f$ “is about to occur” in process $p$ then the state $\Sigma_p$ contains exactly those events that sequentially precede $f$. This means that $H_f = \Sigma_p$ is a valid precondition of $\Sigma_p := \Sigma_p \cup \{ f \}$; if so desired, this precondition can be taken as $H_f$’s definition.
The (global) state of the system can now be defined as the union of the (local) states of the individual processes. Calling the global state $\Gamma$ we obtain:
$$\Gamma = (\cup p::\Sigma_p) .$$
In what follows we shall treat $\Gamma$ (which is redundant), not as an additional variable but as just an abbreviation of the expression $(\cup p::\Sigma_p)$; thus, we do not have to include manipulations of $\Gamma$ in the code of our programs.
Just as $H_f = \Sigma_p$ is a valid local precondition of $\Sigma_p := \Sigma_p \cup \{ f \}$, this state change also has as valid global precondition:
$$G_f \subseteq \Gamma .$$
This cannot be strengthened into an equality, however, because at the moment event $f$ is about to occur in process $p$, events may occur concurrently in the other processes too, as a result of which other $\Sigma$’s and, hence, $\Gamma$ increase. (Formally, this means that $G_f \subseteq \Gamma$ is globally correct whereas $G_f = \Gamma$ is not.)
1.5 Time stamps
The problem to be solved now is to develop a protocol by means of which information about the causal precedence of events in the system can be collected. More precisely, the problem is to define and implement an integer function $T$ on the set of events, with the following property.
**clock condition:** for all events $e, f$:
\[ e \rightarrow f \implies T_e < T_f \]
Traditionally, the value $T_e$ is called the “time stamp” of event $e$, because one (but only one) of the possible definitions of $T$ is such that $T_e = \text{"the moment at which event } e \text{ occurs"}; we shall also use this jargon, but keep in mind that (formally) $T$ has no connection with (physical) time whatsoever.
Because of the implication in the clock condition, function $T$ does not completely represent causal precedence: concurrent events may have different time stamps; yet, for any two non-concurrent events their causal order is represented by their time stamps:
\[
T_e < T_f \\
\Rightarrow \left\{ \begin{array}{l} < \text{ is antisymmetric } \\
\neg (T_f < T_e) \end{array} \right. \\
\Rightarrow \left\{ \begin{array}{l} \text{clock condition } \\
\neg (f \rightarrow e) \end{array} \right. \\
\Rightarrow \left\{ \begin{array}{l} (0) \\
e \parallel f \lor e \rightarrow f \end{array} \right.
\]
So, if $T_e < T_f$ then either $e$ and $f$ are concurrent, that is, causally unrelated, or $e \rightarrow f$. Similarly, we can derive that:
\[ T_e = T_f \Rightarrow e \parallel f \]
Because $T$ is an integer function and because the integers are totally ordered, function $T$ induces an (almost) total order on the set of events, whereas causal precedence itself is a (truly) partial order; hence, generally no integer function $T$ will also satisfy the so-called **strong clock condition**.
**strong clock condition:** for all events $e, f$:
To satisfy the strong clock condition we need functions to domains that are only partially ordered and not, like the integers, totally ordered. An example of such a domain is the space of \( N \)-dimensional integer vectors, where \( N \) is the number of processes in the system, but we shall not elaborate upon this here: for some applications the not-so-strong clock condition is perfectly adequate.
The solution to be derived in the next subsection does not depend on specific properties of the integers; therefore, this solution is generally applicable to various kinds of time stamps, such as the ones based upon so-called vector clocks, which have been invented by several researchers (see [3] for an overview).
### 1.6 An implementation
The problem to be solved now is to assign values to \( T \) for all events in the system, in such a way that the clock condition is satisfied for all pairs of events in \( \Gamma \). Formally, this means that \( T \) is a global variable now, and that the clock condition will be a system invariant. The solution will be such that \( T \cdot g \) will be initialised by process \( pr \cdot g \), just before \( g \) takes place, for each event \( g \): thus, global variable \( T \) is distributed over the processes.
The ordering of the integers is transitive; hence, according to the lemma in Section 1.3, the clock condition is implied by the following condition for \( \rightarrow \).
Thus we obtain a weaker invariant, which can be established more easily.
**basic clock invariant (i):**
\[
(\forall e,f : e,f \in \Gamma \land e \rightarrow f : T \cdot e < T \cdot f )
\]
Because \( \Gamma \) is closed with respect to \( \rightarrow \) and, hence, also with respect to \( \rightarrow \), this can be weakened – at least, formally speaking – even further: \( e \in \Gamma \) is implied by \( f \in \Gamma \) and \( e \rightarrow f \).
**basic clock invariant (ii):**
\[
(\forall e,f : f \in \Gamma \land e \rightarrow f : T \cdot e < T \cdot f )
\]
By means of the definition of $\rightarrow$ this can be reformulated into the following equivalent form, from which $\rightarrow$ has been eliminated altogether.
**basic clock invariant (iii):**
$$(\forall e, f : f \in \Gamma \land e \triangleright f : T \cdot e < T \cdot f) \land (\forall m : \text{rcv} \cdot m \in \Gamma : T \cdot (\text{snd} \cdot m) < T \cdot (\text{rcv} \cdot m))$$
$\square$
The two conjuncts of this version can be dealt with in isolation. A viable design strategy is, first, to satisfy the one conjunct by means of an as liberal solution as possible and, second, to restrict this solution to account for the second conjunct as well. That is what we shall attempt.
**the first conjunct**
The first conjunct from the basic clock invariant, that is:
$$(\forall e, f : f \in \Gamma \land e \triangleright f : T \cdot e < T \cdot f)$$
can be further partitioned, because, by definition, $\Gamma = (\cup p : \Sigma_p)$ and because for any events $e, f$ we have $e \triangleright f \Rightarrow pr \cdot e = pr \cdot f$.
As a consequence, the requirement can be meaningfully partitioned into a collection of (disjoint) parts, one per process, thus:
$$(\forall p : (\forall e, f : f \in \Sigma_p \land e \triangleright f : T \cdot e < T \cdot f))$$
This is meaningful because $f \in \Sigma_p \land e \triangleright f$ implies $e \in \Sigma_p$ as well; therefore, this requirement can now be satisfied term-wise, by turning it into a local invariant per process; thus, the local invariant for process $p$ becomes:
$$Q0: (\forall e, f : f \in \Sigma_p \land e \triangleright f : T \cdot e < T \cdot f)$$
By nesting dummies we rewrite this as follows:
$$Q0: (\forall f : f \in \Sigma_p : (\forall e : e \triangleright f : T \cdot e < T \cdot f))$$
The required invariance of $Q0$ under $\Sigma_p := \Sigma_p \cup \{ g \}$ — “event $g$ occurs” — gives rise to the precondition:
$$(*) : (\forall e : e \triangleright g : T \cdot e < T \cdot g)$$
Because \( e \triangleright g \equiv e \in H_g \) and because \( H_g = \Sigma_p \) is a valid part of the precondition too, condition \((\ast)\) is equivalent to
\[
\left( \forall e: e \in \Sigma_p : T \cdot e < T \cdot g \right),
\]
which can be established by means of a fresh integer variable \( c \), satisfying:
\[
\left( \forall e: e \in \Sigma_p : T \cdot e < c \right) \land c \leq T \cdot g.
\]
Variable \( c \) is a private variable of the process; in Lamport’s jargon \( c \) is called the “logical clock” of that process; the main technical reason to introduce it is modularisation, so as to isolate \( \Sigma_p \) from \( T \cdot g \): now \( \Sigma_p \) only occurs in the formula \( \left( \forall e: e \in \Sigma_p : T \cdot e < c \right) \). We turn this formula into an additional invariant, so what remains is the obligation to assign to \( T \cdot g \) a value that is at least \( c \) (and, of course, to establish the invariance of this new invariant).
Q1: \( \left( \forall e: e \in \Sigma_p : T \cdot e < c \right) \).
Initially Q1 holds, because, initially \( \Sigma_p = \phi \). (Hence, the initial value of \( c \) is irrelevant.) Moreover, Q1 is not violated by increases of \( c \), and \( \Sigma_p := \Sigma_p \cup \{ g \} \) maintains Q1 under the additional precondition \( T \cdot g < c \); this can be established by means of a sufficient increase of \( c \).
Hence, with respect to variables \( T, \Sigma_p, \) and \( c \), the occurrence of event \( g \) boils down to a program fragment of the following shape:
\[
T \cdot g := \text{“a value at least } c \text{”}\n; \{ c \leq T \cdot g \}\n\]
\[
c := \text{“a value exceeding } T \cdot g \text{”}\n; \{ T \cdot g < c \}\n\]
\[
\Sigma_p := \Sigma_p \cup \{ g \} \quad \text{ (“event } g \text{ occurs in process } p \text{”)}
\]
The assertions in this fragment specify which expressions are admissible in the assignments to \( T \cdot g \) and \( c \); the degrees of freedom we have here will be exploited when we deal with the second conjunct of the basic clock condition. (For example, the simplest possible choices meeting all requirements thus far, are \( T \cdot g := c \) and \( c := T \cdot g + 1 \) respectively.)
**the second conjunct**
We recall the second conjunct of the basic clock invariant:
Q2: \( \left( \forall m: \text{rcv-} m \in \Gamma : T \cdot (\text{snd-} m) < T \cdot (\text{rcv-} m) \right) \).
Invariance of Q2 is guaranteed, provided we see to it that every receive event is assigned a sufficiently large time stamp, that is, by seeing to it that \( T \cdot (r_{cv} \cdot m) \) is chosen large enough, for all \( m \). We do so by exploiting the strategic freedom in the previous program fragment, in the obvious way: if \( g \) is a receive event we just strengthen the postassertion of the initialisation of \( T \cdot g \) with \( t < T \cdot g \), where \( t \) is the time stamp of the corresponding send event. Thus we obtain as program fragment for receive events in process \( p \):
\[
\{ \text{snd} \cdot m \in \Gamma \} \quad \{ g = r_{cv} \cdot m \land t = T \cdot (\text{snd} \cdot m) \}
\]
\[
T \cdot g := \text{"a value at least } c \text{ and exceeding } t\text{"}
\]
\[
; \quad \{ c \leq T \cdot g \land t < T \cdot g \}
\]
\[
c := \text{"a value exceeding } T \cdot g\text{"}
\]
\[
; \quad \{ T \cdot g < c \}
\]
\[
\Sigma_p := \Sigma_p \cup \{ g \} \quad \text{("message } m \text{ is received in process } p\")
\]
Notice that, because of the preassertion \( \text{snd} \cdot m \in \Gamma \) – why is it valid? –, the value \( T \cdot (\text{snd} \cdot m) \) is well defined indeed: it has been initialized in the process that has sent message \( m \). To make this value available in the receiving process, it must be transmitted together with the message proper to the receiver – whence its name “time stamp” –. Also notice that, actually, we only need the weaker preassertion \( T \cdot (\text{snd} \cdot m) \leq t \) instead of \( T \cdot (\text{snd} \cdot m) = t \); occasionally, this may be an advantage.
### 1.7 Afterthoughts
In the previous two subsections, we have (deliberately) formulated the program fragments in a way that is independent of \( T \)'s type: its values need not be integers. These program fragments still leave quite some freedom in the choice of expressions. For integer-valued \( T \), here is the minimal choice for receive events – for send events the minimal assignment to \( T \cdot g \) remains \( T \cdot g := c \) –:
\[
\{ g = r_{cv} \cdot m \land t = T \cdot (\text{snd} \cdot m) \}
\]
\[
T \cdot g := c \cdot \text{max} \; (t+1)
\]
\[
; \quad \{ c \leq T \cdot g \land t < T \cdot g \}
\]
\[
c := T \cdot g + 1
\]
\[
; \quad \{ T \cdot g < c \}
\]
\[
\Sigma_p := \Sigma_p \cup \{ g \}
\]
In an actual implementation the identities of the events and their time stamps need not be recorded. All that matters is that each message sent is given the proper time stamp and that, upon reception of a message, variable
c is properly adjusted. Thus, we obtain the following program fragments for send and receive events, in which \textit{send}(t) and \textit{receive}(t) denote the sending and receiving of a message with time stamp \( t \) – annotation omitted –:
\[
\text{send}(c) \\
; c := c + 1
\]
and:
\[
\text{receive}(t) \quad (t \text{ is a private variable here}) \\
; c := c \max(t+1) + 1
\]
Variable \( c \) – the process’s logical clock – only occurs in invariant Q1, in a formula of the shape \( \cdots < c \) only. Therefore, the invariance of Q1 is not violated if we allow, “in between the events” so to speak, occasional additional increases of \( c \). This shows that we may indeed view \( c \) as a “clock”, which continues ticking even if no events take place. In this view an assignment like \( c := c \max(t+1) + 1 \) amounts to an “adjustment of the clock” (and a “tick”) to information received about the clock of another process.
Finally, notice that the initial value of \( c \) is still irrelevant. If we choose, for all processes, \( c = 0 \) initially, then \( T \cdot g \) can be interpreted as the length of a longest chain of events causally preceding \( g \), for every event \( g \). In this case variable \( c \) is better called an “event counter” rather than a “clock”.
Chapter 2
Distributed Mutual Exclusion
In this section we derive a distributed mutual exclusion algorithm. The notion of causal precedence makes it possible to discuss the fairness of the solution. Informally, fairness means here that requests are granted in the order in which they are made, where “order” means causal order: if one request causally precedes another, the former request is to be granted before the latter. So, this kind of fairness requirement does not restrict the order in which concurrent – unrelated – requests are granted; nevertheless, the protocol is such that individual progress is guaranteed.
Because mutual exclusion and fairness are different properties, we can (and shall) discuss them in isolation. First, we derive an algorithm that implements mutual exclusion, without any reference to causal precedence. Second, we shall refine this solution so as to obtain fairness.
2.0 Synchronisation
For the purpose of synchronisation we use the following (tentative) construct:
\[
\text{\{ } \text{\textbullet boolean expression } \text{\textbullet } \text{\}}
\]
with the operational meaning that its execution terminates only if the value of \textit{boolean expression} is \textit{true}; the net effect on the state of the system is nihil: the synchronisation statement causes no state changes. (A correct but not so efficient implementation is repeated evaluation of \textit{boolean expression} until its value is \textit{true}, also known as \textit{busy waiting}.)
Formally, a synchronisation statement can be used to strengthen an assertion in a program. That is, in an application like:
the additional post assertion $B$ is locally correct. (And, its global correctness still requires additional proof, as usual.)
2.1 Mutual exclusion for two processes
We consider a collection of (sequential) processes, each of which contains a so-called critical section. Operationally, the requirement of mutual exclusion is that, at any moment in time, at most one of the processes is executing its critical section. This can also be phrased as the requirement that, at any moment in time, no two processes are executing their critical sections simultaneously. Thus, mutual exclusion of many processes can be viewed as pair-wise mutual exclusion of any two processes in the system. (It is even possible to solve the problem this way, although too naive an approach introduces the danger of deadlock.)
To keep the nomenclature needed as sober as possible, we begin with a solution for 2 processes, named $p$ and $q$, only. Next, we generalize this solution to the case for many processes. Also, we use shared variables and an Owicki-Gries style of reasoning to obtain a correct solution; only after having obtained it, we will take into account that the processes are distributed and that, as a consequence, the shared variables must be implemented by means of private variables and message transmissions. So, we use a top-down approach, in which “being distributed” is considered an implementation issue, although some of the design decisions are clearly inspired by the desire to make such a distributed implementation possible.
\[ \{ Q \} \{ B \} \]
The problem is symmetric in the processes and, as usual, we shall retain this symmetry (and exploit it in the presentation). As starting point, we use the following prototype program, in which two boolean variables $x_i$ occur and two assertions $R_i$, still to be chosen, for $i \in \{ p, q \}$. Every assignment and every guard in this program is considered atomic. This prototype program is (by now) well known, and it allows for many elaborations:
initially: $\neg x_p \land \neg x_q$
program \( p \): \[ \text{do forever} \rightarrow \]
\[
\{ \neg x_p \} \\
x_p := \text{true} \\
; \{ x_p \} \\
\{ \bullet \neg x_q \lor R_p \bullet \} \\
; \{ x_p \} \{ \neg x_q \lor R_p \} \\
\begin{align*}
\text{Critical Section} \quad p \\
x_p := \text{false}
\end{align*}
\] od
The predicates \( R \) must now be chosen in such a way that they satisfy three requirements, namely:
- The assertions in this program are \textit{correct}, and:
- \( R_p \) and \( R_q \) are \textit{disjoint}, to guarantee the required mutual exclusion.
- The preassertions of the synchronisation statements (together) imply \( R_p \lor R_q \), so as to guarantee absence of deadlock.
\textbf{example:} The choice \( R_p \equiv v = p \), where \( v \) is a fresh variable introduced for the purpose, gives rise to Peterson’s algorithm.
As the first step towards the solution we introduce – this is a design decision – an integer function \( F \) on the set of process names. Because the integers are totally ordered we have:
\[ F_p = F_q \lor F_p < F_q \lor F_q < F_p , \]
and, more important, we also have:
\[ \neg (F_p < F_q) \lor \neg (F_q < F_p) . \]
This yields the required disjointness, so we choose:
\[ R_p \equiv F_p < F_q \text{ and } R_q \equiv F_q < F_p . \]
With this choice the requirement of mutual exclusion is satisfied, so the only problems we are left with are the correctness of the assertions and the possibility that \( F_p = F_q \), which gives rise to the danger of deadlock. To exclude the latter we \textit{require} function \( F \) to be chosen in such a way that all its values are different:
In Section 2.4 we shall deal with this requirement.
In this design, priority is given to the process with the smaller value of $F$. In view of the required fairness, $F$ cannot be constant, but must be a variable. Because of the shape of the formula $\neg x_p \lor F_p < F_q$ (in program $q$), an assignment to $F_p$ is harmless – with respect to the proof obligations – when it has $\neg x_p$ as its precondition. Therefore, we combine the (necessary) assignment to $F_p$ with $x_p := \text{true}$, which already has $\neg x_p$ as precondition. The value to be assigned to $F_p$ is obtained from a private variable $c_p$, introduced for this purpose – this is a design decision too –; we postpone (for a while) the question how to manipulate $c_p$. Thus, we obtain a solution with the following structure:
Initially: \[ \neg x_p \land \neg x_q \]
Program $p$: \[
\text{do forever} \rightarrow \\
\{ \neg x_p \} \\
x_p, F_p := \text{true}, c_p \\
; \{ x_p \} \\
\{ \bullet \neg x_q \lor F_p < F_q \bullet \} \\
; \{ x_p \} \{ \neg x_q \lor F_p < F_q (\bullet 0) \} \\
\text{Critical Section } p \\
; x_p := \text{false} \\
\text{od}
\]
The assertion labelled $(\bullet 0)$ is locally correct because of the immediately preceding guard. As for its global correctness, the assignment $x_q := \text{false}$ (in program $q$) is harmless – rule of widening –, whereas the assignment (in $q$) $x_q, F_q := \text{true}, c_q$ requires as additional precondition: $F_p < c_q$. To incorporate this additional condition we have 3 options, namely:
- make $F_p < c_q$ a system invariant;
- add $F_p < c_q$ as preassertion to $x_q, F_q := \text{true}, c_q$ in program $q$;
- add $F_p < c_q$ as co-assertion to assertion $(\bullet 0)$ in program $p$.
The latter option is attractive, because it generates the least amount of new proof obligations; actually, it generates hardly any new proof obligations if we adopt the rule that the variables $c$ will never be decreased. (This is another design decision.)
So, we adopt this rule, and we add $F_p < c_q$ as co-assertion to assertion ($\bullet 0$) in program $p$; its local correctness is most easily established by including it into the preceding guard, and its global correctness now follows from the adopted rule that $c_q$ will only be increased -- rule of widening --.
This yields our first approximation of the solution. This solution is correct, but for the sake of progress we must still see to it that the variables $c$ are increased “every now and then”. (This will be taken care of when we construct a distributed implementation.)
initially: $\neg x_p \land \neg x_q$
program $p$:
\[
\begin{align*}
\text{do forever} & \rightarrow \\
\{ \neg x_p \} & \ \\
x_p, F_p := \text{true}, c_p & \\
; \ { x_p } & \\
\{ \bullet (\neg x_q \lor F_p < F_q) \land F_p < c_q \bullet \} & \\
; \ { x_p } \{ \neg x_q \lor F_p < F_q \} \{ F_p < c_q \} & \\
\text{Critical Section } p & \\
; \ x_p := \text{false} &
\end{align*}
\]
d \square
aside: The decision to obtain the values for $F$ from dedicated private variables certainly is inspired by the desire to obtain a solution that can be implemented in a distributed way. Instead of a private variable per process we could also have introduced a single shared variable $C$; this is simpler, but from the point of view of distribution this is less attractive. Had we done so, however, we would have obtained what is known as Lamport’s “Bakery Algorithm”:
initially: $\neg x_p \land \neg x_q$
program $p$:
\[
\begin{align*}
\text{do forever} & \rightarrow \\
\{ \neg x_p \} & \\
x_p, F_p, C := \text{true}, C, C + 1 & \\
; \ { x_p } \{ F_p < C \} & \\
\{ \bullet \neg x_q \lor F_p < F_q \bullet \} & \\
; \ { x_p } \{ \neg x_q \lor F_p < F_q \} \{ F_p < C \} & \\
\text{Critical Section } p & \\
; \ x_p := \text{false} &
\end{align*}
\]
2.2 Distributed implementation
Process $p$ contains as guard $(\neg x_q \lor F_p F_q) \land F_p < c_q$; this expression contains one private variable, $F_p$, and three shared variables, $x_q, F_q,$ and $c_q$; if processes $p$ and $q$ are to be implemented in different nodes of a distributed system this is awkward. Therefore, we decide to delegate the evaluation of this guard to a dedicated new process, called “co-process $p,q$”. The idea is that this co-process will be implemented in the same machine as process $q$; as a result, (we assume that) process $q$ and co-process $p,q$ can share their variables without any difficulty.
This is attractive because the evaluation of $p$’s guard takes place in states where $x_p$ is true, whereas the assignment to $F_p$ has $\neg x_p$ as precondition: so, during the evaluation of $p$’s guard the value of $F_p$ is stable. This is relevant because from the viewpoint of the co-process, $F_p$ is a shared variable now.
Process $p$ and co-process $p,q$ are synchronized by means of message exchanges. First, process $p$ sends a message containing $F_p$ to co-process $p,q$ and then receives a (so-called) acknowledgement, which is just an empty message. Second, after having received $F_p$ co-process $p,q$ establishes the required condition $(\neg x_q \lor F_p F_q) \land F_p < c_q$ and then communicates this fact back to process $p$ by sending an acknowledgement. (This form of message exchanges implements a two-phase handshake.) The conjunct $F_p < c_q$ is established (in co-process $p,q$) by increasing $c_q$ sufficiently; thus, the obligation to increase the variables $c$ “every now and then” is discharged.
This yields our second version of the solution. The correctness of the new assertions is easily verified; this is left as an exercise.
initially: $\neg x_p \land \neg x_q$
program $p$: do forever $\rightarrow$
\begin{verbatim}
{ $\neg x_p$ } $x_p, F_p := \text{true}, c_p$
{ $x_p$ } $F_p$ to co $p,q$
{ $x_p$ } receive-acknowledgement from co $p,q$
{ $x_p$ } { $\neg x_q \lor F_p F_q$ } { $F_p < c_q$ }
Critical Section $p$
{ $x_p := \text{false}$ }
\end{verbatim}
od
co p,q : do forever →
receive f from p
; { x_p } { f = F_p }
c_q := “a value exceeding f”
; { x_p } { f = F_p } { f < c_q , hence: F_p < c_q }
{ • ¬x_q \lor f < F_q • }
; { x_p } { ¬x_q \lor F_p < F_q } { F_p < c_q }
send-acknowledgement to p
od
2.3 Many processes
Mutual exclusion of a single process with many other processes amounts to pair-wise mutual exclusion of that single process with each of the other processes in the system. Formally, this means that the conjuncts of the requirement (∀q : p ≠ q : ¬x_q \lor R_{p,q}) can be implemented in isolation.
Thus, by generalisation of the previous solution for two processes, we obtain the following solution for many processes. Here, for every process p a co-process co p,q is associated with every other process q in the system. So, if the number of processes proper in the system equals N this solution involves N * (N-1) co-processes in total.
It is possible to combine, for every q, all co-processes co p,q into a single co-process associated with process q, thus reducing the total number of processes in the system to 2*N, but we shall not explore this here.
initially: (∀q : ¬x_q)
program p : do forever →
{ ¬x_p }
x_p, F_p := true, c_p
; { x_p }
( || q : p ≠ q : send F_p to co p,q
; receive-acknowledgement from co p,q
{ ¬x_q \lor F_p < F_q } { F_p < c_q }
)
; { x_p } { (∀q : p ≠ q : (¬x_q \lor F_p < F_q) \land F_p < c_q ) }
Critical Section p
; x_p := false
od
\[
\text{co } p,q: \quad \text{do forever} \rightarrow
\]
\[
\quad \text{receive } f \text{ from } p
\]
\[
; \{ \ x_p \} \{ \ f = F_p \}
\]
\[
\quad e_q := \text{"a value exceeding } f" \n\]
\[
; \{ \ x_p \} \{ \ f = F_p \} \{ \ f < e_q \text{ , hence: } F_p < c_q \}
\]
\[
\quad (\star) \quad \neg x_q \lor f < F_q \lor \star
\]
\[
; \{ \ x_p \} \{ \neg x_q \lor F_p < F_q \} \{ \ F_p < c_q \}
\]
\[
\quad \text{send-acknowledgement to } p
\]
2.4 Keeping the values different
For every \( q \), variables \( F_q \) and \( c_q \) and the assignment \( F_q := c_q \) are local to the processes \( q \) and \( co \ p,q \). Hence, without additional provisions we cannot guarantee that \( (\forall p,q: p \neq q : F_p \neq F_q) \).
One possible way to achieve this is to use pairs instead of just integers: the one component of the pair is an integer and the other component is a name of a process. By means of the lexicographic order, the process names act as “tie breakers” whenever the integer components of two pairs happen to be equal. This requires, of course, that the process names are totally ordered, and this destroys the symmetry among the processes (to some extent).
So, instead of \( F_q := c_q \) we now use:
\[
F_q := (c_q, q)
\]
and to evaluate \( F_p < F_q \) we define:
\[
(x, p) < (y, q) \equiv x < y \lor (x = y \land p < q)
\]
2.5 Progress and fairness
To demonstrate progress of process \( p \) we must show that it will execute its \textit{Critical Section} within finitely many steps after it has executed its assignment \( x_p := \text{true} \). This boils down to the requirement that process \( p \), within finitely many steps after the assignment \( x_p := \text{true} \), receives an acknowledgement from \( co \ p,q \), for all \( q \).
First, process \( p \) sends its \( F_p \) to \( co \ p,q \). Assuming that \( co \ p,q \) is in its initial state, ready to receive a value from \( p \), and assuming that the communication channel from \( p \) to \( co \ p,q \) is reliable, the statement \textit{receive } f \text{ from } p \text{ (in } co \ p,q \text{) will terminate. Next, } co \ p,q \text{ establishes } F_p < c_q \text{, by means of its}
assignment to $c_q$; as this is true for any $q$, we even conclude that, after finitely many steps, we have $(\forall r: p \neq r: F_p < c_r)$.
Second, $co \, p,q$ will execute its send-acknowledgement to $p$ (and return to its initial state), provided its synchronization statement terminates; if the communication channel from $co \, p,q$ to $p$ is reliable too, process $p$ will indeed receive an acknowledgement from $co \, p,q$.
Third, we are left with the obligation to show that the synchronization statement in $co \, p,q$ is guaranteed to terminate, which is the case if its guard $\neg x_q \lor F_p < F_q$ becomes stably true within finitely many steps (of the system). Because $\neg x_q \lor F_p < F_q$ is a correct, that is: stable, assertion in the program, we only have to show that it becomes true within finitely many steps. Now we consider set $V$, defined by:
$$r \in V \equiv x_r \land F_r < F_p \ , \text{ for all } r \ ,$$
and we do so in a state satisfying: $(\forall r: p \neq r: F_p < c_r)$. Because of this, no assignment $x_r, F_r := \text{true}, c_r$ adds $r$ to $V$; hence, no new members enter $V$ anymore after $(\forall r: p \neq r: F_p < c_r)$ has become true. If now, by induction hypothesis, every process $r$ in $V$ terminates its Critical Section and, subsequently, completes $x_r := \text{false}$ and, thus, effectively removes itself from $V$, set $V$ will become empty after finitely many steps. (So, here we use mathematical induction over the values of function $F$. ) Once $V$ is empty we also have what we needed, namely: $\neg x_q \lor F_p < F_q$.
It is important to observe that the latency of the communication channel from $p$ to $co \, p,q$ plays a crucial role here: as long as $p$’s message, carrying $F_p$, has not yet arrived at $co \, p,q$, the waiting time for $p$ cannot be bounded. Only after $co \, p,q$ has received $p$’s request the number of steps taken by the system until $p$’s request is granted can be meaningfully considered.
Chapter 3
Epilogue
In the examples I have seen thus far, the only events in whose causal relationship we seem to be interested are the send events. It may, therefore, be easier and simpler to define causal precedence as a relation on send events only. Moreover, because of the one-to-one correspondence between send events and messages, we may as well define causal precedence as a relation on messages. So, for messages $i, j$, we would write $i + j$ instead of $snd_i
ightarrow snd_j$. Similarly, function $T$ could be defined directly on messages, such that $T_i$ is the time stamp of message $i$.
The new causal precedence $+>$ could be defined as the transitive closure of a basic precedence relation $->$, which could be defined as follows.
**basic precedence:** for all messages $i, j$:
$$i > j \equiv \text{snd}_i > \text{snd}_j \lor \text{rcv}_i > \text{snd}_j.$$
Now it should be possible to prove the equivalence of the two forms of causal precedence, that is: $(\forall i, j:: i + j \equiv \text{snd}_i \rightarrow \text{snd}_j)$.
This approach seems to yield simpler formulae and deserves, therefore, further attention. For instance, the program fragment that corresponds to reception of message $i$ with time stamp $t$ now becomes – here variable $M$ is the set of messages sent or received by the process –:
```plaintext
{ \ t = T\cdot i \ }
\ c := c \max (t+1)
; \ \{ T\cdot i < c \}
\ M := M \cup \{i\}
```
Bibliography
|
{"Source-Url": "https://pure.tue.nl/ws/files/1906131/200210804.pdf", "len_cl100k_base": 13604, "olmocr-version": "0.1.49", "pdf-total-pages": 29, "total-fallback-pages": 0, "total-input-tokens": 76048, "total-output-tokens": 15659, "length": "2e13", "weborganizer": {"__label__adult": 0.0004019737243652344, "__label__art_design": 0.0005388259887695312, "__label__crime_law": 0.00044918060302734375, "__label__education_jobs": 0.00127410888671875, "__label__entertainment": 0.00012731552124023438, "__label__fashion_beauty": 0.00020682811737060547, "__label__finance_business": 0.0005621910095214844, "__label__food_dining": 0.00051116943359375, "__label__games": 0.00077056884765625, "__label__hardware": 0.001956939697265625, "__label__health": 0.000935077667236328, "__label__history": 0.0004875659942626953, "__label__home_hobbies": 0.0002264976501464844, "__label__industrial": 0.0007867813110351562, "__label__literature": 0.0006852149963378906, "__label__politics": 0.00041103363037109375, "__label__religion": 0.0007691383361816406, "__label__science_tech": 0.271240234375, "__label__social_life": 0.00015556812286376953, "__label__software": 0.009429931640625, "__label__software_dev": 0.70654296875, "__label__sports_fitness": 0.0003457069396972656, "__label__transportation": 0.0011167526245117188, "__label__travel": 0.0002562999725341797}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52816, 0.01153]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52816, 0.28076]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52816, 0.88712]], "google_gemma-3-12b-it_contains_pii": [[0, 2127, false], [2127, 2208, null], [2208, 2781, null], [2781, 4634, null], [4634, 6311, null], [6311, 8923, null], [8923, 11237, null], [11237, 13208, null], [13208, 15555, null], [15555, 17581, null], [17581, 19356, null], [19356, 21723, null], [21723, 23583, null], [23583, 25592, null], [25592, 27567, null], [27567, 29981, null], [29981, 32573, null], [32573, 33866, null], [33866, 35492, null], [35492, 37540, null], [37540, 39154, null], [39154, 41153, null], [41153, 42987, null], [42987, 45125, null], [45125, 46627, null], [46627, 48815, null], [48815, 50811, null], [50811, 52244, null], [52244, 52816, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2127, true], [2127, 2208, null], [2208, 2781, null], [2781, 4634, null], [4634, 6311, null], [6311, 8923, null], [8923, 11237, null], [11237, 13208, null], [13208, 15555, null], [15555, 17581, null], [17581, 19356, null], [19356, 21723, null], [21723, 23583, null], [23583, 25592, null], [25592, 27567, null], [27567, 29981, null], [29981, 32573, null], [32573, 33866, null], [33866, 35492, null], [35492, 37540, null], [37540, 39154, null], [39154, 41153, null], [41153, 42987, null], [42987, 45125, null], [45125, 46627, null], [46627, 48815, null], [48815, 50811, null], [50811, 52244, null], [52244, 52816, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52816, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52816, null]], "pdf_page_numbers": [[0, 2127, 1], [2127, 2208, 2], [2208, 2781, 3], [2781, 4634, 4], [4634, 6311, 5], [6311, 8923, 6], [8923, 11237, 7], [11237, 13208, 8], [13208, 15555, 9], [15555, 17581, 10], [17581, 19356, 11], [19356, 21723, 12], [21723, 23583, 13], [23583, 25592, 14], [25592, 27567, 15], [27567, 29981, 16], [29981, 32573, 17], [32573, 33866, 18], [33866, 35492, 19], [35492, 37540, 20], [37540, 39154, 21], [39154, 41153, 22], [41153, 42987, 23], [42987, 45125, 24], [45125, 46627, 25], [46627, 48815, 26], [48815, 50811, 27], [50811, 52244, 28], [52244, 52816, 29]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52816, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
8589f7a398c79d730c50cfe2bbbd5f2041221e85
|
[REMOVED]
|
{"Source-Url": "http://openaccess.city.ac.uk/1141/1/Constructors.pdf", "len_cl100k_base": 15837, "olmocr-version": "0.1.50", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 81123, "total-output-tokens": 18864, "length": "2e13", "weborganizer": {"__label__adult": 0.00047898292541503906, "__label__art_design": 0.0005927085876464844, "__label__crime_law": 0.00042366981506347656, "__label__education_jobs": 0.0013647079467773438, "__label__entertainment": 0.00010752677917480467, "__label__fashion_beauty": 0.0002295970916748047, "__label__finance_business": 0.0003082752227783203, "__label__food_dining": 0.0006227493286132812, "__label__games": 0.0007414817810058594, "__label__hardware": 0.0009851455688476562, "__label__health": 0.0011072158813476562, "__label__history": 0.0004248619079589844, "__label__home_hobbies": 0.0001850128173828125, "__label__industrial": 0.0007395744323730469, "__label__literature": 0.0006575584411621094, "__label__politics": 0.0004494190216064453, "__label__religion": 0.0009055137634277344, "__label__science_tech": 0.0789794921875, "__label__social_life": 0.0001443624496459961, "__label__software": 0.004924774169921875, "__label__software_dev": 0.90380859375, "__label__sports_fitness": 0.0004012584686279297, "__label__transportation": 0.0009245872497558594, "__label__travel": 0.00027489662170410156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57156, 0.00933]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57156, 0.73471]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57156, 0.78483]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2700, false], [2700, 5275, null], [5275, 7206, null], [7206, 10430, null], [10430, 13270, null], [13270, 15551, null], [15551, 17453, null], [17453, 20031, null], [20031, 22292, null], [22292, 24361, null], [24361, 26378, null], [26378, 28536, null], [28536, 31415, null], [31415, 33346, null], [33346, 35472, null], [35472, 37371, null], [37371, 39490, null], [39490, 42121, null], [42121, 45005, null], [45005, 46989, null], [46989, 49206, null], [49206, 51555, null], [51555, 53008, null], [53008, 55787, null], [55787, 57156, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2700, true], [2700, 5275, null], [5275, 7206, null], [7206, 10430, null], [10430, 13270, null], [13270, 15551, null], [15551, 17453, null], [17453, 20031, null], [20031, 22292, null], [22292, 24361, null], [24361, 26378, null], [26378, 28536, null], [28536, 31415, null], [31415, 33346, null], [33346, 35472, null], [35472, 37371, null], [37371, 39490, null], [39490, 42121, null], [42121, 45005, null], [45005, 46989, null], [46989, 49206, null], [49206, 51555, null], [51555, 53008, null], [53008, 55787, null], [55787, 57156, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57156, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57156, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2700, 2], [2700, 5275, 3], [5275, 7206, 4], [7206, 10430, 5], [10430, 13270, 6], [13270, 15551, 7], [15551, 17453, 8], [17453, 20031, 9], [20031, 22292, 10], [22292, 24361, 11], [24361, 26378, 12], [26378, 28536, 13], [28536, 31415, 14], [31415, 33346, 15], [33346, 35472, 16], [35472, 37371, 17], [37371, 39490, 18], [39490, 42121, 19], [42121, 45005, 20], [45005, 46989, 21], [46989, 49206, 22], [49206, 51555, 23], [51555, 53008, 24], [53008, 55787, 25], [55787, 57156, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57156, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
739afa3cab1646d3aea77485bb33305bc0b60d1d
|
Understanding VPLS Label Blocks Operation
This product includes the Envoy SNMP Engine, developed by Epilogue Technology, an Integrated Systems Company. Copyright © 1986-1997, Epilogue Technology Corporation. All rights reserved. This program and its documentation were developed at private expense, and no part of them is in the public domain.
This product includes memory allocation software developed by Mark Moraes, copyright © 1988, 1989, 1995, University of Toronto.
This product includes FreeBSD software developed by the University of California, Berkeley, and its contributors. All of the documentation and software included in the 4.4BSD and 4.4BSD-Lite Releases is copyrighted by the Regents of the University of California. Copyright © 1979, 1980, 1983, 1986, 1988, 1989, 1991, 1992, 1993, 1994. The Regents of the University of California. All rights reserved.
GateD software copyright © 1995, the Regents of the University. All rights reserved. Gate Daemon was originated and developed through release 3.0 by Cornell University and its collaborators. GateD is based on Kirton’s EGP, UC Berkeley’s routing daemon (routed), and DCN’s HELLO routing protocol. Development of Gated has been supported in part by the National Science Foundation. Portions of the GateD software copyright © 1988, Regents of the University of California. All rights reserved. Portions of the GateD software copyright © 1991, D. L. S. Associates.
This product includes software developed by Maker Communications, Inc., copyright © 1996, 1997, Maker Communications, Inc.
Juniper Networks, the Juniper Networks logo, JUNOS, NetScreen, ScreenOS, and Steel-Belted Radius are registered trademarks of Juniper Networks, Inc. in the United States and other countries. JUNOS is a trademark of Juniper Networks, Inc. All other trademarks, service marks, registered trademarks, or registered service marks are the property of their respective owners.
Juniper Networks assumes no responsibility for any inaccuracies in this document. Juniper Networks reserves the right to change, modify, transfer, or otherwise revise this publication without notice.
Products made or sold by Juniper Networks or components thereof might be covered by one or more of the following patents that are owned by or licensed to Juniper Networks: U.S. Patent Nos. 5,473,599, 5,905,725, 5,909,440, 6,192,051, 6,333,650, 6,359,479, 6,406,312, 6,429,706, 6,459,579, 6,493,347, 6,538,518, 6,538,899, 6,552,918, 6,567,902, 6,578,186, and 6,590,785.
Technology Overview Understanding VPLS Label Blocks Operation
Copyright © 2010, Juniper Networks, Inc.
All rights reserved. Printed in USA.
Writing: Sridhar Selvarangam
Editing: Nancy Kurahashi, Katie Smith, Marilyn Kerr, Roy Spencer
Illustration: Faith Bradford
Cover Design: Edmonds Design
Revision History
December 2009—Revision 1
The information in this document is current as of the date listed in the revision history.
YEAR 2000 NOTICE
Juniper Networks hardware and software products are Year 2000 compliant. The JUNOS Software has no known time-related limitations through the year 2038. However, the NTP application is known to have some difficulty in the year 2036.
END USER LICENSE AGREEMENT
READ THIS END USER LICENSE AGREEMENT (“AGREEMENT”) BEFORE DOWNLOADING, INSTALLING, OR USING THE SOFTWARE. BY DOWNLOADING, INSTALLING, OR USING THE SOFTWARE OR OTHERWISE EXPRESSING YOUR AGREEMENT TO THE TERMS CONTAINED HEREIN, YOU (AS CUSTOMER OR IF YOU ARE NOT THE CUSTOMER, AS A REPRESENTATIVE/AGENT AUTHORIZED TO BIND THE CUSTOMER) CONSENT TO BE BOUND BY THIS AGREEMENT. IF YOU DO NOT OR CANNOT AGREE TO THE TERMS CONTAINED HEREIN, THEN (A) DO NOT DOWNLOAD, INSTALL, OR USE THE SOFTWARE, AND (B) YOU MAY CONTACT JUNIPER NETWORKS REGARDING LICENSE TERMS.
1. The Parties. The parties to this Agreement are (i) Juniper Networks, Inc. (if the Customer’s principal office is located in the Americas) or Juniper Networks (Cayman) Limited (if the Customer’s principal office is located outside the Americas) (such applicable entity being referred to herein as “Juniper”), and (ii) the person or organization that originally purchased from Juniper or an authorized Juniper reseller the applicable license(s) for use of the Software (“Customer”) (collectively, the “Parties”).
2. The Software. In this Agreement, “Software” means the program modules and features of the Juniper or Juniper-supplied software, for which Customer has paid the applicable license or support fees to Juniper or an authorized Juniper reseller, or which was embedded by Juniper in equipment which Customer purchased from Juniper or an authorized Juniper reseller. “Software” also includes updates, upgrades and new releases of such software. “Embedded Software” means Software which Juniper has embedded in or loaded onto the Juniper equipment and any updates, upgrades, additions or replacements which are subsequently embedded in or loaded onto the equipment.
3. License Grant. Subject to payment of the applicable fees and the limitations and restrictions set forth herein, Juniper grants to Customer a non-exclusive and non-transferable license, without right to sublicense, to use the Software, in executable form only, subject to the following use restrictions:
a. Customer shall use Embedded Software solely as embedded in, and for execution on, Juniper equipment originally purchased by Customer from Juniper or an authorized Juniper reseller.
b. Customer shall use the Software on a single hardware chassis having a single processing unit, or as many chassis or processing units for which Customer has paid the applicable license fees, provided, however, with respect to the Steel-Belted Radius or Odyssey Access Client software only, Customer shall use such Software on a single computer containing a single physical random access memory space and containing any number of processors. Use of the Steel-Belted Radius or IMS AAA software on multiple computers or virtual machines (e.g., Solaris zones) requires multiple licenses, regardless of whether such computers or virtualizations are physically contained on a single chassis.
c. Product purchase documents, paper or electronic user documentation, and/or the particular licenses purchased by Customer may specify limits to Customer’s use of the Software. Such limits may restrict use to a maximum number of seats, registered endpoints, concurrent users, sessions, calls, connections, subscribers, clusters, nodes, realms, devices, links, ports or transactions, or require the purchase of separate licenses to use particular features, functionalities, services, applications, operations, or capabilities, or provide throughput, performance, configuration, bandwidth, interface, processing, temporal, or geographical limits. In addition, such limits may restrict the use of the Software to managing certain kinds of networks or require the Software to be used only in conjunction with other specific Software. Customer’s use of the Software shall be subject to all such limitations and purchase of all applicable licenses.
d. For any trial copy of the Software, Customer’s right to use the Software expires 30 days after download, installation or use of the Software. Customer may operate the Software after the 30-day trial period only if Customer pays for a license to do so. Customer may not extend or create an additional trial period by re-installing the Software after the 30-day trial period.
e. The Global Enterprise Edition of the Steel-Belted Radius software may be used by Customer only to manage access to Customer’s enterprise network. Specifically, service provider customers are expressly prohibited from using the Global Enterprise Edition of the Steel-Belted Radius software to support any commercial network access services.
The foregoing license is not transferable or assignable by Customer. No license is granted herein to any user who did not originally purchase the applicable license(s) for the Software from Juniper or an authorized Juniper reseller.
4. Use Prohibitions. Notwithstanding the foregoing, the license provided herein does not permit the Customer to, and Customer agrees not to and shall not: (a) modify, unbundle, reverse engineer, or create derivative works based on the Software; (b) make unauthorized copies of the Software (except as necessary for backup purposes); (c) rent, sell, transfer, or grant any rights in and to any copy of the Software, in any form, to any third party; (d) remove any proprietary notices, labels, or marks on or in any copy of the Software or any product in which the Software is embedded; (e) distribute any copy of the Software to any third party, including as may be embedded in Juniper equipment sold in the secondhand market; (f) use any “locked” or key-restricted feature, function, service, application, operation, or capability without first purchasing the applicable license(s) and obtaining a valid key from Juniper, even if such feature, function, service, application, operation, or capability is enabled without a key; (g) distribute any key for the Software provided by Juniper to any third party; (h) use the Software in any manner that extends or is broader than the uses purchased by Customer from Juniper or an authorized Juniper reseller; (i) use Embedded Software on non-Juniper equipment; (j) use Embedded Software (or make it available for use) on Juniper equipment that the Customer did not originally purchase from Juniper or an authorized Juniper reseller; (k) disclose the results of testing or benchmarking of the Software to any third party without the prior written consent of Juniper; or (l) use the Software in any manner other than as expressly provided herein.
5. Audit. Customer shall maintain accurate records as necessary to verify compliance with this Agreement. Upon request by Juniper, Customer shall furnish such records to Juniper and certify its compliance with this Agreement.
6. **Confidentiality.** The Parties agree that aspects of the Software and associated documentation are the confidential property of Juniper. As such, Customer shall exercise all reasonable commercial efforts to maintain the Software and associated documentation in confidence, which at a minimum includes restricting access to the Software to Customer employees and contractors having a need to use the Software for Customer’s internal business purposes.
7. **Ownership.** Juniper and Juniper’s licensors, respectively, retain ownership of all right, title, and interest (including copyright) in and to the Software, associated documentation, and all copies of the Software. Nothing in this Agreement constitutes a transfer or conveyance of any right, title, or interest in the Software or associated documentation, or a sale of the Software, associated documentation, or copies of the Software.
8. **Warranty, Limitation of Liability, Disclaimer of Warranty.** The warranty applicable to the Software shall be as set forth in the warranty statement that accompanies the Software (the “Warranty Statement”). Nothing in this Agreement shall give rise to any obligation to support the Software. Support services may be purchased separately. Any such support shall be governed by a separate, written support services agreement.
9. **Termination.** Any breach of this Agreement or failure by Customer to pay any applicable fees due shall result in automatic termination of the license granted hereunder. Upon such termination, Customer shall destroy or return to Juniper all copies of the Software and related documentation in Customer’s possession or control.
10. **Taxes.** All license fees payable under this agreement are exclusive of tax. Customer shall be responsible for paying Taxes arising from the purchase of the license, or importation or use of the Software. If applicable, valid exemption documentation for each taxing jurisdiction shall be provided to Juniper prior to invoicing, and Customer shall promptly notify Juniper if their exemption is revoked or modified. All payments made by Customer shall be net of any applicable withholding tax. Customer will provide reasonable assistance to Juniper in connection with such withholding taxes by promptly: providing Juniper with valid tax receipts and other required documentation showing Customer’s payment of any withholding taxes; completing appropriate applications that would reduce the amount of withholding tax to be paid; and notifying and assisting Juniper in any audit or tax proceeding related to transactions hereunder.
11. **Export.** Customer agrees to comply with all applicable export laws and restrictions and regulations of any United States and any applicable foreign agency or authority, and not to export or re-export the Software or any direct product thereof in violation of any such restrictions, laws or regulations, or without all necessary approvals.
12. **Commercial Computer Software.** The Software is “commercial computer software” and is provided with restricted rights. Use, duplication, or disclosure by the United States government is subject to restrictions set forth in this Agreement and as provided in DFARS 227.7201 through 227.7202-4, FAR 12.212, FAR 27 405(b)(2), FAR 52.227-19, or FAR 52.227-14(ALT II) as applicable.
13. **Interface Information.** To the extent required by applicable law, and at Customer’s written request, Juniper shall provide Customer with the interface information needed to achieve interoperability between the Software and another independently created program, on payment of applicable fee, if any.
14. **Third Party Software.** Any licensor of Juniper whose software is embedded in the Software and any supplier of Juniper whose products or technology are embedded in (or services are accessed by) the Software shall be a third party beneficiary with respect to this Agreement, and such licensor or vendor shall have the right to enforce this Agreement in its own name as if it were Juniper. In addition, certain third party software may be provided with the Software and is subject to the accompanying license(s), if any, of its respective owner(s). To the extent portions of the Software are distributed under and subject to open source licenses obligating Juniper to make the source code for such portions publicly available (such as the GNU General Public License (“GPL”) or the GNU Library General Public License (“LGPL”)), Juniper will make such source code portions (including Juniper modifications, as appropriate) available upon request for a period of up to three years from the date of distribution. Such request can be made in writing to Juniper Networks, Inc., 1194 N. Mathilda Ave., Sunnyvale, CA 94089, ATTN: General Counsel. You may obtain a copy of the GPL at http://www.gnu.org/licenses/gpl.html, and a copy of the LGPL at http://www.gnu.org/licenses/lgpl.html.
15. **Miscellaneous.** This Agreement shall be governed by the laws of the State of California without reference to its conflicts of laws principles. The provisions of the U.N. Convention for the International Sale of Goods shall not apply to this Agreement. For any disputes arising under this Agreement, the Parties hereby consent to the personal and exclusive jurisdiction of, and venue in, the state and federal courts within Santa Clara County, California. This Agreement constitutes the entire and sole agreement between Juniper and the Customer with respect to the Software, and supersedes all prior and contemporaneous
agreements relating to the Software, whether oral or written (including any inconsistent terms contained in a purchase order), except that the terms of a separate written agreement executed by an authorized Juniper representative and Customer shall govern to the extent such terms are inconsistent or conflict with terms contained herein. No modification to this Agreement nor any waiver of any rights hereunder shall be effective unless expressly assented to in writing by the party to be charged. If any portion of this Agreement is held invalid, the Parties agree that such invalidity shall not affect the validity of the remainder of this Agreement. This Agreement and associated documentation has been written in the English language, and the Parties agree that the English version will govern. (For Canada: Les parties aux présentés confirment leur volonté que cette convention de même que tous les documents y compris tout avis qui s’y rattache, soient rédigés en langue anglaise. (Translation: The parties confirm that this Agreement and all related documentation is and will be in the English language)).
Table of Contents
Overview .........................................................................................................1
Elements of Network Layer Reachability Information ................................1
Requirements for NLRI Elements .............................................................2
How Labels are Used in Label Blocks .....................................................2
Label Block Composition .......................................................................2
Label Blocks in JUNOS ..........................................................................3
VPLS Label Block Structure ..................................................................3
Example: Building a VPLS From Router 1 to Router 3 .................................5
Overview
This document describes the details of how virtual private LAN service (VPLS) labels are defined and exchanged in the Border Gateway Protocol (BGP) control plane. This document also describes how label blocks are allocated and used in the VPLS control plane for autodiscovery and signaling in the JUNOS Software implementation.
A VPLS is a Layer 2 (L2) service that emulates a local area network (LAN) across a wide area network (WAN).
There are two primary functions of the VPLS control plane: autodiscovery and signaling.
- **Autodiscovery** – A method for automatically recognizing each provider edge (PE) router in a particular VPLS domain, using BGP update messages.
- **Signaling** – Each pair of PE routers in a VPLS domain sends and withdraws VPN labels to each other. The labels are used to establish and dismantle pseudowires between the routers. Signaling is also used to transmit certain characteristics of a pseudowire.
The PE router uses BGP extended communities to identify the members of its VPLS. Once the PE discovers its members, it is able to establish and tear down pseudowires between members by exchanging and withdrawing labels and transmitting certain characteristics of the pseudowires.
The PE sends common update messages to all remote PEs, using a distinct BGP update message, thereby reducing the control plane load. This is achieved by using label blocks.
**Elements of Network Layer Reachability Information**
VPLS BGP network layer reachability information (NLRI) is used to exchange VPLS membership and parameters. A VPLS BGP NLRI has the elements defined in Table 1 on page 1.
<table>
<thead>
<tr>
<th>Element</th>
<th>Acronym</th>
<th>Description</th>
<th>Default Size (Octets)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Length</td>
<td></td>
<td>Total length of the NLRI size represented in bytes.</td>
<td>2</td>
</tr>
<tr>
<td>Route Distinguisher</td>
<td>RD</td>
<td>A unique identifier for each routing instance configured on a PE.</td>
<td>8</td>
</tr>
<tr>
<td>VPLS Edge ID</td>
<td>VE ID</td>
<td>A unique number to identify the edge site.</td>
<td>2</td>
</tr>
<tr>
<td>VE Block Offset</td>
<td>VBO</td>
<td>A value used to identify a label block from which a label value will be selected to set up pseudowires for a remote site</td>
<td>2</td>
</tr>
</tbody>
</table>
Table 1: Elements of the NLRI (continued)
<table>
<thead>
<tr>
<th>Element</th>
<th>Acronym</th>
<th>Description</th>
<th>Default Size (Octets)</th>
</tr>
</thead>
<tbody>
<tr>
<td>VE Block Size</td>
<td>VBS</td>
<td>Indicates the number of pseudowires that peers can have in a single block.</td>
<td>2</td>
</tr>
<tr>
<td>Label Base</td>
<td>LB</td>
<td>The starting value of the label in the advertised label block.</td>
<td>3</td>
</tr>
</tbody>
</table>
Requirements for NLRI Elements
JUNOS Software requires a unique route distinguisher (RD) for each routing instance configured on a PE. A PE router might use the same RD across a VPLS (or VPN) domain or it might use different RDs. Using different RDs helps identify the originator of the VPLS NLRI.
The VPLS edge (VE) ID can be a unique VE ID, site ID, or customer edge (CE) ID. The VE ID is used by a VPLS PE router to index into label blocks used to derive the transmit and receive VPN labels needed for transport of VPLS traffic. The VE ID identifies a particular site, so it needs to be unique within the VPLS domain, except for some scenarios such as multihoming.
All PE routers have full mesh connectivity with each other to exchange labels and set up pseudowires. The VE block size (VBS) is a configurable value that represents the number of label blocks required to cover all the pseudowires for the remote peer.
A single label block contains 8 labels (1 octet) by default. The default VBS in JUNOS Software is 2 blocks (2 octets) for a total of 16 labels.
How Labels are Used in Label Blocks
Each PE router creates a mapping of the labels in the label block to the sites in a VPLS domain. A PE router advertising a label block with a block offset indicates which sites can use the labels to reach it. When a PE router is ready to advertise its membership to a VPLS domain, it allocates a label block and advertises the VPLS NLRI. In this way, other PE routers in the same VPLS domain can learn of the existence of the VPLS and set up pseudowires to it if needed. The VPLS NLRI advertised for this purpose is referred to as the default VPLS NLRI. The label block in the default VPLS NLRI is referred to as the default label block.
Label Block Composition
A label block (set of labels) is used to reach a given site ID. A single label block contains 8 labels (1 octet) by default. The VBS is 2 octets by default in JUNOS Software.
The label block advertised is defined as a label base (LB) and a VE block size (VBS). It is a contiguous set of labels (LB, LB + 1,...LB + VBS-1). For example, when Router PE-A sends a VPLS update, it sends the same label block information to all other PE routers. Each PE router that receives the LB advertisement infers the label intended for Router PE-A by adding its own site ID to the label base.
In this manner, each receiving PE gets a unique label for PE-A for that VPLS. This simple method is enhanced by using a VE block offset (VBO).
A label block is defined as: \(<\text{Label Base (LB)}, \text{VE block offset (VBO)}, \text{VE block size (VBS)}>\) is the set \(\{\text{LB} + \text{VBO}, \text{LB} + \text{VBO} + 1, \ldots, \text{LB} + \text{VBO} + \text{VBS}-1\}\).
**Label Blocks in JUNOS**
Instead of a single large label block to cover all VE IDs in a VPLS, the JUNOS Software implementation contains several label blocks, each with a different label base. This makes label block management easier, and also allows Router PE-A to cater gracefully to a PE router joining a VPLS with a site ID not covered by the set of label blocks that Router PE-A has already advertised.
**VPLS Label Block Structure**
This section illustrates how a label block is uniquely identified.
A VPLS BGP NLRI with site ID V, VE block offset VBO, VE block size VBS, and label base LB communicates the following to its peers:
- Label block for V: Labels from LB to \((\text{LB} + \text{VBS} -1)\).
- Remote VE set for V: from VBO to \((\text{VBO} + \text{VBS} -1)\).
The label block advertised is a set of labels used to reach a given site ID. If there are several label blocks, the remote VE set helps to identify which label block to use. The example in Figure 1 on page 3 illustrates label blocks. There are 2 blocks and each block has eight labels. In this example, the label values are 64 to 71 and 80 to 87.
**Figure 1: VPLS Label Block Structure**
To create a one-to-one mapping of these sixteen labels to sixteen sites, assume the site IDs are the numbers 1 to 16, as shown in the illustration. The site block indicates which site ID can use which label in the label block. So, in the first block, site ID 1 will use 64, site ID 2 will use 65, and so forth. Finally, site ID 8 will use 71. The 9th site ID will use the second block instead of the first block.
The labels are calculated by comparing the values of VBO <= Local site ID < (VBO + VBS). Consequently, site ID 9 will use 80, site ID 10 will use 81, and so on.
To further illustrate the one-to-one mapping of labels to sites, assume a label block with site offset of 1 and a label base of 10. The combination of label base and block offset contained in the VPLS NLRI provides the mapping of labels to site IDs. The block offset is the starting site ID that can use the label block as advertised in the VPLS NLRI.
To advertise the default VPLS NLRI, a PE router picks a starting block offset that fits its own site ID and is such that the end block offset is a multiple of a single label block, in JUNOS Software a single label block is eight labels by default.
The end block offset is the last site ID that maps to the last label in the label block. The end offset for the first block is 8 which maps to label 17 and the second block is 16. For example, a site with ID 3 picks a block offset of 1 and advertises a label block of size 8 to cover sites with IDs 1 to 8. A site with ID 10 picks a block offset of 9 to cover sites with IDs 9 to 16.
The VPLS NLRI shown in Figure 2 on page 4 is for site ID 18. The label base contains value 262145. The block offset contains value 17. The illustration shows which site IDs correspond to which labels.
If a PE router configured with site ID 17 is in the same VPLS domain as a PE router configured with site ID 18, it receives the VPLS NLRI as shown in Figure 3. So it uses label 262145 to send traffic to site 18. Similarly, a PE router configured with site ID 19 uses label 262147 to send traffic to a PE router configured with site ID 18. However, only PE routers configured with site IDs 17 to 24 can use the label block shown to set up pseudowires.
Example: Building a VPLS From Router 1 to Router 3
This example illustrates how VPLS label blocks are allocated for a specific configuration. It is organized in the following sections:
- Requirements on page 5
- Overview and Topology on page 5
- Configuration on page 6
Requirements
This configuration example requires three Juniper Networks routers.
Overview and Topology
In the network shown in Figure 3 on page 5 Router 1 is establishing a pseudowire to Router 3

Each PE filters the VPLS NLRI contained in the BGP update messages based on route target communities. Those VPLS NLRI instances that match the route target (in this case 8717:2000:2:1) are imported for further processing. The NLRI for Router 1 and Router 3 is shown in Table 2 on page 5.
Table 2: NLRI Exchange Between for Router 1 and Router 3
<table>
<thead>
<tr>
<th>Router 1 NLRI Advertisement to Router 3</th>
<th>Router 3 NLRI Advertisement to Router 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>RD - 8717:1000</td>
<td>RD - 8717:1000</td>
</tr>
<tr>
<td>VE ID - 1</td>
<td>VE ID - 2</td>
</tr>
<tr>
<td>VE Block Offset - 1</td>
<td>VE Block Offset - 1</td>
</tr>
<tr>
<td>VE Block Size - 8</td>
<td>VE Block Size - 8</td>
</tr>
<tr>
<td>Label Base - 262161</td>
<td>Label Base - 262153</td>
</tr>
</tbody>
</table>
To set up a pseudowire to Router 3, Router 1 must select a label to use to send traffic to Router 3 and also select a label that it expects Router 3 to use to send traffic to itself. The site ID contained in the VPLS NLRI from Router 3 is 2.
Router 1 learns of the existence of site ID 2 in the same VPLS domain. Using the equation \( VBO \leq \text{Local Site ID} < (VBO + VBS) \), Router 1 checks if the route advertised by site ID 2 fits in the label block and block offset that it previously advertised to Router 3. In this example it does fit, so the site ID 2 is mapped by the VPLS NLRI advertised by Router 1, and Router 1 is ready to set up a pseudowire to Router 3.
To select the label to reach Router 3, Router 1 looks at the label block advertised by Router 3 and performs a calculation. The calculation a PE router uses to check if its site ID is mapped in the label block from the remote peer is \( VBO \leq \text{Local Site ID} < (VBO + VBS) \). So, Router 1 selects label \( 262153 + (1 - 1) = 262153 \) to send traffic to Router 3. Using the same equation, Router 1 looks at its own label block that it advertised and selects label \( 262161 + (2 - 1) = 262162 \) to receive traffic from Router 3. Router 1 programs its forwarding state such that any traffic destined to Router 3 carries the pseudowire label 262153 and any traffic coming from Router 3 is expected to have the pseudowire label 262162. This completes the operations on the VPLS NLRI received from Router 3. Router 1 now has a pseudowire set up to Router 3.
Router 3 operation is very similar to the Router 1 operation. Since the Router 3 site ID of 2 fits in the label block and block offset advertised by Router 1, Router 3 selects label \( 262161 + (2 - 1) = 262162 \) to send traffic to Router 1. Router 3 looks at its own label block that it advertised and selects label \( 262153 + (1 - 1) = 262153 \) to receive traffic from Router 1. This completes the creation of a pseudowire to Router 1.
By default, for VPLS operation JUNOS Software uses a virtual tunnel (VT) loopback interface to represent a pseudowire. This example uses a label-switched interface (LSI) instead of a VT interface because there is no change in the VPLS control plane operation. Thus, for an MX platform, if there is a tunnel physical interface card (PIC) configured, it is mandatory to include the `no-tunnel-services` statement at the `[edit routing-instances routing-instance-name protocols vpls]` hierarchy level.
## Configuration
The following sections present the steps to configure and verify the example.
- Configuring Router 1 on page 6
- Configuring Router 3 on page 7
- Verifying the VPLS Label Allocations on page 8
### Configuring Router 1
#### Step-by-Step Procedure
1. Configure Router 1. Create the `edut` routing instance. Specify the `vpls` instance type. Configure the route distinguisher and specify the value `8717:1000`. Configure the route target and specify the value `8717:100` Configure the VPLS
protocol. Specify 10 as the site range. Specify 1 as the site ID. Include the no-tunnel-services statement.
[edit routing-instances]
edut {
instance-type vpls;
interface ge-5/0/2.0;
route-distinguisher 8717:1000;
vrf-target target:8717:100;
protocols {
vpls {
site-range 10;
no-tunnel-services;
site router-1 {
site-identifier 1;
}
}
}
}
Configuring Router 3
Step-by-Step Procedure
1. Configure Router 3. Create the edut routing instance. Specify the vpls instance type. Configure the route distinguisher and specify the value 8717:2000. Configure the route target and specify the value 8717:200. Configure the VPLS protocol. Specify 10 as the site range. Specify 2 as the site ID. Include the no-tunnel-services statement.
[edit routing-instances]
edut {
instance-type vpls;
interface ge-4/0/2.0;
route-distinguisher 8717:2000;
vrf-target target:8717:100;
protocols {
vpls {
site-range 10;
no-tunnel-services;
site router-3 {
site-identifier 2;
}
}
}
}
**Verifying the VPLS Label Allocations**
**Step-by-Step Procedure**
1. As shown in the figure and the configuration, Site A is attached to Router 1. Site A is assigned a site ID of 1. Before Router 1 can announce its membership to VPLS edut using a BGP update message, Router 1 needs to allocate a default label block. In this example, the label base of the label block allocated by Router 1 is 262161. Since Router 1’s site ID is 1, Router 1 associates the assigned label block with block offset of 1. The following are the messages sent from Router 1 to Router 3 as displayed using the `monitor traffic interface interface-name` command.
```
user@Router1> monitor traffic interface ge-5/3/2
Jun 14 12:26:31.280818 BGP SEND 10.10.10.1+179 -> 10.10.10.3+53950
Jun 14 12:26:31.280824 BGP SEND message type 2 (Update) length 88
Jun 14 12:26:31.280828 BGP SEND flags 0x40 code Origin(1): IGP
Jun 14 12:26:31.280833 BGP SEND flags 0x40 code ASPath(2) length 0: <null>
Jun 14 12:26:31.280837 BGP SEND flags 0x40 code LocalPref(5): 100
Jun 14 12:26:31.280844 BGP SEND flags 0xc0 code Extended Communities(16): 2:8717:100 800a:19:0:0
Jun 14 12:26:31.280848 BGP SEND flags 0x90 code MP_reach(14): AFI/SAFI 25/65
Jun 14 12:26:31.280853 BGP SEND nhop 10.10.10.1 len 4
Jun 14 12:26:31.280862 BGP SEND 8717:1000:1:1 (label base : 262161 range : 8, ce id: 1, offset: 1)
Jun 14 12:26:31.405067 BGP RECV 10.10.10.3+53950 -> 10.10.10.1+179
Jun 14 12:26:31.405074 BGP RECV message type 2 (Update) length 88
Jun 14 12:26:31.405082 BGP RECV flags 0x40 code Origin(1): IGP
Jun 14 12:26:31.405086 BGP RECV flags 0x40 code ASPath(2) length 0: <null>
Jun 14 12:26:31.405093 BGP RECV flags 0x40 code LocalPref(5): 100
Jun 14 12:26:31.405098 BGP RECV flags 0xc0 code Extended Communities(16): 2:8717:100 800a:19:0:0
Jun 14 12:26:31.405103 BGP RECV nhop 10.10.10.3 len 4
```
2. As shown in the figure and the configuration, Site B is attached to Router 3. Site B is assigned a site ID of 2. Before Router 3 can announce its membership to VPLS edut using a BGP update message, Router 3 assigns a default label block with the label base of 262153. The block offset for this label block is 1 because its own site ID of 2 fits in the block being advertised. The following are the messages sent from Router 3 to Router 1 as displayed using the `monitor traffic interface interface-name` command.
```
user@Router3> monitor traffic interface ge-2/0/1
Jun 14 12:26:31.282008 BGP SEND 10.10.10.3+53950 -> 10.10.10.1+179
Jun 14 12:26:31.282018 BGP SEND message type 2 (Update) length 88
Jun 14 12:26:31.282026 BGP SEND flags 0x40 code Origin(1): IGP
Jun 14 12:26:31.282034 BGP SEND flags 0x40 code ASPath(2) length 0: <null>
Jun 14 12:26:31.282041 BGP SEND flags 0x40 code LocalPref(5): 100
Jun 14 12:26:31.282052 BGP SEND flags 0xc0 code Extended Communities(16): 2:8717:100 800a:19:0:0
```
3. Verify the connection status messages for Router 1 using the `show vpls connections` command. Notice the base label is 262161, the incoming label from Router 3 is 262162, and the outgoing label to Router 3 is 262153.
```bash
user@Router1> show vpls connections instance edut extensive
Instance: edut
Local site: router-1 (1)
Number of local interfaces: 1
Number of local interfaces up: 1
IRB interface present: no
ge-5/0/2.0 lsi.1049600
Intf - vpls edut local site 1 remote site 2
Label-base Offset Range Preference
262161 1 8 100
connection-site Type St Time last up # Up
trans 2 rmt Up Jun 14 12:26:31 2009 1
Remote PE: 10.10.10.3, Negotiated control-word: No
Incoming label: 262162, Outgoing label: 262153
Local interface: lsi.1049600, Status: Up, Encapsulation: VPLS
Description: Intf - vpls edut local site 1 remote site 2
Connection History:
Jun 14 12:26:31 2009 status update timer
Jun 14 12:26:31 2009 loc intf up
Jun 14 12:26:31 2009 PE route changed
Jun 14 12:26:31 2009 Out lbl Update 262153
Jun 14 12:26:31 2009 In lbl Update 262162
Jun 14 12:26:31 2009 loc intf down
Layer-2 VPN connections:
Legend for connection status (St)
EI -- encapsulation invalid
CCC/TCC/VPLS
EM -- encapsulation mismatch
VC-Dn -- Virtual circuit down
WE -- interface and instance encaps not same
NC -- interface encapsulation not
NP -- interface hardware not present
```
CM -- control-word mismatch <- only outbound connection is up
CN -- circuit not provisioned --> only inbound connection is up
OR -- out of range Up -- operational
OL -- no outgoing label Dn -- down
LD -- local site signaled down CF -- call admission control failure
RD -- remote site signaled down SC -- local and remote site ID collision
LN -- local site not designated LM -- local site ID not minimum designated
RN -- remote site not designated RM -- remote site ID not minimum designated
XX -- unknown connection status IL -- no incoming label
MM -- MTU mismatch MI -- Mesh-Group ID not available
BK -- Backup connection ST -- Standby connection
PF -- Profile parse failure PB -- Profile busy
Legend for interface status
Up -- operational
Dn -- down
4. Verify the connection status messages for Router 3 using the `show vpls connections` command. Notice the base label is 262153, the incoming label from Router 1 is 262153, and the outgoing label to Router 1 is 262162.
user@Router3> show vpls connections instance edut extensive
Instance: edut
Local site: router-3 (2)
Number of local interfaces: 1
Number of local interfaces up: 1
IRB interface present: no
ge-4/0/2.0
lsi.1050368 1 Intf - vpls edut local site 2 remote site 1
Label-base Offset Range Preference
262153 1 8 100
connection-site Type St Time last up # Up
trans rmt Up Jun 14 12:26:31 2009 1
1 rmt Up Jun 14 12:26:31 2009
Remote PE: 10.10.10.1, Negotiated control-word: No
Incoming label: 262153, Outgoing label: 262162
Local interface: lsi.1050368, Status: Up, Encapsulation: VPLS
Description: Intf - vpls edut local site 2 remote site 1
Connection History:
Jun 14 12:26:31 2009 status update timer
Jun 14 12:26:31 2009 loc intf up lsi.1050368
Jun 14 12:26:31 2009 PE route changed
Jun 14 12:26:31 2009 Out lbl Update 262162
Jun 14 12:26:31 2009 In lbl Update 262153
Jun 14 12:26:31 2009 loc intf down
Layer-2 VPN connections:
Legend for connection status (St)
EI -- encapsulation invalid NC -- interface encapsulation not
CCC/TCC/VPLS same
EM -- encapsulation mismatch WE -- interface and instance encap not
same
VC-Dn -- Virtual circuit down NP -- interface hardware not present
CM -- control-word mismatch -< -- only outbound connection is up
CN -- circuit not provisioned >- -- only inbound connection is up
OR -- out of range Up -- operational
OL -- no outgoing label Dn -- down
LD -- local site signaled down CF -- call admission control failure
RD -- remote site signaled down SC -- local and remote site ID collision
LN -- local site not designated LM -- local site ID not minimum designated
RN -- remote site not designated RM -- remote site ID not minimum designated
XX -- unknown connection status IL -- no incoming label
MM -- MTU mismatch MI -- Mesh-Group ID not available
BK -- Backup connection ST -- Standby connection
PF -- Profile parse failure PB -- Profile busy
Legend for interface status
Up -- operational
Dn -- down
Example: Building a VPLS From Router 1 to Router 3
|
{"Source-Url": "https://kb.juniper.net/library/CUSTOMERSERVICE/technotes/Understanding_VPLS_Label_Blocks_Operation.pdf", "len_cl100k_base": 9727, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 42135, "total-output-tokens": 11193, "length": "2e13", "weborganizer": {"__label__adult": 0.0003371238708496094, "__label__art_design": 0.00030803680419921875, "__label__crime_law": 0.00047135353088378906, "__label__education_jobs": 0.0006685256958007812, "__label__entertainment": 0.00014781951904296875, "__label__fashion_beauty": 0.00015175342559814453, "__label__finance_business": 0.002750396728515625, "__label__food_dining": 0.00018608570098876953, "__label__games": 0.0015764236450195312, "__label__hardware": 0.00792694091796875, "__label__health": 0.00018715858459472656, "__label__history": 0.00021314620971679688, "__label__home_hobbies": 0.00020885467529296875, "__label__industrial": 0.0008726119995117188, "__label__literature": 0.00015461444854736328, "__label__politics": 0.0001595020294189453, "__label__religion": 0.0002694129943847656, "__label__science_tech": 0.0288848876953125, "__label__social_life": 7.790327072143555e-05, "__label__software": 0.41552734375, "__label__software_dev": 0.53759765625, "__label__sports_fitness": 0.0003819465637207031, "__label__transportation": 0.0005946159362792969, "__label__travel": 0.00021255016326904297}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39890, 0.07058]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39890, 0.06122]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39890, 0.81759]], "google_gemma-3-12b-it_contains_pii": [[0, 42, false], [42, 3185, null], [3185, 9960, null], [9960, 15506, null], [15506, 16620, null], [16620, 16620, null], [16620, 17419, null], [17419, 17419, null], [17419, 19894, null], [19894, 22805, null], [22805, 24772, null], [24772, 26574, null], [26574, 28035, null], [28035, 31028, null], [31028, 32195, null], [32195, 35242, null], [35242, 36676, null], [36676, 39077, null], [39077, 39890, null], [39890, 39890, null]], "google_gemma-3-12b-it_is_public_document": [[0, 42, true], [42, 3185, null], [3185, 9960, null], [9960, 15506, null], [15506, 16620, null], [16620, 16620, null], [16620, 17419, null], [17419, 17419, null], [17419, 19894, null], [19894, 22805, null], [22805, 24772, null], [24772, 26574, null], [26574, 28035, null], [28035, 31028, null], [31028, 32195, null], [32195, 35242, null], [35242, 36676, null], [36676, 39077, null], [39077, 39890, null], [39890, 39890, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39890, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39890, null]], "pdf_page_numbers": [[0, 42, 1], [42, 3185, 2], [3185, 9960, 3], [9960, 15506, 4], [15506, 16620, 5], [16620, 16620, 6], [16620, 17419, 7], [17419, 17419, 8], [17419, 19894, 9], [19894, 22805, 10], [22805, 24772, 11], [24772, 26574, 12], [26574, 28035, 13], [28035, 31028, 14], [31028, 32195, 15], [32195, 35242, 16], [35242, 36676, 17], [36676, 39077, 18], [39077, 39890, 19], [39890, 39890, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39890, 0.05629]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
b2c22cede9ebbd59416613653f5795969f9ab44c
|
Risk of Using Pirated Software and its Impact on Software Protection Strategies
Samuel Kwan
Samuel.Kwan@ust.hk
Jeevan Jaisingh
jeevan@ust.hk
Kar Yan Tam
kytam@ust.hk
Follow this and additional works at: http://aisel.aisnet.org/pacis2006
Recommended Citation
http://aisel.aisnet.org/pacis2006/35
This material is brought to you by the Pacific Asia Conference on Information Systems (PACIS) at AIS Electronic Library (AISeL). It has been accepted for inclusion in PACIS 2006 Proceedings by an authorized administrator of AIS Electronic Library (AISeL). For more information, please contact elibrary@aisnet.org.
Risk of Using Pirated Software and its Impact on Software Protection Strategies
Samuel Kwan
Department of Information and Systems Management
Hong Kong University of Science and Technology
Samuel.Kwan@ust.hk
Jeevan Jaisingh
Department of Information and Systems Management
Hong Kong University of Science and Technology
jeevan@ust.hk
Kar Yan Tam
Department of Information and Systems Management
Hong Kong University of Science and Technology
ktyam@ust.hk
Abstract
The software protection strategy of software developer and the inherent risk to end user in using pirated software are two major factors that affect a user’s decision on whether to purchase or pirate a software product. This paper analyzes the optimal protection strategy for software developer in horizontally and vertically differentiated markets. We find that the implementation cost of software protection constitutes the primary factor for software developers to determine their software protection strategies. However, in a vertically differentiated market, the lower quality product should always adopt a non-protection strategy, regardless of the protection implementation cost. In other cases, protection would only be optimal if the protection implementation cost to the software developer is relatively small. These findings are consistent with anecdotal evidence.
Keywords: Software piracy, software protection strategy, horizontal differentiation, vertical differentiation
1. Introduction
According to a global report by Business Software Alliance (2003), the software industry is said to have lost more than $13.08 billion in business during the year 2002 due to software piracy. It remains to be one of the most well known and persistent problems of the IT industry. It is estimated that an average of 39% of all software installed in 2002 were pirated versions (Business Software Alliance 2003). In fact, the situation is deteriorating with the rapid and pervasive application of IT in the modern society.
At the first glance, one may perceive software piracy as just another example of the illegal duplication of other intellectual properties like books, journals, or media contents. However, there are at least two factors that make software piracy a unique type of problem in itself. Firstly, software developers are able to implement protection codes or mechanisms that can effectively and significantly increase the difficulty to pirate. Such measures are usually not available to publishers and producers. The protection of software products can range from the use of hardware “dongles” to just requiring the user to enter a cryptic product key code. Although one may argue that these schemes are usually not unbreakable, they increase the cost for pirates to use illegal copies of software. Of course, the software developer would also need to pay a certain implementation cost for this type of software protection mechanisms. Secondly, there are inherent risks in using pirated software. These risks are unique to the software industry and make software piracy quite different from other...
forms of illegal duplication of intellectual properties. For instance, due to the unlawful nature of piracy, the quality of pirated software can never be guaranteed. Very often the pirated software would have already been infected with malicious computer virus before it arrives at the hands of the end user.
Also, software is seldom free of defects. Some defects not only result in malfunctioning of the software but also leave “vulnerabilities” for malicious computer hackers to exploit. Very often these defects would only be discovered after the consumer has purchased and used the software for a certain period of time. It is a common practice for software developers to provide post-sale technical support to the legitimate users should there be any subsequent problems. While these types of technical support may exist in a variety of forms, ranging from security patches, features updates, to email or even telephone support, they are usually available only to the paying consumers but not to the pirates. Users of pirated software are at their own risk. It is reasonable to assume that some people would be deterred from pirating in view of this risk.
Cheng et al (1997) attempted to exhaustively enlist the reasons behind people’s software purchasing or pirating decisions in an empirical study. In particular, they found “technical support in case of problems” as well as “worry about computer viruses” to be among the ten most important reasons for people to purchase, rather than pirate software.
In the Internet age, the risk of using vulnerable software cannot be overemphasized. The US-CERT Vulnerability Notes Database (US-CERT 2004) lists many popular software products that contain critical security vulnerabilities. For example, the various “buffer overrun” vulnerabilities that exist in the popular Oracle 9i product would require software updates available only to registered users. In principle, users of pirated copies of Oracle 9i would have to bear the risk of future attacks exploiting these vulnerabilities, especially if their systems are connected to the Internet. The risk in using pirated software became quite apparent in the recent “Blaster” attack. “Blaster” was an Internet virus that exploited a known vulnerability of the Windows XP software. A timely patch to this vulnerability was actually released by the vendor but was made available only to registered customers. As a result, machines running pirated copies of Windows XP were forced to disconnect from the Internet to prevent from getting exposed to the virus attack.
To summarize, both the software protection mechanism and the risk in using pirated software serve to reduce piracy. The former is mainly a preventive measure that is available to the software developer who needs to weigh the cost and benefit before deciding on what type of protection mechanism, if any, should be adopted. The latter can be considered a deterrent means that is beyond the control of any single party. The effect of risk may depend on a number of factors such as the chance of virus infection through the use of pirated software, the ultimate reliability of the software product3, etc. In this paper, we attempt to study the optimal protection strategies for software firms in a duopoly software market, with the explicit consideration of the potential risk in using pirated software due to the lack of technical support. We develop an analytic model that assumes that people can overcome the software protection by bearing a cost of pirating. Users are heterogeneous in the cost of pirating. We will also model the risk in using pirated software in our framework.
We consider a duopoly market under two forms of product differentiation: horizontal and vertical (Tirole 1988). By horizontal differentiation, we mean that software firms compete with each other by designing features that are unique from its competitor. On the
---
3 In this study, we assume that software developers would not intentionally reduce the reliability of their software products for the purpose of deterring piracy.
other hand, in a vertically differentiated market, firms compete in the quality of their products. Our main objective is to analyze the optimal protection strategies for software firms under each situation. The rest of the paper is organized as follows: To begin with, we will examine the relevant prior research in the area of software piracy first. We will then develop an analytical model conforming to our observations mentioned above. In particular, we will analyze the problem using two well known market competition paradigms, namely the horizontally differentiated market and the vertically differentiated one.
2. Background Literature
Intuitively thinking, the existence of piracy should reduce demand and thus profit. It follows that the best strategy for software firms would be to increase the protection level as much as possible so that potential pirates would simply find it very costly to pirate. However, Conner & Rumelt (1991) argue that by taking into account the effect of network externalities, as commonly found in software products, a high level of protection may not be optimal for firms. They show that in a monopoly setting, raising software protection would be profit-maximizing only when there is only insignificant effect of network externalities. Otherwise, profit would decrease with an increased protection level because some would-be pirates are forced to do without the software, rather than buying it. However, the model used does not consider strategic interactions in a competitive market as well as the inherent risk in using pirated software.
The work by Shy & Thisse (1999) further develops the analysis of optimal software protection strategy by the use of a horizontally differentiated duopoly model. Their findings are similar to those by Conner & Rumelt in that when externalities effects are strong, non-protection would be optimal for competing software firms. Their model assumes dichotomization in two dimensions. Firstly, consumers are dichotomized into support-oriented or support-independent ones. Support-oriented users choose to buy rather than pirate if the price of software is less than the utility they derive from the support service. Secondly, rather than treating the level of protection level as a continuous variable, firm’s protection strategies are dichotomized into either full protection or nil protection. This conforms to the reality in that software products usually come only with a simple protection mechanism that checks for a valid product key, or are just completely unprotected.
However, their model also assumes that end users would have no way to use pirated software if software protection is in place. Unfortunately this is often not true in real life. In fact, end users can usually obtain pirated software with protection mechanism already compromised. Also, most of the time software is only protected by a product key code that can be easily duplicated. Therefore, we believe that it should be more realistic to assume that people can still pirate even though a software product is protected, only that they would need to pay a cost of pirating. The cost for pirating can differ by individual but in general should be small compared with the price of software.
The dichotomization of support-oriented and support-independent consumers does not fully represent the inherent risk in using pirated software as discussed previously. In Shy & Thisse’s model, technical support only brings a fixed amount of utility to support-oriented users. However, we believe the lack of technical support would introduce a risk that essentially discounts, in the sense of expected utility, the benefits derivable from using the pirated software.
The concept of risk in using pirated software was first used by Banerjee (2003) in his analysis of the software piracy problem from the perspective of social welfare and government policy. In his model, end user simply cannot be certain that a piece of software
obtained from illegal sources would indeed work as expected. However, his focus was mainly on governmental monitoring of counterfeiting business.
We believe that the concept of risk is not only applicable to cases when end user purchase software from pirates, but also to cases when end users make illegal copies of licensed software themselves. In fact, as pointed out earlier, the study by Cheng et al (1997) reveals that there are other risks in using pirated software, such as the lack of technical support in case of problems and computer viruses. In the following, market competition, dichotomization of software protection level, as well as the risk in using pirated software will be incorporated into our analytical model.
3. Horizontal Differentiation
We start with the horizontally differentiated market setting. Namely, we consider the case when competing software firms aim at the same application area (e.g. symbolic computation, graphics design, web authoring, etc.) but produce software with features differentiated from each other. Moreover, each consumer would value each of these differentiated features differently.
For example, consider the desktop operating systems provided by Apple Computer and that by Microsoft. Both operating systems are designed to provide an easy-to-use graphical user interface for end users to manage their personal computers. However, some of the features they provide are unique from each other and these differentiated features are valued differently by different camps of consumers.
For simplicity, we model the market as a duopoly and represent the heterogeneity in consumers' preferences for the two different software products using the “linear city” model (Hotelling 1929). In the real software market, very often there would be an innovator firm at the beginning, followed by a number of other software developers who believe it would be profitable to sell similar products in the same application area. However, due to fierce market competition among software developers, usually only a few major players might remain when the market becomes stable. Such a phenomenon of market consolidation can be found in many application areas such as productivity tools, graphics packages, etc. We thus believe that our duopoly model represents an acceptable approximation of reality. We denote the two competing products software 1 ($sw_1$) and software 2 ($sw_2$) respectively.
3.1. The Firms
Before the software is actually developed, the firm would decide on whether to implement any protection mechanism against unauthorized copying. As discussed earlier, a dichotomization of protection strategy should be more appropriate than a continuous level of protection because software products nowadays are usually shipped with protection by simple checking of product key code, or without any protection at all. We denote their decisions on protection strategies by $\eta_i \in \{0, 1\}$ ($i = 1, 2$) where $\eta_i = 0$ means firm $i$ has chosen not to implement protection. However, if a firm chooses to implement protection ($\eta_i = 1$), an implementation cost $k$ would be incurred.
Once the firms decide on their protection strategies, they also need to decide the selling price of their software $p_i$ ($i = 1, 2$). It is assumed that firms would act rationally and
choose their respective optimal prices to maximize their own profits. Assuming a zero marginal cost of production for simplicity, the profit of a firm is given by:
$$\pi_i = p_i d_i - k \eta_i$$ \hspace{1cm} \text{.. (1)}
where $d_i$ denotes the demand of the software in concern. In order to determine the optimal price, a firm needs to anticipate the possible reactions of both its competitor and the potential consumers, as detailed in the following.
3.2. The Consumers
We will assume full participation by consumers in that all consumers either buy or pirate one of the software. There are two main factors, namely benefit and cost, affecting the utility a consumer may derive from using a piece of software:
Benefit The benefit of software would depend on the intrinsic quality of it as well as how its features match the preferences of the user. A piece of software that is highly regarded by one user may not appear to be that useful to another. In our model for horizontally differentiated market, the intrinsic software quality is assumed to be the same for both firms and is denoted by $q$. On the other hand, consumers are ranked by their preferences of $\text{sw}_1$ to $\text{sw}_2$, with their relative preference positions denoted by $x \in [0,1]$. Namely, a consumer with a smaller $x$ would prefer $\text{sw}_1$ more to $\text{sw}_2$. Considering the deterioration in benefit due to preference mismatch, we model the benefit of $\text{sw}_1$ to a consumer at position $x$ by $q - tx$ where $t$ denotes the benefit degradation factor (i.e. the “transportation cost”) due to preference mismatch. Similarly, the benefit of $\text{sw}_2$ would be $q - t(1 - x)$ to the same consumer.
Cost The cost would simply be the selling price of the software in case a consumer purchases it. Prices are denoted by $p_1$ and $p_2$ for $\text{sw}_1$ and $\text{sw}_2$ respectively. In the case of pirating protected software, a cost for pirating would also be incurred. It is assumed that this cost would depend on individual’s characteristics (e.g. technical know-how, available resources for pirating, etc.) but would be more or less similar across different target software to be pirated. As such, the consumer’s cost for pirating is modeled to be heterogeneous among consumers but the same for both $\text{sw}_1$ and $\text{sw}_2$. For simplicity, we define the cost for pirating as $\tau z$ where $\tau$ is the homogeneous scaling factor of piracy costs while $z \in [0,1]$ denotes the consumer’s heterogeneity in pirating protected software. Essentially, some consumers pay a higher cost than others to pirate a piece of protected software.
As a result, the utility $U_{b1}$ and $U_{b2}$ derived from purchasing $\text{sw}_1$ and $\text{sw}_2$ would be:
$$U_{b1} = q - tx - p_1$$ \hspace{1cm} \text{.. (2)}
$$U_{b2} = q - t(1 - x) - p_2$$ \hspace{1cm} \text{.. (3)}
As mentioned before, users of pirated software are all subject to risk. We may express this risk factor by the expected benefit of using a pirated software copy. Assuming a risk factor of $\phi \in (0,1)$, the utility $U_{p1}$ and $U_{p2}$ for pirating $sw_1$ and $sw_2$ would respectively be:
\[
U_{p1} = (1 - \phi)(q - tx) - tz\eta_1
\]
\[
U_{p2} = (1 - \phi)(q - t(1 - x)) - tz\eta_2
\]
Namely, $1 - \phi$ is the probability that the pirated software would work perfectly.
### 3.3. The Market
Having introduced the essential characteristics of software firms and consumers, we are about to incorporate the two in a competitive market. Namely, we consider a competitive market in a three-stage non-cooperative game. In stage 1, software firms set their respective protection strategies $(\eta_1, \eta_2)$. In stage 2, firms determine their optimal prices $(p_1, p_2)$ with the expectation that their profits would be maximized. Lastly in stage 3, consumers choose whether to buy or pirate either one of the software so as to maximize their utilities. The game, in its extensive form, can be illustrated in Figure 1.
We will study the problem using the Sub-game Perfect Nash Equilibrium (SPNE) concept. That is, both firms would first anticipate the utility-maximizing decisions of consumers that would happen at stage 3. Based on this anticipation and also considering the profit-maximizing behavior of its competitor, a firm determines its profit-maximizing price under the 4 possible protection strategies, namely $(\eta_1 = 1, \eta_2 = 1)$, $(\eta_1 = 1, \eta_2 = 0)$, $(\eta_1 = 0, \eta_2 = 1)$ and $(\eta_1 = 0, \eta_2 = 0)$. Lastly, by comparing the maximized profits at each different protection strategy, the two firms set their optimal protection strategies at stage 1 based on the Nash Equilibrium concept. Before proceeding with the analysis, the utility function of the consumer is restated as follows:
\[
U = \begin{cases}
q - tx - p_1 & \text{if buy } sw_1 \\
(1 - \phi)(q - tx) - tz\eta_1 & \text{if pirate } sw_1 \\
q - t(1 - x) - p_2 & \text{if buy } sw_2 \\
(1 - \phi)(q - t(1 - x)) - tz\eta_2 & \text{if pirate } sw_2
\end{cases}
\]
while the profit functions of the two firms are given by:
\[
\pi_1 = p_1d_1 - k\eta_1 \\
\pi_2 = p_2d_2 - k\eta_2
\]
Figure 1: Game Tree
One may easily note from (6) and (7) the dynamics of such a market. Firstly, by setting protection level and price, a firm is affecting the decisions of consumers on whether to buy or pirate $sw_1$ or $sw_2$. Such decisions would in turn affect the demands for $sw_1$ and $sw_2$. Finally, the profits of firms are actually determined by the demands for their software, as can be seen from (7). To continue our analysis, we will first study the demands for $sw_1$ and $sw_2$ that result from the utility-maximizing behavior of consumers.
3.4. Demand and Profit at Equilibrium
We will consider the demand of $sw_1$ first. To start with, let us focus on the effect of $x$ on the consumer’s utility and leave the effect of $z$ alone for the time being. Figure 2 shows the utility functions for purchasing and for pirating $sw_1$ at each fixed value of $z$. Firstly, all utility functions of the consumer are linear in $x$. For $sw_1$, the utilities of the two choices (i.e. buying or pirating) would simply be represented by the two downward-sloping straight lines $U_b$ and $U_p$. In particular, the slope for buying is $-t$ whereas that for pirating is $-(1-\phi)t$. As $\phi$ must be within the interval $(0,1)$, $U_b$ would always be steeper than $U_p$.
From Figure 2, it can be easily seen that consumers in the range $(0,x_{blp1})$ would prefer buying to pirating $sw_1$ while those in the range $(x_{blp1},1)$ would prefer pirating to buying.
We can now consider the effect of $z$ on the demand. It can be seen from (6) that different values of $z$ would result in different intercepts of the pirating utility, as shown in Figure 3.
Note that the intersection point $x_{blp1}$ would also be changing with $z$. Considering $z$, the indifference point $x_{blp1}$ becomes a line of indifference between buying and pirating $sw_1$.
The consumer’s utility functions $U_{bl}$ and $U_{pl}$ become 2-dimensional planes in the 3-dimensional space of $(U, x, z)$. The demand for $sw_t$ is simply the projection, on the $(x, z)$ plane, of the region where the plane $U_{bl}$ is the highest. Essentially this area is outlined by the indifference line $x_{b1,p1}$ with respect to $z$ within the interval $z \in [0,1]$.
More generally, we can derive the utility-maximizing demands for software from the appropriate lines of indifference, as will be shown later. It should be noted that $U_{bl}$ and $U_{pl}$ may not necessarily intersect within the interval of $x = (0,1)$. This could happen when the vertical intercept of $U_{pl}$ is larger than that of $U_{bl}$, and in this case pirating would always undercut buying. We would not further analyze this case because the firm will doubtlessly need to lower its price or abandon the market as no consumer is buying the product. On the other hand, $U_{bl}$ and $U_{pl}$ would also not intersect when the value of $U_{pl}$ is smaller than that of $U_{bl}$ when $x = 1$. In this case, buying would always undercut pirating. Again, we would not further analyze this case because there is actually no issue of piracy under such a situation.
We may now consider the situation when $sw_2$ is also put in the picture. Considering the 2-dimensional space of $(U, x)$, the utility functions $U_{b2}$ and $U_{p2}$ would simply be two lines having slopes $t$ and $(1-\phi)t$ respectively, as shown in Figure 4.
We are only interested in the situation when there are non-zero portions of users buying and pirating \(sw_1\) or \(sw_2\). This is equivalent to the following assumption that posits the relations among the intersecting points:
\[ \forall \ z \in [0,1] \quad 1>x_{b2p2} > x_{p1p2} > x_{b1p1} > 0 \]
\[ \ldots \text{(C1)} \]
Now we can consider the 3-dimensional space of \((U,x,z)\). As explained previously, the demands for \(sw_1\) and \(sw_2\) can be derived from the indifference lines \(x_{b1p1}\) and \(x_{b2p2}\). In other words, the demands would simply be the projections on the \((x,z)\) plane as shown in Figure 5. Based on the utility functions of the consumer as given by (6), the demands for \(sw_1\) and \(sw_2\) are:
\[
d_1 = \int_0^1 x_{b1p1} dz = \frac{1}{2} \frac{\tau \eta_1 - 2 p_1 + 2q \phi}{t \phi} \quad \ldots \text{(8)}
\]
\[
d_2 = 1 - \int_0^1 x_{b2p2} dz = 1 + \frac{1}{2} \frac{\tau \eta_2 - 2 p_2 + 2q \phi - 2t \phi}{t \phi} \quad \ldots \text{(9)}
\]
Since firms need to determine optimal prices to maximize their profits, their problems would be:
Proposition 1: In a horizontally differentiated software market, protection would be optimal for both firms only if \( k < k^* = \frac{\tau(\tau + 4q\phi)}{16t\phi} \). Otherwise, non-protection would be optimal for both firms.
Note that \( k^* \) is increasing in \( \tau \), the pirating cost. Protection would be optimal only if the protection cost is below \( k^* \) which mainly consists of a square term of the pirating cost \( \tau \) of the consumer. This suggests that firms should prefer only a very simple and low-cost protection mechanism or no protection at all.
As shown in the Appendix, the optimal prices, demands and profits of both firms should be symmetrical if they adopt the same protection strategy. In case of protection, the optimal price, demand and profit should be \( p_1^* = p_2^* = \frac{\tau + 2q\phi}{4} \), \( d_1^* = d_2^* = \frac{\tau + 2q\phi}{4t\phi} \) and
\[
\pi_1^* = \pi_2^* = \frac{\tau^2 + 4\tau q\phi + 4q^2\phi^2 - 16kt\phi}{16t\phi}
\]
respectively. In case of non-protection, the optimal price, demand and profit would be \( p_1^* = p_2^* = \frac{q\phi}{2t} \), \( d_1^* = d_2^* = \frac{q}{2t} \) and \( \pi_1^* = \pi_2^* = \frac{q^2\phi}{4t} \) respectively.
It follows that the optimal profit is increasing in \( q \) but decreasing in \( t \), regardless of whether protection is in place or not. Namely, optimal profit increases when software is of higher quality but decreases when the negative effect of preference mismatch (i.e. the transportation cost) is high. Also, when protection is in place, the optimal profit is also increasing in \( \tau \), the pirating cost on the consumer side. These very much conform to intuition.
Comparing the optimal prices and demands for protection and non-protection, it can be seen that the optimal prices and demands for non-protection would always be lower than those for protection. In this sense, the protection cost contributes as the major determining factor for firms to adopt protection. On the other hand, the effects of risk (i.e. \( \phi \)) on the optimal price, demand as well as profit are summarized in the following table of comparative statics:
---
\( k^* \) is increasing in \( \tau \).
Both Protect
<table>
<thead>
<tr>
<th></th>
<th>( \frac{\partial p_1^*}{\partial \phi} )</th>
<th>( \frac{\partial p_2^*}{\partial \phi} )</th>
<th>( \frac{\partial d_1^*}{\partial \phi} )</th>
<th>( \frac{\partial d_2^*}{\partial \phi} )</th>
<th>( \frac{\partial \pi_1^*}{\partial \phi} )</th>
<th>( \frac{\partial \pi_2^*}{\partial \phi} )</th>
</tr>
</thead>
<tbody>
<tr>
<td>+</td>
<td>+</td>
<td>−</td>
<td>−</td>
<td>+</td>
<td>+</td>
<td></td>
</tr>
</tbody>
</table>
Both Not Protect
<table>
<thead>
<tr>
<th></th>
<th>( \frac{\partial p_1^*}{\partial \phi} )</th>
<th>( \frac{\partial p_2^*}{\partial \phi} )</th>
<th>( \frac{\partial d_1^*}{\partial \phi} )</th>
<th>( \frac{\partial d_2^*}{\partial \phi} )</th>
<th>( \frac{\partial \pi_1^*}{\partial \phi} )</th>
<th>( \frac{\partial \pi_2^*}{\partial \phi} )</th>
</tr>
</thead>
<tbody>
<tr>
<td>+</td>
<td>+</td>
<td>0</td>
<td>0</td>
<td>+</td>
<td>+</td>
<td></td>
</tr>
</tbody>
</table>
\( + : \) positive if \( \tau < 2q\phi \)
In general, optimal prices and profits should increase with risk\(^5\). It is also interesting to note that the optimal demands would decrease with risk in case of protection. The intuition behind is that if the software is protected and the risk becomes higher, the firm can charge a higher price and reap a higher profit, although there are actually less buying consumers.
4. Vertical Differentiation
Having considered the case of horizontally differentiated market, we now consider the case when software products are vertically differentiated. By vertical differentiation, we mean that software products compete in quality. In general, the higher quality firm can sell at a higher price and also the preference for quality is assumed to be different across different consumers.
Vertical differentiation is indeed quite common in the software industry. Many popular software magazines and download sites (e.g. PC Magazine, Bytes, download.com, zdnet.com, etc.) offer ratings of software products in terms of a common set of criteria such as ease-of-use, functionalities, etc. to assist consumers in making their purchasing decisions.
The main difference from the analysis of horizontal differentiation would be in the formulation of the consumer’s utility functions. Namely, we denote the intrinsic qualities of \( sw_1 \) and \( sw_2 \) by \( q_1 \) and \( q_2 \) respectively. Consumers are now ranked by their preferences to the quality of software, denoted by \( \theta \in (0,1) \), instead of by their preferences of product features (i.e. \( x \)). A consumer with a larger \( \theta \) would derive more utility from the quality of \( sw_1 \) and \( sw_2 \). As such, the benefits of \( sw_1 \) and \( sw_2 \) to a consumer \( \theta \) would be \( q_1\theta \) and \( q_2\theta \) respectively. Without loss of generosity, we assume \( q_1 > q_2 \). Therefore, the utility functions of the consumer are modified as follows:
\[
U = \begin{cases}
q_1\theta - p_1 & \text{if buy } sw_1 \\
(1-\phi)q_1\theta - \tau z_1 & \text{if pirate } sw_1 \\
q_2\theta - p_2 & \text{if buy } sw_2 \\
(1-\phi)q_2\theta - \tau z_2 & \text{if pirate } sw_2
\end{cases}
\tag{12}
\]
where the definitions of \( p_1, p_2, \tau, z, \eta_1, \eta_2 \) remain the same as in horizontal differentiation.
---
\(^5\) The condition \( \tau < 2q\phi \) is likely to be valid because the pirating cost should be significantly lower than the benefit of the software to make a case of software piracy.
Consider the consumer’s utility when pirating either $sw_1$ or $sw_2$. From (12), it follows that the slope of consumer’s utility with respect to $\theta$ when pirating $sw_1$ would always be steeper than that of pirating $sw_2$. It can be easily seen that when $(\eta_1, \eta_2)$ is either $(1,1)$, $(0,1)$ or $(0,0)$, pirating $sw_1$ would always dominate pirating $sw_2$. When $(\eta_1, \eta_2) = (1,0)$, pirating $sw_2$ may dominate pirating $sw_1$ for some consumers. Denote the point of indifference between pirating $sw_1$ and $sw_2$ as $\theta_{p1p2}$, it can be seen that no one would pirate $sw_2$ unless $\theta_{p1p2} > 0$.
Now consider the consumer’s utility when buying either software. From (12), it is clear that the slope of consumer’s utility with respect to $\theta$ when buying $sw_1$ would always be steeper than that of buying $sw_2$. We assume that the point of indifference between buying $sw_1$ and buying $sw_2$, denoted by $\theta_{bb2}$, lies somewhere between 0 and 1 (i.e. $0 < \theta_{bb2} < 1$). (Without this assumption, buying either software would always dominate buying the other.)
Consider the consumer’s utility with respect to $\theta$ as shown in Figure 6. Namely, there will be 4 groups of consumers. Those with $\theta \in [\theta_{bb2}, 1]$ would buy $sw_1$ and those with $\theta \in [\theta_{p2b2}, \theta_{bb2}]$ would buy $sw_2$. Moreover, those with $\theta \in [\theta_{p1p2}, \theta_{p1b2}]$ would choose to pirate $sw_1$ while those with $\theta \in [0, \theta_{p1p2}]$ (if $(\eta_1, \eta_2) = (1,0)$ and $\theta_{p1p2} > 0$) would choose to pirate $sw_2$. However, we assume that even though $sw_2$ is unprotected, it can only convert a certain portion of consumers from pirating $sw_1$ to pirating $sw_2$, mainly because the pirating cost should be relatively small. More formally, we assume the relations among the intersecting points to satisfy the following:
$$1 > \theta_{bb2} > \theta_{p2b2} > \theta_{p2b2} \quad \forall \ z \in [0,1]$$
\[ \text{..... (C2)} \]
Intuitively, it implies that the price of $sw_1$ is higher than that of $sw_2$ and both prices are higher than the pirating cost. Also, the risk of using pirated software is more significant than the quality difference between the products (i.e. $q_2 > (1-\phi)q_1$ such that $U_{b_2}$ is always steeper than $U_{b_2}$).
Similar to our analysis on the horizontal differentiation case, the demands are given by the corresponding projections of the utility planes onto the $(y, z)$ plane, as illustrated by the shaded areas in Figure 7. Namely, the demands for $sw_1$ and $sw_2$ are given by:
$$d_1 = 1 - \int_0^1 \theta_{b_1} dz = 1 - \frac{p_1 - p_2}{q_1 - q_2} \quad \ldots \quad (13)$$
$$d_2 = \int_0^1 \theta_{b_2} dz - \int_0^1 \theta_{b_2}^{\prime} dz = \frac{p_1 - p_2}{q_1 - q_2} + \frac{1}{2} \frac{\tau \eta_1 - 2 p_2}{q_1 (\phi - 1) + q_2} \quad \ldots \quad (14)$$
That is, the utility-maximizing demands would be entirely in terms of the other exogenous model parameters $q_1, q_2, \phi, \tau$ and $k$ as well as the endogenous $p_1, p_2, \eta_1$ and $\eta_2$. Since firms need to determine optimal prices to maximize their profits, their problems would be:
$$\max_{p_1} \pi_1 = \max_{p_1} p_1 d_1 - k \eta_1 = \max_{p_1} \left( 1 - \frac{p_1 - p_2}{q_1 - q_2} \right) p_1 - k \eta_1 \quad \ldots \quad (15)$$
$$\max_{p_2} \pi_2 = \max_{p_2} p_2 d_2 - k \eta_2 = \max_{p_2} \left( \frac{p_1 - p_2}{q_1 - q_2} + \frac{1}{2} \frac{\tau \eta_1 - 2 p_2}{q_1 (\phi - 1) + q_2} \right) p_2 - k \eta_2 \quad \ldots \quad (16)$$
Proposition 2\(^{\ast}\): In a vertically differentiated software market, non-protection would always be optimal to the lower-quality firm. Protection would be optimal for the higher-quality firm only if $k < k^* = \frac{\tau (8q_1^2 + q_1 \tau - 8q_1q_2\phi - \tau q_2)}{4(q_1 + 3q_1\phi - q_2)^2}$.
It is apparent that $k^*$ is always increasing in $\tau$, the pirating cost. Protection would be optimal only if the protection cost is below $k^*$ which mainly consists of a square term of the pirating cost $\tau$ of the consumer. This once again suggests that firms should prefer only a very simple and low-cost protection mechanism or no protection at all.
As shown in the Appendix, the optimal prices, demands as well as profits, if non-protection strategy is adopted by both firms, would be:
$$p_1^* = \frac{2q_1\phi (q_1 - q_2)}{q_1 + 3q_1\phi - q_2} \quad d_1^* = \frac{2q_1\phi}{q_1 + 3q_1\phi - q_2} \quad \pi_1^* = \frac{4q_1^2\phi^2 (q_1 - q_2)}{(q_1 + 3q_1\phi - q_2)^2}$$
$$p_2^* = \frac{(q_1\phi - q_1 + q_2)(q_1 - q_2)}{q_1 + 3q_1\phi - q_2} \quad d_2^* = \frac{q_1\phi}{q_1 + 3q_1\phi - q_2} \quad \pi_2^* = \frac{q_1\phi(q_1\phi - q_1 + q_2)(q_1 - q_2)}{(q_1 + 3q_1\phi - q_2)^2}$$
\(^{\ast}\) Proof of Proposition 2 is straightforward and withheld due to length limitation. Interested readers may obtain it from the authors directly.
In particular, the higher-quality firm would charge a higher price and the optimal profit of the higher-quality firm is increasing in \( q_1 \) just like the case of horizontal differentiation. The optimal profit of the lower-quality firm is also increasing in \( \phi \). In case the higher-quality firm chooses to protect, the optimal prices, demands as well as profits of the two firms would become:
\[
p_1^* = \frac{(4q_1\phi + \tau)(q_1 - q_2)}{2(q_1 + 3q_1\phi - q_2)} \quad \quad d_1^* = \frac{1}{2} \left( \frac{4q_1\phi + \tau}{q_1 + 3q_1\phi - q_2} \right)
\]
\[
\pi_1^* = \frac{1}{(q_1 + 3q_1\phi - q_2)^2} (16q_1\phi^2 + 8q_1\phi + q_1\tau^2 - 16q_1q_3\phi^2 - 8q_1q_3\phi\tau - q_1\tau^2 - 4q_1q_2^2 - 24q_1q_2\phi + 8q_1q_2 - 36q_1q_2\phi + 24q_1q_2\phi - 4q_2^2)
\]
\[
p_2^* = \frac{(q_1\phi - q_1 + q_2 + \tau)(q_1 - q_2)}{q_1 + 3q_1\phi - q_2} \quad \quad d_2^* = \frac{1}{q_1 + 3q_1\phi - q_2} (q_1\phi + q_1 + q_2)(q_1 + 3q_1\phi - q_2)
\]
\[
\pi_2^* = \frac{q_1\phi(q_1\phi - q_1 + \tau + q_2)^2(q_1 - q_2)}{(q_1\phi - q_1 + q_2)(q_1 + 3q_1\phi - q_2)^2}
\]
Similar to the case of horizontal differentiation, it can be shown that the optimal prices and demands for non-protection would always be lower than those if the higher quality firm chooses to protect. Again, the protection cost should be the major determining factor for the higher quality firm to choose protection. The effects of risk on the optimal price, demand as well as profit can be seen from the following table of comparative statics:
<table>
<thead>
<tr>
<th></th>
<th>( \frac{\partial p_1^*}{\partial \phi} )</th>
<th>( \frac{\partial p_2^*}{\partial \phi} )</th>
<th>( \frac{\partial d_1^*}{\partial \phi} )</th>
<th>( \frac{\partial d_2^*}{\partial \phi} )</th>
<th>( \frac{\partial \pi_1^*}{\partial \phi} )</th>
<th>( \frac{\partial \pi_2^*}{\partial \phi} )</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Only Firm 1 Protect</strong></td>
<td>+"</td>
<td>+"</td>
<td>+"</td>
<td>-"</td>
<td>+"</td>
<td>+"</td>
</tr>
<tr>
<td><strong>Both Not Protect</strong></td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
<td>+</td>
</tr>
</tbody>
</table>
\(+\): positive if \( \tau < \frac{4(q_1 - q_2)}{3} \) \(-\): negative if \( \tau > \frac{4(q_1 - q_2)}{3} \)
Namely, optimal prices, demands and profits would all increase with risk if both firms choose the non-protection strategy. In case the higher quality firm chooses to protect, the optimal prices and profits would still increase with risk\(^7\) but the optimal demand for the lower quality product would decrease. Intuitively, a higher risk would lead to a higher demand for the higher quality product but that would essentially reduce the demand of the lower quality product, although it would still result in an increased profit for the lower quality firm due to the increased price.
5. **Discussion**
We have considered the optimal protection strategies under two different types of market differentiations. Our analysis shows that in a vertically differentiated market the lower-quality firm would always prefer non-protection. Furthermore, protection would be
---
\(^7\) We mainly consider the case when \( \tau < \frac{4}{3}(q_1 - q_3) \) because the pirating cost should be significantly lower than the benefits of software in order for people to consider pirating.
profit-maximizing only if the implementation cost is low. In reality, we observe that most software developers are still implementing some sort of protection mechanisms in their software products although strong externalities effects are quite universal in the widely-expanded software business nowadays. Apparently this seems to be inconsistent with the findings from previous researches (Conner & Rumelt 1991; Shy & Thisse 1999). It is also interesting to note that complicated protection mechanisms are seldom found nowadays. Most software products just employ a simple product key code validation or registration process to guard against unauthorized usage. The duplicated uses of those product key codes are seldom really checked, nor would they prevent the actual usage of the software. The software protection mechanisms used nowadays are observed to be converging to a very simple and common form of product key code validation. It is reasonable to expect that this sort of mechanisms would not be very costly to implement and is likely to be reusable on other software products developed by the same firm, further lowering the average implementation cost of protection.
Anecdotal evidence supports some of our findings. For instance, Maplesoft’s Maple and Wolfram’s Mathematica can be regarded as two horizontally differentiated products competing in the area of symbolic computation software. They are two incompatible products with different sets of features and employ different file formats although their problem domains are similar. Both of them adopt a simple product key code validation mechanism for protection. It is interesting to find that apart from protection strategy, their listed prices are also very similar. These facts are consistent with our analytical findings.
On the other hand, the Microsoft Office suite and Sun Microsystems’ StarOffice package can be regarded as examples of vertically differentiated products. As Microsoft Office has become a de facto standard in the office productivity area, competitors in this application area have to develop products that are compatible with it. Unfortunately, Microsoft Office has been adopting a proprietary file format that prevents others from producing compatible products. StarOffice actually originated from an open-source initiative that attempted to reverse-engineer the proprietary file formats used by Microsoft Office that was believed to be over-priced. As a result, StarOffice is able to read and produce documents and spreadsheets in Microsoft Office format. However, it never achieves full compatibility with Microsoft Office and users may perceive it as a lower-quality product in this sense. Interestingly, Microsoft Office is adopting a protection scheme while StarOffice is not. Again, this is consistent with our analytical findings.
6. Conclusion and Future Work
Our findings show that the primary consideration of software protection strategies should be the implementation cost. This may help explain why complicated protection mechanisms have mostly been driven out of the software market nowadays. Also, the software developer of the lower-quality product would tend to adopt non-protection in order to compete with the higher-quality product in a vertically differentiated market. We have also considered the effects of risk in using pirated software. In either horizontally differentiated or vertically differentiated markets, a firm’s profit is found to be increasing with the risk of using pirated software. More interestingly, one may find that risk has a similar positive effect on profit as product quality.
As mentioned in the beginning of this paper, the existence of risk in itself does not prevent the use of pirated software. However, consumers are deterred from doing so in view
---
8 If protection is chosen, this is subject to some technical constraints regarding the pirating cost $\tau$.
---
of the uncertainty introduced by the risk. Gopal & Sanders (1997) showed that deterrent measures would be more profit-maximizing than preventive ones for dealing with software piracy. Our findings about the effect of risk also support this argument. We attribute one of the sources of the risk in using pirated software to the unavailability of technical support. However, it should be noted that in this study we do not assume risk to be a parameter controllable by firm. In real life, the risk in using pirated software is subject to many other factors beyond the control of the software firm. We believe that firms can actually affect at least two factors: the reliability of software product and the quality of technical support. Ironically, the value of technical support increases when the reliability of software decreases. It would be interesting to see how these two factors (i.e. reliability and technical support quality) would interact and affect the firm’s optimal strategy. We believe that future extension of this study can be developed along this line.
Our analysis does not consider the effect of externalities. Intuitively, firms should merely have less incentive to protect their software if there are strong externalities effects. However, empirical observation shows that most software products are still implementing protection mechanisms, albeit only simple and low-cost ones. In this study, we mainly focus on the effects of protection costs and risk in a competitive market. It would actually be straightforward to extend our model to include externalities effects as well. This could be another possible extension of this work.
7. References
|
{"Source-Url": "http://aisel.aisnet.org/cgi/viewcontent.cgi?article=1009&context=pacis2006", "len_cl100k_base": 11159, "olmocr-version": "0.1.49", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 45683, "total-output-tokens": 12574, "length": "2e13", "weborganizer": {"__label__adult": 0.0006132125854492188, "__label__art_design": 0.0007233619689941406, "__label__crime_law": 0.00487518310546875, "__label__education_jobs": 0.00234222412109375, "__label__entertainment": 0.00031185150146484375, "__label__fashion_beauty": 0.00020420551300048828, "__label__finance_business": 0.00954437255859375, "__label__food_dining": 0.0005831718444824219, "__label__games": 0.00414276123046875, "__label__hardware": 0.0009784698486328125, "__label__health": 0.0007457733154296875, "__label__history": 0.0003025531768798828, "__label__home_hobbies": 0.0001424551010131836, "__label__industrial": 0.00042557716369628906, "__label__literature": 0.0007867813110351562, "__label__politics": 0.0008540153503417969, "__label__religion": 0.00036978721618652344, "__label__science_tech": 0.03363037109375, "__label__social_life": 0.0001665353775024414, "__label__software": 0.136474609375, "__label__software_dev": 0.80078125, "__label__sports_fitness": 0.00024890899658203125, "__label__transportation": 0.0004477500915527344, "__label__travel": 0.00027179718017578125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46038, 0.03256]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46038, 0.52075]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46038, 0.92082]], "google_gemma-3-12b-it_contains_pii": [[0, 783, false], [783, 3888, null], [3888, 7967, null], [7967, 11946, null], [11946, 15272, null], [15272, 18156, null], [18156, 20438, null], [20438, 22296, null], [22296, 23805, null], [23805, 24891, null], [24891, 27095, null], [27095, 30333, null], [30333, 32357, null], [32357, 35255, null], [35255, 38945, null], [38945, 42865, null], [42865, 46038, null]], "google_gemma-3-12b-it_is_public_document": [[0, 783, true], [783, 3888, null], [3888, 7967, null], [7967, 11946, null], [11946, 15272, null], [15272, 18156, null], [18156, 20438, null], [20438, 22296, null], [22296, 23805, null], [23805, 24891, null], [24891, 27095, null], [27095, 30333, null], [30333, 32357, null], [32357, 35255, null], [35255, 38945, null], [38945, 42865, null], [42865, 46038, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46038, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46038, null]], "pdf_page_numbers": [[0, 783, 1], [783, 3888, 2], [3888, 7967, 3], [7967, 11946, 4], [11946, 15272, 5], [15272, 18156, 6], [18156, 20438, 7], [20438, 22296, 8], [22296, 23805, 9], [23805, 24891, 10], [24891, 27095, 11], [27095, 30333, 12], [30333, 32357, 13], [32357, 35255, 14], [35255, 38945, 15], [38945, 42865, 16], [42865, 46038, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46038, 0.04717]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
15a4e9c5923a403e20c9cb458bfe74b7dd97fd44
|
PowerLyra: Differentiated Graph Computation and Partitioning on Skewed Graphs
Rong Chen, Jiaxin Shi, Yanzhe Chen, Haibo Chen
Shanghai Key Laboratory of Scalable Computing and Systems
Institute of Parallel and Distributed Systems, Shanghai Jiao Tong University
{rongchen, jiaxinshi, yanzhechen, haibochen}@sjtu.edu.cn
Abstract
Natural graphs with skewed distribution raise unique challenges to graph computation and partitioning. Existing graph-parallel systems usually use a “one size fits all” design that uniformly processes all vertices, which either suffer from notable load imbalance and high contention for high-degree vertices (e.g., Pregel and GraphLab), or incur high communication cost and memory consumption even for low-degree vertices (e.g., PowerGraph and GraphX).
In this paper, we argue that skewed distribution in natural graphs also calls for differentiated processing on high-degree and low-degree vertices. We then introduce PowerLyra, a new graph computation engine that embraces the best of both worlds of existing graph-parallel systems, by dynamically applying different computation and partitioning strategies for different vertices. PowerLyra further provides an efficient hybrid graph partitioning algorithm (hybrid-cut) that combines edge-cut and vertex-cut with heuristics. Based on PowerLyra, we design locality-conscious data layout optimization to improve cache locality of graph accesses during communication. PowerLyra is implemented as a separate computation engine of PowerGraph, and can seamlessly support various graph algorithms. A detailed evaluation on two clusters using graph-analytics and MLDM (machine learning and data mining) applications show that PowerLyra outperforms PowerGraph by up to 5.53X (from 1.24X) and 3.26X (from 1.49X) for real-world and synthetic graphs accordingly, and is much faster than other systems like GraphX and Giraph, yet with much less memory consumption. A porting of hybrid-cut to GraphX further confirms the efficiency and generality of PowerLyra.
1. Introduction
Graph-structured computation has become increasingly popular, which is evidenced by its emerging adoption in a wide range of areas including social computation, web search, natural language processing and recommendation systems [9, 19, 38, 48, 58, 62]. The strong desire for efficient and expressive programming models for graph-structured computation has recently driven the development of a number of graph-parallel systems such as Pregel [35], GraphLab [33] and PowerGraph [18]. They usually follow the “think as a vertex” philosophy [35] by coding graph computation as vertex-centric programs to process vertices in parallel and communicate across edges.
On the other hand, the distribution of graphs in the real world tends to be diversified and continue evolving [31]. For example, some existing datasets exhibit a skewed power-law distribution [17] where a small number of vertices have a significant number of neighboring vertices, while some other existing datasets (e.g., SNAP [39]) exhibit a more balanced distribution. The diverse properties inside and among graph datasets raise new challenges to efficiently partition and process such graphs [6, 18, 32].
Unfortunately, existing graph-parallel systems usually adopt a “one size fits all” design where different vertices are equally processed, leading to suboptimal performance and scalability. For example, Pregel [35] and GraphLab [33] centralize their design in making resources locally accessible to hide latency by evenly distributing vertices to machines, which may result in imbalanced computation and communication for vertices with high degrees (i.e., the number of neighboring vertices). In contrast, PowerGraph [18] and GraphX [20] focus on evenly parallelizing the computation by partitioning edges among machines, which incurs high communication cost among partitioned vertices even with low degrees.
Further, prior graph partitioning algorithms may result in some deficiencies for skewed and non-skewed (i.e. regular) graphs. For example, edge-cut [26, 44, 49, 52], which divides a graph by cutting cross-partition edges among subgraphs with the goal of evenly distributing vertices, usu-
ally results in replication of edges as well as imbalanced messages with high contention. In contrast, vertex-cut [12, 18, 24], which partitions vertices among sub-graphs with the goal of evenly distributing edges, incurs high communication overhead among partitioned vertices and excessive memory consumption.
In this paper, we make a comprehensive analysis of existing graph-parallel systems over skewed graphs and argue that the diverse properties of different graphs and skewed vertex distribution demand differentiated computation and partitioning on low-degree and high-degree vertices. Based on our analysis, we introduce PowerLyra, a new graph-parallel system that embraces the best of both worlds of existing systems. The key idea of PowerLyra is to adaptively processing different vertices according to their degrees.
PowerLyra follows the GAS (Gather, Apply and Scatter) model [18] and can seamlessly support existing graph algorithms under such a model. Internally, PowerLyra distinguishes the processing of low-degree and high-degree vertices: it uses centralized computation for low-degree vertices to avoid frequent communication and only distributes the computation for high-degree vertices.
To efficiently partition a skewed graph, PowerLyra is built with a balanced $p$-way hybrid-cut algorithm to partition different types of vertices for a skewed graph. The hybrid-cut algorithm evenly distributes low-degree vertices along with their edges among machines (like edge-cut), and evenly distributes edges of high-degree vertices among machines (like vertex-cut). We further provide a greedy heuristic to improve partitioning of low-degree vertices accordingly, and consumes much less memory, due to significantly reduced replication, less communication cost, and better locality in computation and communication. A porting of the hybrid-cut to GraphX further confirms the efficiency and generality of PowerLyra.
This paper makes the following contributions:
- A comprehensive analysis that uncovers some performance issues of existing graph-parallel systems (§2).
- The PowerLyra model that supports differentiated computation on low-degree and high-degree vertices, as well as adaptive communication with minimal messages while not sacrificing generality (§3)
- A hybrid-cut algorithm with heuristics that provides more efficient partitioning and computation (§4), as well as locality-conscious data layout optimization (§5).
- A detailed evaluation that demonstrates the performance benefit of PowerLyra (§6).
<table>
<thead>
<tr>
<th>Graph Placement</th>
<th>Pregel-like [2, 3, 35, 43]</th>
<th>GraphLab [33]</th>
<th>PowerGraph [18]</th>
<th>GraphX [20]</th>
<th>PowerLyra</th>
</tr>
</thead>
<tbody>
<tr>
<td>Comm. Cost</td>
<td>$\leq \text{#edge-cuts}$</td>
<td>$\leq 2 \times \text{#mirrors}$</td>
<td>$\leq 5 \times \text{#mirrors}$</td>
<td>$\leq 4 \times \text{#mirrors}$</td>
<td>L: local</td>
</tr>
<tr>
<td>Dynamic Comp.</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
<tr>
<td>Load Balance</td>
<td>no</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
<td>yes</td>
</tr>
</tbody>
</table>
Table 1. A summary of various distributed graph-parallel systems. ‘L’ and ‘H’ represent low-degree and high-degree vertex respectively.
Many graph-parallel systems, including PowerLyra, abstract computation as vertex-centric program $P$, which is executed in parallel on each vertex $v \in V$ in a sparse graph $G = (V, E)$. The scope of computation and communication in each $P(v)$ is restricted to neighboring vertices $n$ through edges where $(v, n) \in E$.
This section briefly introduces skewed graphs and illustrates why prior graph-parallel systems fall short using Pregel, GraphLab, PowerGraph and GraphX, as they are representatives of existing systems.
2. Background and Motivation
2.1 Skewed Graphs
Natural graphs, such as social networks (follower, citation, and co-authorship), email and instant messaging graphs, or web graphs (hubs and authorities), usually exhibit skewed distribution, such as power-law degree distribution [17]. This implies that a major fraction of vertices have relatively few neighbors (i.e., low-degree vertex), while a small fraction of vertices has a significant large number of neighbors (i.e., high-degree vertex). Given a positive power-law constant $\alpha$, the probability that the vertex has degree $d$ under power-law distribution is
$$P(d) \propto d^{-\alpha}$$
The source code and a brief instruction of PowerLyra are available at http://ipads.se.sjtu.edu.cn/projects/powerlyra.html
implemented in GraphLab is similar to that of Pregel, except that it uses replicas to exchange messages from neighboring vertices.
**PowerGraph** abstracts computation into the GAS (Gather, Apply and Scatter) model and uses vertex-cut to split a vertex into multiple replicas in different machines to parallelize the computation for a single vertex. Fig. 1(b) uses the Gather and the Acc functions to accumulate the rank of neighboring vertices along in-edges, the Apply function to calculate and update a new rank to vertex and the Scatter function to send messages and activate neighboring vertices along out-edges. Five messages for each replica are used to parallelize vertex computation to multiple machines in each iteration (i.e., 2 for Gather, 1 for Apply and 2 for Scatter), three of them are used to support dynamic computation. As shown in Fig. 2, the edges of a single vertex are assigned to multiple machines to evenly distribute workloads, and the replicas of vertex are placed in machines with its edges.
**GraphX** [20] extends the general dataflow framework in Spark [60], by recasting graph-specific operations into analytics pipelines formed by basic dataflow operators such as Join, Map and Group-by. GraphX also adopts vertex replication, incremental view maintenance and vertex-cut partitioning to support dynamic computation and balance the workload for skewed graphs.
### 2.2 Existing Systems on Skewed Graphs
Though a skewed graph has different types of vertices, existing graph systems usually use a “one size fits all” design and compute equally on all vertices, which may result in suboptimal performance. Tab. 1 provides a comparative study of typical graph-parallel systems.
**Pregel** and its open-source relatives [2, 3, 43] use the BSP (Bulk Synchronous Parallel) model [53] with explicit messages to fetch all resources for the vertex computation. Fig. 1(a) illustrates an example implementation of PageRank [9] in Pregel. The Compute function sums up the ranks of neighboring vertices through the received messages M, and sets it as the new rank of the current vertex. The new rank will also be sent to its neighboring vertices by messages until a global convergence estimated by a distributed aggregator is reached. As shown in Fig. 2, Pregel adopts random (hash-based) edge-cut evenly assigning two vertices in the sample graph to two machines, and provides interaction between vertices by message passing along edges. Since the communication is restricted to push-mode algorithms (e.g., vertex A cannot actively pull data from vertex B), Pregel does not support dynamic computation [33].
**GraphLab** replicates vertices for all edges spanning machines and leverages an additional vertex activation message to support dynamic computation. In Fig. 2, GraphLab also uses edge-cut as Pregel, but creates replicas (i.e., mirrors) and duplicates edges in both machines (e.g., for the edge from vertex A to B, there are one edge and replica in both machines). The communication between replicas of a vertex is bidirectional, i.e., sending updates from a master to its mirrors and activation from mirrors to the master. PageRank implemented in GraphLab is similar to that of Pregel, except
---
**Figure 1.** The sample code of PageRank on various systems.
The lower exponent α implies that a graph has higher density and more high-degree vertices. For example, the in and out degree distribution of the Twitter follower graph is close to 1.7 and 2.0 [18]. Though there are also other models [31, 41, 42, 55] for skewed graphs, we restrict the discussion to power-law distribution due to space constraints. However, PowerLyra is not bound to such a distribution and should benefit other models with skewed distribution as well. (having high-degree and low-degree vertices).
### 2.2.1 Issues with Graph Computation
To exploit locality during computation, both Pregel and GraphLab use edge-cut to accumulate all resources (i.e., messages or replicas) of a vertex in a single machine. However, a skewed distribution of degrees among vertices implies skewed workload, which leads to substantial imbalance when being accumulated on a single machine. Even if the number of high-degree vertices is much more than the number of machines to balance workload [23], it still incurs heavy network traffic among machines to accumulate all resources for high-degree vertices. Further, high-degree vertices would be the center of contention when performing scatter operations on all edges in a single machine. As shown in Fig. 3, there is significant load imbalance for edge-cut in Pregel and GraphLab, as well as high contention on vertex 1 (high-degree) when its neighboring vertices activate it in parallel. This situation will be even worse with the increase of machines and degrees of vertices.
PowerGraph and GraphX address the load imbalance issue using vertex-cut and decomposition under the GAS.
model, which split a vertex into multiple machines. However, this splitting also comes at a cost, including more computation, communication and synchronization required to gather values and scatter the new value from/to its replicas (Fig. 2). However, as the major number of vertices are only with small degrees in a skewed graph, splitting such vertices is not worthwhile. Further, while the GAS model provides a general abstraction, many algorithms only gather or scatter in one direction (e.g., PageRank). Yet, both PowerGraph and GraphX still require redundant communication and data movement. The workload is always distributed to all replicas even without such edges. Under the Random vertex-cut in Fig. 3, the computation on vertex 4 still needs to follow the GAS model, even though all in-edges are located together with the master of vertex 4.
### 2.2.2 Issues with Graph Partitioning
Graph partitioning plays a vital role in reducing communication and ensuring load balance. Traditional balanced $p$-way edge-cut \([44, 49, 52]\), evenly assigns vertices of a graph to $p$ machines to minimize the number of edges spanning machines. Under edge-cut in Fig. 3, six vertices are randomly (i.e., hash modulo $\#$machine) assigned to three machines. Edge-cut creates replicated vertices (e.g., mirrors) and edges to form a locally consistent graph state in each machine. However, natural graphs with skewed distribution are difficult to partition using edge-cut \([6, 30]\), since skewed vertices will cause a burst of communication cost and work imbalance. Vertex 1 in Fig. 3 contributes about half of replicas of vertices and edges, and incurs load imbalance on machine 1, which has close to half of edges.
The balanced $p$-way vertex-cut \([18]\) evenly assigns edges to $p$ machines to minimize the number of vertices spanning machines. Compared to edge-cut, vertex-cut avoids replication of edges and achieves load balance by allowing edges of a single vertex to be split over multiple machines. However, randomly constructed vertex-cut leads to much higher replication factor ($\lambda$) (i.e., the average number of replicas for a vertex), since it incurs poor placement of low-degree vertices. In Fig. 3, Random vertex-cut creates a mirror for vertex 3 even if it has only two edges.\(^2\)
To reduce replication factor, PowerGraph uses a greedy heuristic \([18]\) to accumulate adjacent edges on the same machine. In practice, applying the greedy heuristic to all edges (i.e., Coordinated) incurs a significant penalty during graph partitioning \([23]\), mainly caused by exchanging vertex information among machines. Yet, using greedy heuristic independently on each machine (i.e., Oblivious) will notably increase the replication factor.
The constrained vertex-cut \([24]\) (e.g., Grid) is proposed to strike a balance between ingress and execution time. It follows the classic 2D partitioning \([11, 59]\) to restrict the locations of edges within a small subset of machines to approximate an optimal partitioning. Since the set of machines for each edge can be independently calculated on each machine by hashing, constrained vertex-cut can significantly reduce the ingress time.\(^3\) However, the ideal upper bound of replication factor is still too large for a good placement of low-degree vertices (e.g., $2\sqrt{N} - 1$ for Grid). Further, constrained vertex-cut necessitates the number of partitions ($N$) close to be a square number to get a reasonably balanced graph partitioning.
Some work (e.g., \([23]\)) argues that intelligent graph placement schemes may dominate and hurt the total execution time, whereas such argument just partially works for greedy heuristic partitioning and simple graph algorithms. First,\(^4\)
<table>
<thead>
<tr>
<th>Algorithm & Graph</th>
<th>Vertex-cut</th>
<th>$\lambda$</th>
<th>Time (Sec)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>Ingress</td>
</tr>
<tr>
<td>PageRank & Twitter follower</td>
<td>Random</td>
<td>16.0</td>
<td>263</td>
</tr>
<tr>
<td></td>
<td>Coordinated</td>
<td>5.5</td>
<td>391</td>
</tr>
<tr>
<td></td>
<td>Oblivious</td>
<td>12.8</td>
<td>289</td>
</tr>
<tr>
<td></td>
<td>Grid</td>
<td>8.3</td>
<td>123</td>
</tr>
<tr>
<td></td>
<td>Hybrid</td>
<td>5.6</td>
<td>138</td>
</tr>
<tr>
<td>ALS ($d=20$) & Netflix follower</td>
<td>Random</td>
<td>36.9</td>
<td>21</td>
</tr>
<tr>
<td></td>
<td>Coordinated</td>
<td>5.3</td>
<td>31</td>
</tr>
<tr>
<td></td>
<td>Oblivious</td>
<td>31.5</td>
<td>25</td>
</tr>
<tr>
<td></td>
<td>Grid</td>
<td>12.3</td>
<td>12</td>
</tr>
<tr>
<td></td>
<td>Hybrid</td>
<td>2.6</td>
<td>14</td>
</tr>
</tbody>
</table>
Table 2. A comparison of various vertex-cuts for 48 partitions using PageRank (10 iterations) on the Twitter follower graph and ALS ($d=20$, the magnitude of latent dimension) on the Netflix movie recommendation graph. $\lambda$ means replication factor. Ingress means loading graph into memory and building local graph structures.
\(^2\)PowerGraph mandates the creation of a flying master of vertex (e.g., vertex 5 and 6) in its hash-based location to support simple external querying for some algorithms even without edges. PowerLyra also follows this rule.
\(^3\)Coordinated greedy vertex-cut has been deprecated due to its excessive graph ingress time and buggy, meanwhile both PowerGraph and GraphX have adopted Grid-like vertex-cut as the preferential partitioning algorithm.
\(^4\)GraphLab has been highly optimized in the 2.2 release, especially for ingress time with parallel loading.
naive random partitioning does not necessarily imply efficiency in ingress time due to a lengthy time to create an excessive number of mirrors. Second, with the increasing sophistication of graph algorithms (e.g., MLDM), the ingress time will become relatively small to the overall computation.
Tab. 2 illustrates a comparison of various state-of-the-art vertex-cuts of PowerGraph for 48 partitions. Random vertex-cut performs worst in both ingress and computation time due to the highest replication factor. Coordinated vertex-cut achieves both small replication factor and execution time, but at the cost of excessive ingress time. Oblivious vertex-cut decreases ingress time (but still slower than Random) while doubling replication factor and execution time. Grid vertex-cut outperforms coordinated vertex-cuts in ingress time by 2.8X but decreasing runtime performance. Besides, the percent of ingress time for PageRank on the Twitter follower graph with 10 iterations\(^5\) of graph computation ranges from 24.2\% to 56.8\%, while for ALS on Netflix motive recommendation graph only ranges from 3.6\% to 22.8\%. The random Hybrid-cut of PowerLyra (see §4) provides optimal performance by significantly decreasing execution time while only slightly increasing ingress time (compared to Grid).
3. Graph Computation in PowerLyra
This section describes the graph computation model in PowerLyra, which combines the best from prior systems by differentiating the processing on low-degree and high-degree vertices. Without loss of generality, the rest of this paper will use in-degree of the vertex to introduce the design of PowerLyra’s hybrid computation model.
3.1 Abstraction and Engine
Like others, a vertex-program \(P\) in PowerLyra runs on a directed graph \(G = (V, E)\) and computes in parallel on each vertex \(v \in V\). Users can associate arbitrary vertex data \(D_v\), where \(v \in V\), and edge data \(D_{e, t}\) where \((s, t) \in E\). Computation on vertex \(v\) can gather and scatter data from/to neighboring vertex \(n\) where \((v, n) \in E\). During graph partitioning (§4), PowerLyra replicates vertices to construct a local graph on each machine, all of which are called replicas. Like PowerGraph, PowerLyra also elects a replica randomly (using vertex’s hash) as master and other replicas as mirrors. PowerLyra still strictly conforms to the GAS model, and hence can seamlessly run all existing applications in PowerGraph.
PowerLyra employs a simple loop to express iterative computation of graph algorithms. The graph engine sequentially executes the Gather, Apply and Scatter phases in each iteration, but processes vertices differently according to the vertex degrees.
3.2 Differentiated Vertex Computation
Processing high-degree vertex: To exploit parallelism of vertex computation, PowerLyra follows the GAS model in PowerGraph to process high-degree vertices. In the Gather phase, two messages are sent by the master vertex (herein master for short) to activate all mirrors to run the gather function locally and accumulate results back to the master. In the Apply phase, the master runs the apply function and then sends the updated vertex data to all its mirrors. Finally, all mirrors execute the scatter function to activate their neighbors, and the master will similarly receive notification from activated mirrors. Unlike PowerGraph, PowerLyra groups the two messages from master to mirrors in the Apply and Scatter phases (the left part of Fig. 4), to reduce message exchanges.
Processing low-degree vertex: To preserve access locality of vertex computation, PowerLyra introduces a new GraphLab-like computation model to process low-degree vertices. However, PowerLyra does not provide bidirectional (i.e., both in and out) access locality like GraphLab, which necessitates edge replicas and doubles messages. We observe that most graph algorithms only gather or scatter in only one direction. For example, PageRank only gathers data along in-edges and scatters data along out-edges. PowerLyra leverages this observation to provide unidirectional access locality by placing vertices along with edges in only one direction (which has already been indicated by application code). As the update message from master to mirrors is inevitable after computation (in the Apply phase), PowerLyra adopts local gathering and distributed scattering to minimize the communication overhead.
As shown in the right part of Fig. 4, since all edges required by gathering has been placed locally, both the Gather and Apply phases can be done locally by the master without help of its mirrors. The message to activate mirrors (that further scatter their neighbors along out-edges) are combined with the message for updating vertex data (sent from master to mirrors).
Finally, the notifications from mirrors to master in the Scatter phase are not necessary anymore, since only the master will be activated along in-edges by its neighbors. Compared to GraphLab, PowerLyra requires no replication of edges, and only incurs up to one (update) message per mirror in each iteration for low-degree vertices. In addition, the unidirectional message from master to mirrors avoids potential contention on the receiving end of communication [14].
---
\(^5\) Increasing iterations, like [23, 35], will further reduce the percent.
PowerLyra classifies algorithms according to the direction of edges accessed in gathering and scattering, which are returned from the gather_edges and scatter_edges interfaces of PowerGraph accordingly. Hence, it can be checked at runtime without any changes to applications.
Table 3. A classification of various graph algorithms.
<table>
<thead>
<tr>
<th>Type</th>
<th>Gather</th>
<th>Scatter</th>
<th>Example Algo.</th>
</tr>
</thead>
<tbody>
<tr>
<td>Natural</td>
<td>in or none</td>
<td>out or none</td>
<td>PR, SSSP, DIA[25]</td>
</tr>
<tr>
<td>Other</td>
<td>any</td>
<td>any</td>
<td>CC, ALS[5]</td>
</tr>
</tbody>
</table>
3.3 Generalization
PowerLyra applies a simplified model for low-degree vertices to minimize communication overhead, but may limit its expressiveness to some graph algorithms that may require gathering or scattering data in both in and out directions.
PowerLyra introduces an adaptive way to handle different graph algorithms. Note that PowerLyra only needs to use such an approach for low-degree vertices, since communication on high-degree vertices is already bidirectional. PowerLyra classifies algorithms according to the directions of edges accessed in gathering and scattering, which are returned from the gather_edges and scatter_edges interfaces of PowerGraph accordingly. Hence, it can be checked at runtime without any changes to applications.
Tab. 3 summarizes the classification of graph algorithms. PowerLyra naturally supports the Natural algorithms that gather data along one direction (e.g., in/out_edges) or none and scatter data along another direction (e.g., out/in_edges) or none, such as PageRank (PR), Single-Source Shortest Paths (SSSP) and Approximate Diameter (DIA) [25]. For such algorithms, PowerLyra needs up to one message per mirror for low-degree vertices in each iteration.
For Other algorithms that gather and scatter data via any edges, PowerLyra asks mirrors to do gathering or scattering operations like those of high-degree vertices, but only on demand. For example, Connected Components (CC) gathers data via none edges and scatters data via all_edges, so that PowerLyra only requires one additional message in the Scatter phase to notify the master by the activated mirrors, and thus still avoids unnecessary communication in the Gather phase.
4. Distributed Graph Partitioning
This section describes a new hybrid vertex-cut algorithm that uses differentiated partitioning for low-degree and high-degree vertices. Based this, a new heuristic, called Ginger, is provided to further optimize partitioning for PowerLyra.
4.1 Balanced p-way Hybrid-Cut
Since vertex-cut evenly assigns edges to machines and only replicates vertices to construct a local graph within each machine, the memory and communication overhead highly depend on the replication factor ($\lambda$). Hence, existing vertex-cuts mostly aim at reducing the overall $\lambda$ of all vertices. However, we observe that the key is instead reducing $\lambda$ of low-degree vertices, since high-degree vertices inevitably need to be replicated on most of machines. Nevertheless, many current heuristics for vertex-cuts have a bias towards high-degree vertices, while paying little attention to low-degree vertices.
We propose a balanced $p$-way hybrid-cut that focuses on reducing $\lambda$ of low-degree vertices. It uses differentiated partitioning to low-degree and high-degree vertices. To avoid replication of edges, each edge is exclusively assigned to its target vertex (the destination of an edge)\textsuperscript{6}. For low-degree vertices, hybrid-cut adopts low-cut to evenly assign vertices along with in-edges to machines by hashing their target vertices. For high-degree vertices, hybrid-cut adopts high-cut to distribute all in-edges by hashing their source vertices. After that, hybrid-cut creates replicas and constructs local graphs, as done in typical vertex-cuts.
As shown in Figure 5, all vertices along with their in-edges are assigned as low-degree vertices except vertex 1, whose in-edges are assigned as high-degree vertex. For example, the edge (1, 4) and (3, 4) are placed in machine 1 with the master of low-degree vertex 4, while the edge (2, 1) and (5, 1) are placed in machine 2 with the mirror of high-degree vertex 1. The partition constructed by hybrid-cut only yields four mirrors and achieves good load balance.
Hybrid-cut addresses the major issues in edge-cut and vertex-cut on skewed graphs. First, hybrid-cut can provide much lower replication factor. For low-degree vertices, all in-edges are grouped with their target vertices, and there is no need to create mirrors for them. For high-degree vertices, the upper bound of increased mirrors due to assigning a new high-degree vertex along with in-edges is equal to the number of partitions (i.e., machines) rather than the degree of vertex; this completely avoids new mirrors of low-degree vertices. Second, hybrid-cut provides unidirectional access locality for low-degree vertices, which can used by hybrid computation model (§3) to reduce communication cost at runtime. Third, hybrid-cut is very efficient in graph ingress, since it is a hash-based partitioning for both low-degree and high-degree vertices. Finally, the partition constructed by hybrid-cut is naturally balanced on vertices and edges. Randomized placement of low-degree vertices leads to bal-
\textsuperscript{6} The edge could also exclusively belong to its source vertex, which depends on the direction of locality preferred by the graph algorithm.
ance of vertices, which is almost equivalent to the balance of edges for low-edge vertices. For high-degree vertices, all in-edges are evenly assigned since they are hosted by the owner machine of source vertices, which are also evenly assigned.
Constructing hybrid-cut: A general approach to constructing a hybrid-cut is adding an extra re-assignment phase for high-degree vertices to the original streaming graph partitioning. The left part of Fig. 6 illustrates the execution flow of graph ingestion using hybrid-cut, and the right part shows the sample graph in each stage. First, the worker on each machine loads the raw graph data from underlying distributed file systems in parallel, and dispatches a vertex and its in-edges according to the hash of a vertex. Each worker counts the in-degree of vertices and compares it with a user-defined threshold (θ) to identify high-degree vertices. After that, in-edges of high-degree vertex are re-assigned by hashing source vertices. Finally, each worker creates mirrors to construct a local graph as normal vertex-cut.
This approach is compatible with existing formats of raw graph data, but incurs a few communication overhead due to re-assigning in-edges of high-degree vertices. For some graph file format (e.g., adjacent list), the worker can directly identify high-degree vertices and distributes edges in loading stage to avoid extra communication, since the in-degree and a list of all source vertices are grouped in one line.
4.2 Heuristic Hybrid-Cut
To further reduce the replication factor of low-degree vertices, we propose a new heuristic algorithm, namely Ginger, inspired by Fennel [52], which is a greedy streaming edge-cut framework. Ginger places the next low-degree vertex along with in-edges on the machine that minimizes the expected replication factor.
Formally, given that the set of partitions for assigned low-degree vertices are \( P = (S_1, S_2, \ldots, S_p) \), a low-degree vertex \( v \) is assigned to partition \( S_i \) such that \( \delta g(v, S_i) \geq \delta g(v, S_j), \text{for all } j \in \{1, 2, \ldots, p\} \). We define the score for-
| Graph | \(|V|\) | \(|E|\) | \(\alpha\) | #Edges |
|----------|--------|--------|----------|--------|
| Twitter [28] | 42M | 1.47B | 1.8 | 673,275,560 |
| UK-2005 [8] | 40M | 936M | 1.9 | 249,459,718 |
| Wiki [22] | 5.7M | 130M | 2.0 | 105,156,471 |
| LJournal [16] | 5.4M | 79M | 2.1 | 53,824,704 |
| GoogleWeb [32] | 0.9M | 9.1M | 2.2 | 38,993,568 |
Table 4. A collection of real-world graphs and randomly constructed power-law graphs with varying \(\alpha\) and fixed 10 million vertices. Smaller \(\alpha\) produces denser graphs.
for the Power-law graphs. Though Coordinated vertex-cut provides comparable replication factor to Random hybrid-cut (10% higher), it triples the ingress time. Ginger can further reduce the replication factor by more than 20% (Fig. 7(a)), but also increases ingress time like Coordinated vertex-cut.
For real-world graphs (Fig. 8(a)), the improvement of Random hybrid-cut against Grid is smaller and sometimes slightly negative since the skewness of some graphs is moderate and randomized placement is not suitable for highly adjacent low-degree vertices. However, Ginger still performs much better in such cases, up to 3.11X improvement over Grid on UK. Fig. 8(b) compares the replication factor with an increasing number of machines on the Twitter follower graph. Random hybrid-cut provides comparable results to Coordinated vertex-cut with just 35% ingress time, and outperforms Grid and Oblivious vertex-cut by 1.74X and 2.67X respectively.
5. Locality-conscious Graph Layout
Graph computation usually exhibits poor data access locality [34], due to irregular traversal of neighboring vertices along edges as well as frequent message exchanges between masters and mirrors. The internal data structure of PowerLyra is organized to improve data access locality. Specifically, PowerLyra splits different (meta)data for both masters and mirrors to separate arrays and sequentially assigns a unified local ID in each machine to vertex for indexing, which is mapped to global vertex ID. As shown in the bottom of Fig. 9, in each phase, the worker thread sequentially traverses vertices and executes user-defined functions. The messages across machines are batched and sent periodically.
After the synchronization in each phase, all messages received from different machines will be updated to vertices in parallel and the order of accessing vertices is only determined by the order in the sender. However, since the order of messages is predefined by the traversal order, accesses to vertices have poor locality due to mismatching of orders between sender and receiver. Worse even, messages from multiple machines are processed in parallel and interfere with each other (shown in the upper part of Fig. 9). Though it appears that both problems could be partially addressed at runtime by sorting or dispatching messages on the fly [14], our experience shows that this will cause notable overhead instead of performance boost, due to non-trivial CPU cycles.
PowerLyra mitigates the above problems by extending hybrid-cut in four steps, as shown in Fig. 10. The left part shows the arrangement of masters and mirrors in each machine after each step, and the right part provides a thumbnail with some hints about the ordering. Before the relocation, all masters and mirrors of high-degree and low-degree vertices are mixed and stored in random order. For example, the order of update messages from masters in machine 0 (M0) mismatches the order of their mirrors stored in machine 1 (M1).
First, hybrid-cut divides vertex space into 4 zones to store (H)igh-degree masters (Z0), (L)ow-degree masters (Z1), (H)igh-degree mirrors (Z2) and (L)ow-degree mirrors (Z3) respectively. This is friendly to the message batching, since the processing on vertices in the same zone is similar. Further, it also helps to skip the unnecessary vertex traversal and avoid interference between the sender and the receiver. For example, in the Apply phase, only masters (Z0 and Z1) participate in the computation and only mirrors (Z2 and Z3) receive messages.
Second, the mirrors in Z2 and Z3 are further grouped according to the location of their masters, which could reduce the working set and the interference when multiple receiver threads update mirrors in parallel. For example, in M1, mirror 4 and 7 are grouped in L0 while mirror 9 and 3 are grouped in L2. The processing on messages from the master of low-degree vertices in M0 (L0) and M2 (L2) are restricted to different groups (L0 and L2) on M1.
Third, hybrid-cut sorts the masters and mirrors within a group according to the global vertex ID and sequentially assigns its local ID. Because the order of messages follows the order of local ID, sorting ensures masters and mirrors
hybrid-cut places mirrors in a
in Fig. 10. The effect of locality-conscious optimization.
6. Evaluation
We have implemented PowerLyra based on the latest GraphLab 2.2 (release in Mar. 2014) as a separate engine, which can seamlessly run all existing graph algorithms in GraphLab and respect the fault tolerance model. PowerLyra currently supports both synchronous and asynchronous execution. Due to the space restriction, we focus on the experiment of synchronous mode, which is the default mode for most graph tools and adopted as the sole execution mode of most graph processing systems. To illustrate the efficiency and generality of PowerLyra, we further port the Random hybrid-cut to GraphX.
We evaluate PowerLyra with hybrid-cut (Random and Ginger) against PowerGraph with vertex-cut (Grid, Oblivious and Coordinated), and report the average results of five runs for each experiment. Most experiments are performed on a dedicated, VM-based 48-node EC2-like cluster. Each node has 4 AMD Opteron cores and 12GB DRAM. All nodes are connected via 1Gb Ethernet. To avoid exhausting memory for other systems, a 6-node in-house physical cluster with total of 144 cores and 384GB DRAM is used to evaluate the scalability in terms of data size (§6.3) and the comparison with other systems (§6.9). We use the graphs listed in Tab. 4 and set 100 as the default threshold of hybrid-cut during our evaluation.
6.1 Graph Algorithms
We choose three different typical graph-analytics algorithms representing three types of algorithms regarding the set of edges in the Gather and Scatter phases:
PageRank (PR) computes the rank of each vertex based on the ranks of its neighbors [9], which belongs to Natural algorithms that gather data along in-edges and scatter data along out-edges, for which PowerLyra should have significant speedup. Unless specified, the execution time of PageRank is the average of 10 iterations.
Approximate Diameter (DIA) estimates an approximation of diameter for a graph by probabilistic counting, which is the maximum length of shortest paths between each pair of vertices [25]. DIA belongs to the inverse Natural type of algorithms that gather data along out-edges and scatter none. In such a case, PowerLyra is still expected to show notable improvements.
PowerLyra still outperforms PowerGraph due to hybrid-cut, especially for high-degree vertices. In all cases, PowerLyra outperforms PowerGraph with Grid vertex-cut by more than 2X, from 2.02X to 3.26X. Even compared with PowerGraph with Coordinated vertex-cut, PowerLyra still provides a speedup ranging from 1.42X to 2.63X. Though not clearly shown in Fig. 12(b), PowerLyra with Ginger outperforms Random hybrid-cut from 7% to 17%. Such a relatively smaller speedup for the Power-law graphs is because Random hybrid-cut already has balanced partition with a small replication factor (Fig. 7).
6.3 Scalability
We study the scalability of PowerLyra in two aspects. First, we evaluate the performance for a given graph (Twitter follower graph) with the increase of resources. Second, we fix the resources using the 6-node cluster while increasing the size of graph.
Fig. 13 shows that PowerLyra has similar scalability with PowerGraph, and keeps the improvement with increasing machines and data size. With the increase of machines from 8 to 48, the speedup of PowerLyra using Random hybrid-cut over PowerGraph with Grid, Oblivious and Coordinated vertex-cut ranges from 2.41X to 2.76X, 2.14X to 3.78X and 1.86X to 2.09X. For the increase of graph from 10 to 400 million vertices with fixed power-law constant 2.2, PowerLyra with Random hybrid-cut stably outperforms PowerGraph with Grid, Oblivious and Coordinated vertex-cut by up to 2.89X, 2.83X and 1.94X respectively. Note that only PowerLyra with Random hybrid-cut can handle the graph with 400 million vertices due to the reduction of memory in graph computation and partitioning.
6.4 Effectiveness of Graph Engine
Hybrid-cut can also be applied to original PowerGraph engine, which we use to quantify the performance benefit from the hybrid computation model, we run both PowerGraph and PowerLyra engine using the same hybrid-cut on 48 machines for the Power-law graphs. As shown in Fig. 14(a), PowerLyra outperforms PowerGraph by up to 1.40X and 1.41X using Random and Ginger hybrid-cut respectively, due to the elimination of more than 30% communication cost.
6.5 Communication Cost
The improvement of PowerLyra is mainly from reducing communication cost. In PowerLyra, only high-degree vertices (a small fraction) require significant communication cost, while low-degree vertices (a major fraction) only require one message exchange in each iteration. As shown in Fig. 15, PowerLyra has much less communication cost compared to PowerGraph. For the Power-law graphs, PowerLyra can reduce data transmitted by up to 75% and 50% using Random hybrid-cut, and up to 79% and 60% using Ginger, compared to PowerGraph with Grid and Coordinated vertex-cut respectively. PowerLyra also significantly reduces the communication cost for the Twitter follower graph up to 69% and 52% using Random hybrid-cut, and up to 74% and 59% using Ginger, compared to PowerGraph with Grid and Coordinated vertex-cut respectively.

6.6 Threshold
To study the impact of different thresholds, we run PageRank on the Twitter follower graph with different thresholds. As shown in Fig. 16, using high-cut ($\theta=0$) or low-cut ($\theta=\infty$) for all vertices results in poor replication factor due to the negative impact from skewed vertices in terms of out-edge or in-edge. With increasing threshold, the replication factor rapidly decreases and then slowly increases. The best runtime performance usually does not occur simultaneously with the lowest replication factor, since the increase of threshold also decreases the number of high-degree vertices, which benefits the overall performance. The ultimate metric for the optimal threshold is beyond the scope of this paper. Fortunately, the execution time is relatively stable for a large range of thresholds. In Fig. 16, the difference of execution time under threshold from 100 to 500 is lower than 1 sec.

6.7 Other Algorithms and Graphs
To study the performance of PowerLyra on different algorithms, we evaluate DIA and CC on the Power-law graphs. As shown in Fig. 17(a), PowerLyra outperforms PowerGraph with Grid vertex-cut by up to 2.48X and 3.15X using Random and Ginger hybrid-cut respectively for DIA. Even compared with PowerGraph with Coordinated vertex-cut, the speedup still reaches 1.33X and 1.74X for Random and Ginger hybrid-cut. Note that the missing data for PowerGraph with Oblivious is because of exhausted memory.
Since PowerLyra treats execution in the Scatter phase of low-degree vertices the same as high-degree vertices, the improvement on CC is mainly from hybrid-cut, which reduces the communication cost by decreasing replication factor. For the Power-law graphs, PowerLyra can still outperform PowerGraph with Grid vertex-cut by up to 1.88X and 2.07X using Random and Ginger hybrid-cut respectively for DIA. Even compared with PowerGraph with Coordinated vertex-cut, the speedup still reaches 1.33X and 1.74X for Random and Ginger hybrid-cut. Note that the missing data for PowerGraph with Oblivious is because of exhausted memory.
We also investigate the performance of PowerLyra for non-skewed graphs like road networks. Tab. 5 illustrates a performance comparison between PowerLyra and PowerGraph for PageRank with 10 iterations on RoadUS [1], the road network of the United States. The average degree of RoadUS is less than 2.5 (no high-degree vertex). Even though Oblivious and Coordinated vertex-cut have lower replication factor due to the greedy heuristic, PowerLyra with hybrid-cut still notably outperforms PowerGraph with vertex-cut by up to 1.78X, thanks to improved computation locality of low-degree vertices.

**Table 5. A comparison of various graph partitioning algorithms on 48 machines using PageRank (10 iterations) for the RoadUS graph.**
<table>
<thead>
<tr>
<th>Algorithm & Graph</th>
<th>Vertex-cut</th>
<th>$\lambda$</th>
<th>Time (Sec)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td>Ingress</td>
</tr>
<tr>
<td>PageRank & RoadUS[1]</td>
<td>Coordinated</td>
<td>2.28</td>
<td>26.9</td>
</tr>
<tr>
<td>$</td>
<td>V</td>
<td>=23.9M$</td>
<td>Oblivious</td>
</tr>
<tr>
<td>$</td>
<td>E</td>
<td>=58.3M$</td>
<td>Grid</td>
</tr>
<tr>
<td></td>
<td>Hybrid</td>
<td>3.31</td>
<td>14.0</td>
</tr>
<tr>
<td></td>
<td>Ginger</td>
<td>2.77</td>
<td>28.8</td>
</tr>
</tbody>
</table>
Netflix Movie Recommendation [63] | Replication Factor
| $|V|$ | $|E|$ | Vertex Data | Edge Data | Grid | Hybrid |
|-------|-------|------------|------------|------|-------|
| 0.5M | 99M | 8d + 13 | 16 | 12.3 | 2.6 |
### 6.8 MLDМ Applications
We further evaluate PowerGraph and PowerLyra on machine learning and data mining applications. Two different collaborative filtering algorithms, Alternating Least Squares (ALS) [63] and Stochastic Gradient Descent (SGD) [50], are used to predict the movie ratings for each user on Netflix movie recommendation dataset [63], in which the users and movies are presented as vertices, and the ratings are presented as edges. Both the memory consumption and computational cost depend on the magnitude of latent dimension ($d$), which also impacts the quality of approximation. The higher $d$ produces higher accuracy of prediction while increasing both memory consumption and computational cost. As shown in Tab. 6, with the increase of latent dimension ($d$), the speedup of PowerLyra using Random hybrid-cut over PowerGraph with Grid vertex-cut ranges from 1.45X to 4.13X and 1.33X to 1.96X for ALS and SGD respectively. Note that PowerGraph fails for ALS using $d=100$ due to exhausted memory as well.
 **Figure 18.** Performance comparison for various systems on the Twitter follower and Power-law ($\alpha=2.0$) graphs using PageRank. GraphX/H means GraphX with random hybrid-cut. The labels upon histogram are ingress time.
### 6.9 Comparison with Other Systems
Readers might be interested in how the performance of PowerLyra compares to other graph processing systems, even if they adopt different designs such as graph-parallel abstraction [2, 3, 18, 23, 27, 35, 43], dataflow operators [20], sparse matrix operations [10] or declarative programming [45]. We evaluate PageRank on such systems to provide an end-to-end performance comparison, as the implementation of PageRank is almost identical and well-studied on different systems. We deployed the latest Giraph 1.1, GPS, CombBLAS 1.4 and GraphX 1.1 on our 6-node cluster.
Fig. 18 shows the execution time of PageRank with 10 iterations on each system for the Twitter follower graph and the Power-law graph with 10 million vertices. The ingress time is also labeled separately. PowerLyra outperforms other systems by up to 9.01X (from 1.73X), due to less communication cost and improved locality from differentiated computation and partitioning. Though CombBLAS has closest runtime performance (around 50% slower), its pre-processing stage takes a very long time for data transformation due to the limitation of the programming paradigm (sparse matrix). We further port the Random hybrid-cut to GraphX (i.e., GraphX/H), leading to a 1.33X speedup even without heuristic and differentiated computation engine. Compared to default 2D partitioning in GraphX, random hybrid-cut can reduce vertex replication by 35.3% and data transmitted by 25.7% for the Power-law graph.
We further change the comparison targets to systems on single-machine platform. One machine of our 6-node cluster (24 cores and 64GB DRAM) is used to run in-memory (Polymer [61] and Galois [37]) and out-of-core (X-Stream [10, 40] and GraphChi [29]) systems for both in-memory and out-of-core graphs using PageRank with 10 iterations. As shown in Tab. 7, PowerLyra performs comparably to Polymer and Galois for the 10-million vertex graph, while significantly outperforming X-Stream and GraphChi for the 400-million vertex graph. Considering the resources used by PowerLyra, single-machine systems would be more economical for in-memory graphs, while distributed solutions are more efficient for out-of-core graphs that cannot handle the workload at scale.
<table>
<thead>
<tr>
<th>Graph</th>
<th>PL/6</th>
<th>PL/1</th>
<th>PO</th>
<th>GA</th>
<th>XS</th>
<th>GC</th>
</tr>
</thead>
<tbody>
<tr>
<td>$</td>
<td>V</td>
<td>$</td>
<td>10M</td>
<td>45</td>
<td>6.3</td>
<td>9.8</td>
</tr>
<tr>
<td>$</td>
<td>V</td>
<td>$</td>
<td>400M</td>
<td>186</td>
<td>–</td>
<td>–</td>
</tr>
</tbody>
</table>
Table 7. Performance (in seconds) comparison with Polymer (PO), Galois (GA), X-Stream (XS) and GraphChi (GC) on PageRank (10 iterations) for both in-memory and out-of-core graphs using one machine of our 6-node cluster. PL/N means PowerLyra running on $N$ machines.
---
5 The source code of LFGraph [23] is not available, and SocialLite [45] and Mizan [27] have some bugs to run on our clusters, which cannot be fixed in time by their authors.
6 Both Giraph and GraphX ran out of memory on our 48-node cluster for the Twitter follower graph. Missed data for GraphX and GraphX/H on the Twitter follower graph is because of exhausted memory.
8 We only implement Random hybrid-cut on GraphX for preserving its graph partitioning interface.
10 X-Stream provides both in-memory and out-of-core engines. We use the latest release from authors, which can disable direct I/O and sufficiently leverage page cache.
not fit in the memory of a single machine. The current PowerLyra focuses on the distributed platform, resulting in the relative poor performance (45s of PL/1). We believe that PowerLyra can further improve the performance for both in-memory and out-of-core graphs by adopting the novel techniques of single-machine systems, such as NUMA-aware accesses strategy [61].
6.10 Memory Consumption
Besides performance improvement, PowerLyra also can mitigate the memory pressure due to significantly fewer vertex replicas and messages. The overall effectiveness depends on the ratio of vertices to edges and the size of vertex data. As shown in the left part of Fig. 19, both the size and the duration of memory consumption on PowerLyra is notably smaller than that on PowerGraph for ALS (d=50) with Netflix movie recommendation graph, reducing near 85% peak memory consumption (30GB vs. 189GB) and 75% elapsed time (194s vs. 749s). We also use jstat, a memory tool in JDK, to monitor the GC behavior of GraphX and GraphX/H. Integrating hybrid-cut to GraphX also reduces about 17% memory usage for RDD and causes fewer GC operations even on only 6 nodes for PageRank with a Power-law graph (α=2.0). We believe the measured reduction of memory would be significantly larger if GraphX executes on a larger cluster or memory-intensive algorithms.
7. Other Related Work
PowerLyra is inspired by and deparTs from prior graph-parallel systems [18, 20, 33, 35], but differs from them in adopting a novel differentiated graph computation and partitioning scheme for vertices with different degrees.
Other graph processing systems: Several prior systems [46] use a distributed in-memory key-value table abstraction to support graph processing. LFGraph [23] proposes a publish-subscribe mechanism to reduce communication cost but restricts graph algorithms just to one direction access. Mizan [27] leverages vertex migration for dynamic load balancing. Imitator [54] reuses computational replication for fault tolerance in large-scale graph processing to provide low-overhead normal execution and fast crash recovery. Giraph++ [51] provides several algorithm-specific optimizations for graph traversal and aggregation applications relying on the graph-centric model with partitioning information. PowerSwitch [57] embraces the best of both synchronous and asynchronous execution modes by adaptively switching graph computation between them. GPS [43] also features an optimization on skewed graphs by partitioning the adjacency lists of high-degree vertices across multiple machines, while it overlooks the locality of low-degree vertices and still uniformly processes all vertices. There are also a few systems considering stream processing [15, 36] or temporal graphs [21].
Besides vertex-centric model, various programming paradigms are extended to handle graph processing. SociaLite [45] stores the graph data in tables and abstracts graph algorithms as declarative rules on the tables by Datalog. CombBLAS [10] expresses the graph computation as operations on sparse matrices and vectors, resulting in efficient computation time but also lengthy pre-processing time for data transformation. It also uses 2D partitioning to distribute the matrix for load balance.
None of existing graph processing systems use differentiated computation and partitioning. In addition, PowerLyra is orthogonal to above techniques and can further improve the performance of these systems on skewed graphs.
There are also several efforts aiming at leveraging multicore platforms for graph processing [29, 37, 40, 47, 61], which focus on such as improving out-of-core accesses [29], selecting appropriate execution modes [47], supporting sophisticated task scheduler [37], reducing random operations on edges [40], and adopting NUMA-aware data layout and access strategy [61]. Such techniques should be useful to improve the performance of PowerLyra on each machine in the cluster.
Graph replication and partitioning: Generally, prior online graph partitioning approaches can be categorized into vertex-cut [18, 24] and edge-cut [44, 49, 52] according to their partition mechanism. Several greedy heuristics [18] and 2D mechanisms [11, 24, 59] are proposed to reduce communication cost and partitioning time on skewed graphs. Surfer [13] exploits the underlying heterogeneity of a public cloud for graph partitioning to reduce communication cost. However, most of them are degree-oblivious but focus on using a general propose for all vertices or edges. Degree-based hashing [56], to our knowledge, is the only other partitioning algorithm for skewed graphs considering the vertex degrees. However, it adopts a uniform partitioning strategy yet and requires long ingress time due to counting the degree of each vertex in advance. Based on the skewed degree distribution of vertices, PowerLyra is built with a hybrid graph partitioning as well as a new heuristic that notably improves performance.
8. Conclusion
This paper argued that the “one size fits all” design in existing graph-parallel systems may result in suboptimal performance and introduced PowerLyra, a new graph-parallel system. PowerLyra used a hybrid and adaptive design that differentiated the computation and partitioning on high-degree and low-degree vertices. Based on PowerLyra, we also design locality-conscious data layout optimization to improve locality during communication. Performance results showed that PowerLyra improved over PowerGraph and other graph-parallel systems substantially, yet fully preserved the compatibility with various graph algorithms.
Acknowledgments
We thank our shepherd Amitabha Roy and the anonymous reviewers for their insightful comments, Kaiyuan Zhang for evaluating graph-parallel systems on single machine platform and Di Xiao for porting Random hybrid-cut to GraphX. This work is supported in part by the National Natural Science Foundation of China (No. 61402284), the Doctoral Fund of Ministry of Education of China (No. 20130073120040), the Program for New Century Excellent Talents in University, Ministry of Education of China (No. ZXZY037003), a foundation for the Author of National Excellent Doctoral Dissertation of PR China (No. TS0220103006), the Open Project Program of the State Key Laboratory of Mathematical Engineering and Advanced Computing (No. 2014A05), the Shanghai Science and Technology Development Fund for high-tech achievement translation (No. 14511100902), a research grant from Intel and the Singapore NRF (CREATE E2S2).
References
|
{"Source-Url": "https://ipads.se.sjtu.edu.cn/_media/publications/powerlyra-eurosys15.pdf", "len_cl100k_base": 12915, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 62411, "total-output-tokens": 17008, "length": "2e13", "weborganizer": {"__label__adult": 0.0004143714904785156, "__label__art_design": 0.0005893707275390625, "__label__crime_law": 0.0004608631134033203, "__label__education_jobs": 0.00127410888671875, "__label__entertainment": 0.00025343894958496094, "__label__fashion_beauty": 0.00023424625396728516, "__label__finance_business": 0.0006046295166015625, "__label__food_dining": 0.0004642009735107422, "__label__games": 0.0010890960693359375, "__label__hardware": 0.0016803741455078125, "__label__health": 0.0008087158203125, "__label__history": 0.0005917549133300781, "__label__home_hobbies": 0.00012433528900146484, "__label__industrial": 0.0007128715515136719, "__label__literature": 0.0005712509155273438, "__label__politics": 0.0005002021789550781, "__label__religion": 0.0006351470947265625, "__label__science_tech": 0.465087890625, "__label__social_life": 0.00015974044799804688, "__label__software": 0.0195770263671875, "__label__software_dev": 0.5029296875, "__label__sports_fitness": 0.00032448768615722656, "__label__transportation": 0.0007562637329101562, "__label__travel": 0.0002579689025878906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66021, 0.04841]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66021, 0.22244]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66021, 0.88406]], "google_gemma-3-12b-it_contains_pii": [[0, 4216, false], [4216, 8773, null], [8773, 13705, null], [13705, 19286, null], [19286, 24635, null], [24635, 30092, null], [30092, 32766, null], [32766, 36987, null], [36987, 39272, null], [39272, 41393, null], [41393, 46058, null], [46058, 50922, null], [50922, 55893, null], [55893, 61384, null], [61384, 66021, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4216, true], [4216, 8773, null], [8773, 13705, null], [13705, 19286, null], [19286, 24635, null], [24635, 30092, null], [30092, 32766, null], [32766, 36987, null], [36987, 39272, null], [39272, 41393, null], [41393, 46058, null], [46058, 50922, null], [50922, 55893, null], [55893, 61384, null], [61384, 66021, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66021, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66021, null]], "pdf_page_numbers": [[0, 4216, 1], [4216, 8773, 2], [8773, 13705, 3], [13705, 19286, 4], [19286, 24635, 5], [24635, 30092, 6], [30092, 32766, 7], [32766, 36987, 8], [36987, 39272, 9], [39272, 41393, 10], [41393, 46058, 11], [46058, 50922, 12], [50922, 55893, 13], [55893, 61384, 14], [61384, 66021, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66021, 0.1711]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
650baff445f39ff1a6bd21086380468bccbc017e
|
Software Engineering
G22.2440-001
Session 7 – Sub-Topic 3
Pattern Elicitation Frameworks/Methodologies
Dr. Jean-Claude Franchitti
New York University
Computer Science Department
Courant Institute of Mathematical Sciences
Objectives
- Describe Pattern Elicitation Activities
Roadmap
Definitions
- Solution Architecture
- Component
- Sub-solution/Sub-system
- Architectural Style
- Reference Architecture/Element
- ABASs
- Architectural Mechanisms
- Patterns
- Framework
- Architectural Pattern
- Design Pattern
- Idiom
Becoming a Chess Master
- First learn rules and physical requirements
- e.g., names of pieces, legal movements, chess board geometry and orientation, etc.
- Then learn principles
- e.g., relative value of certain pieces, strategic value of center squares, power of a threat, etc.
- However, to become a master of chess, one must study the games of other masters
- These games contain patterns that must be understood, memorized, and applied repeatedly
- There are hundreds of these patterns
Patterns...
- « Patterns help you build on the collective experience of skilled architects. »
- « They capture existing, well-proven experience in solutions development and help to promote good design practice »
- « Every pattern deals with a specific, recurring problem in the design or implementation of a business solution »
- « Patterns can be used to construct solution architectures with specific properties… »
Becoming a Solution Master
- First learn the rules
- e.g., the processes/algorithms, data structures and modeling/implementation languages
- Then learn the principles
- e.g., CBM/SOAD/OOAD methodologies, structured/modular/OO/generic programming, etc.
- However, to truly master solution design, one must study the designs of other masters
- These designs contain patterns must be understood, memorized, and applied repeatedly
- There are hundreds of these patterns
Solution Architecture
- A solution architecture is a description of the sub-solutions and components of a solution and the relationships between them
- Sub-solutions and components are typically specified in different views to show the relevant functional and non-functional properties of a business solution
- The business solution is an artifact
- It is the result of the solution design activity
Solution Architecture (cont.)
- A set of artifacts (that is: principles, guidelines, policies, models, standards, and processes) and the relationships between these artifacts, that guide the selection, creation, and implementation of solutions aligned with business goals
- Solution architecture encompasses the set of significant decisions about the organization of a solution
- Selection of the structural elements and their interfaces by which a solution is composed
- Behavior as specified in collaborations among those elements
- Composition of these structural and behavioral elements into larger solutions
- Architectural style or pattern that guides this organization
- Architecture = Elements + Form + Rationale
- Architecture involves a set of strategic design decisions, rules, or patterns that constrain solution design and implementation
- Architecture constrains design which constrains implementation
Component
- A component is an encapsulated part of a business solution/software system
- A component has an interface
- Components serve as the building blocks for the structure of a business solution/system.
- At a modeling language level, components may be represented as processes, services, etc
- At a programming-language level, components may be represented as modules, classes, objects or as a set of related functions
Sub-solutions/Sub-systems
- A sub-solution/sub-system is a set of collaborating components performing a given task
- A sub-solution/sub-system is considered a separate entity within a solution/software architecture
- It performs its designated task by interacting with other sub-solutions/sub-systems and components…
Architectural Style
- An architectural style is a description of component types and their topology
- It also includes a description of the pattern of data and control interaction among the components and an informal description of the benefits and drawbacks of using that style
- Architectural styles are important engineering artifacts because they define classes of designs along with their associated known properties
- They offer experience-based evidence of how each class has been used historically, along with qualitative reasoning to explain why each class has its specific properties
ABASs
- Attribute Based Architectural Styles (ABASs)
- ABASs build on architectural styles to provide a foundation for more precise reasoning about architectural design by explicitly associating a reasoning framework (whether qualitative or quantitative) with an architectural style
- These reasoning frameworks are based on quality attribute-specific models, which exist in the various quality attribute communities (such as the performance and reliability communities)
Back to “Patterns”
- A common solution to a common problem in a context
- Examples:
- Architectural Patterns
- Design Patterns
- Frameworks
- Implementation Patterns
- Idioms
Reference Architecture/Element
- A reference architecture is a self-contained architectural style
- i.e., provides a description of readily applicable set of component types and their topology
- e.g., SOA, OMA, etc.
- A reference element is an atomic constituent of a reference architecture
- e.g., various categories of SOA services, OMA components, etc.
Framework
- A set of assumptions, concepts, values, and practices that constitutes a way of viewing the current environment
- Defines the general approach to solving the problem
- Skeletal solution, whose details may be analysis/design patterns
- A solution/software framework is a partially complete solution/software (sub-) system that is intended to be instantiated
- It defines the architecture for a family of (sub-) systems and provides the basic building blocks to create them
- It also defines the places where adaptations for specific functionality should be made
Architectural Mechanism
- An architectural mechanism represents a common solution to a problem occurring a number of places in the system
- Often a frequently-encountered problem → a pattern
- Provide a clean way to “plug” technology-based solutions into technology-independent application models
- Examples
- Commercial off-the-shelf products
- Database management systems
- Distributed access (networking, remote methods, etc.)
- Enterprise platforms (Microsoft .NET, Java 2 Enterprise Edition, CORBA Services, etc.)
- Three categories
- Analysis mechanisms (conceptual: persistence, remote access, etc.)
- Implementation mechanisms (concrete: e.g. RDBMS, J2EE)
- Product selection mechanisms (actual: Oracle, BEA WebLogic)
Architectural Pattern
- An architectural Pattern expresses a fundamental structural organization schema for software systems
- Predefined subsystems and their responsibilities
- Rules and guidelines for organizing the subsystems
- Relationships between subsystems
- Examples of architecture patterns
- Layers
- Model-View-Controller (separate the user interface from underlying application model, integrated by a controller)
- Pipes and filters (Unix, signal processing systems, etc.)
- Shared data (web-based and corporate information systems with user views of a shared RDBMS)
Design Pattern
- A solution to a narrowly-scoped business/technical problem
- A fragment of a solution, a partial solution, or a piece of the puzzle
- A solution to a common design problem
- Describes a common design problem
- Describes a proven solution to the problem
- A solution based on experience
- Design patterns discuss the result and trade-offs of applying the pattern
- Design patterns provide the capability to reuse successful designs
- A design pattern provides a scheme for refining the subsystems or components of a solution, or the relationships between them
A technical pattern is modeled as a parameterized collaboration in UML, including its structural and behavioral aspects.
Idiom
- An Idiom is a low-level pattern specific to an implementation (i.e., execution/programming) language
- An idiom describes how to implement particular aspects of components or the relationships between them using the features of the given language
Roadmap
EAMF Framework
- Introducing the EAMF Framework
- EAMF Framework Concepts
- EAMF Standard Structural Elements
Spelling it Out!
- Enterprise
- Architecture
- Management
- Framework
Why EAMF?
- Design Information is typically not organized well enough
- Cannot find documentation when you need it
- Solutions to difficult problems are typically too complex
- Documentation, when available, is difficult to understand and buried in long and arcane documents
- Communication of problems and their solutions is typically inefficient
- Long and boring meetings with too many people.
EAMF Objectives
- Identify, categorize, capture and catalogue optimal solutions and their intent based on best practice architectural analysis and design guidelines, and patterns
- Divide and conquer problem and solution spaces
- Formalize architectural processes
- From the inception of a problem
- To the deployment of a solution
- And every step in-between
- Encourage top-down, bottom-up, and abstract thinking
- Simplify interactions between architects
EAMF Practical Ingredients
- EAMF Framework
- Supporting structure used as a container to present and maintain EAMF artifacts
- EAMF artifacts include reference and/or solution specific pattern clusters along with their intent
- EAMF Methodology
- Set of documented architectural analysis and design procedures and guidelines used to produce EAMF artifacts stored in the EAMF Framework
Introducing the EAMF Framework
- The EAMF Framework subsumes concepts and elements to store captured information
- Framework Concepts
- Organization techniques used to capture architecture information
- Structural Elements
- The framework includes general purpose structural elements that may be combined for a specific purpose
EAMF Framework Concepts
- Map
- Landscape
- Grid
- Perspective
- ViewPoint
- View
- Cell
- Artifact
- Level of Abstraction
- Level of Encapsulation
EAMF Framework Concepts: Map
- The EAMF map represents the underlying (virtual) area on which all the EAMF artifacts are located independently of the perspectives and views used to create and/or visualize them.
- The EAMF concept of a map accommodates back and forth navigation across disciplines and viewpoints within a given perspective.
- The EAMF concept of a map facilitates re-engineering or pre-existing architectures.
- EAMF is designed to support architecture engineering, re-engineering, and evolution modes.
EAMF Framework Concepts: Landscape
- The EAMF architectural landscape encompasses all the architectural elements that exist at a given time on the EAMF map.
- Effectively, it should be possible to look at an existing architectural landscape and map its artifacts to various EAMF perspectives.
- This type of effort is referred to as architectural re-engineering.
EAMF Framework Concepts: Grid
- The EAMF grid is a two-dimensional table
- Its columns represent perspectives and its rows represent views
- The grid is the main structure used in EAMF architecture engineering mode to capture information about a problem and characterize its optimal solution
- Each grid is specific to a particular architecture domain
EAMF Framework Concepts: Perspective
- A perspective is a window into the architectural sub-domains that make up a complete architecture.
- Example: Enterprise Architectures
- Architectural sub-domains include business, information, application, and technology architectures.
- EAMF perspectives may be defined accordingly to focus on one or more architectural sub-domain.
EAMF Framework Concepts: Viewpoint
- A viewpoint is a window within a perspective that focuses on a very specific aspect of an architecture sub-domain
- A viewpoint and a perspective are conceptually related as a viewpoint is more specific than a perspective
- Viewpoints encompass important information about a problem context within a given perspective that is not comprehensive enough to describe the whole problem context
- A viewpoint is a decomposition tool that helps architects focus on one important aspect of the problem rather than looking at the problem from many angles at the same time
EAMF Framework Concepts: View
- Viewpoints in a perspective divide that perspective in further detail areas
- A view, in contrast, looks at the same perspective with different intentions in mind
- A view is intention related while a viewpoint is area related
EAMF Framework Concepts: Cell
- A cell may contain any number of artifacts of different types
EAMF Framework Concepts: Artifact
- Each cell in the perspective-view grid is populated with artifacts that together capture the following information for a given business problem:
- Complete static and dynamic views
- Solution structure and information as to how that solution structure is achieved
- Catalogs that help designers create new solutions structures
- As-is (current state)
- To-be (future state)
EAMF Framework Concepts: Artifact (cont.)
- Three types of artifacts
- Textual
- Documents, notes, e-mails, memos, anything that captures information in plain text.
- Graphical
- Images, graphs, diagrams, pictures, etc.
- Tabular
- Tables, matrices, spreadsheets, etc.
EAMF Framework Concepts: Artifact (cont.)
Arrows indicate artifact traceability
EAMF Framework Concepts: Level of Abstraction
- EAMF levels of abstraction on graphical artifacts
- The graphical artifacts have conceptual, logical and physical levels of abstraction, where conceptual is very high level and does not contain any specific detail information
- The physical level is a very specific and detailed level, and the logical level somewhere between the conceptual and physical level
- EAMF levels of abstraction on tabular artifacts
- Levels of abstractions are organized on the vertical axis of the matrices (rows) where the top rows represent high level, more abstract views and the bottom rows represent lower level, highly detailed views
- EAMF defines different levels of abstractions for each perspective and each view within the perspective
EAMF Framework Concepts: Level of Encapsulation
- Levels of encapsulation/nesting may apply to certain artifacts
- For example, a pattern hierarchy may be used to describe the organization of a collection of patterns that make up a framework in a given view
- In this case the patterns involved in the hierarchy are at the same level of abstraction (i.e., they are an exclusive part of either of the analysis, design, or implementation view)
- Pattern languages may suggest how multiple pattern can be used together to make up a framework, without always implying levels of encapsulation
Roadmap
EAMF Standard Structural Elements
- EAMF Perspectives
- EAMF Views
- Perspective-View Grid
- Catalog
- Standard Matrices
- Domain Specific Matrices
- Standard vs. Domain Specific Matrices
- Constraints and Restrictions Document
- Capability Matrix
The EAMF framework relies on an architectural decomposition in terms of four perspectives:
- Business
- Application
- Information
- Technology
EAMF uses a 4x4 grid where perspectives are placed horizontally and views are placed vertically.
EAMF Perspectives (cont.)
- **Business Perspective**
- This perspective establishes a context around the problem from a business point of view
- **Information Perspective**
- This perspective establishes a context around the problem from a data structure solution point of view
- **Application Perspective**
- This perspective establishes a context around the problem from the software solution point of view
- **Technology Perspective**
- This perspective establishes a context around the problem from the hardware solution point of view
EAMF Views
- **Analysis and Design View (Model View)**
- This view defines reference architectures, architectural styles and patterns. The problem analysis and design model artifacts at conceptual and logical levels are placed in this view.
- **Implementation View**
- This view defines reference implementations, implementation styles and patterns.
- **Product View**
- This view holds artifacts that list the physical products used in the solution. The products are different for each perspective.
- **Deployment View**
- This view holds artifacts that show how the solutions are used in a physical environment with the determined products.
The EAMF perspectives and views create a 4x4 grid where perspectives are placed horizontally and views are placed vertically as shown.
This grid is the primary mechanism through which all architectural analysis, design, implementation and deployment information is stored on the map in an organized manner.
Catalog
- A catalog exists in EAMF independent of a problem context
- There can be one catalog per view per perspective
- A catalog contains best practice patterns available in an industry
- For practical reasons, catalogs only include pattern information relevant to a specific domain
- The catalogs are maintained by BAs and TAs to keep track of emerging and evolving patterns
Standard Matrices
- The *standard matrices* show how a particular problem should be solved in an ideal environment
- Most of the time a company does not have the ideal environment to implement the solution
- These matrices can be used as a description of the desired state of architecture for a particular problem
- They, too, need to be updated continuously to reflect recent changes in the patterns world
Domain Specific Matrices
- The *domain specific matrices* capture the solution implemented in an environment that is less than ideal
- There might be many reasons why a company does not have an ideal environment which is mostly financial and time constraints related
- Domain specific matrices are a snapshot that shows the current architecture and implementation
- When the company environment changes towards the ideal environment the solution can be re-factored and brought closer to the solution that is described in the standard matrices
Standard vs. Domain Specific Matrices
- The standard matrix shows an ideal choice of patterns for the solution while the domain specific matrix shows choice of patterns that need to be used (i.e., mechanisms) in a company domain based on the restrictions and constraints imposed either by the company or by external forces.
- Standard and Domain Specific Matrices can respectively be considered as the future and current state matrices.
- Standard Matrix represents the future state because it captures information for an ideal solution.
- Most often, due to constraints and restrictions, internal or external, this ideal solution cannot be realized.
- Domain Specific Matrix represents the current state solution.
- Therefore, the information in these matrices can be used as gap analysis and provide executive management with important information for decision making purpose.
- Capturing the constraints and restrictions during the process also ties historical decisions to the current state.
Standard vs. Domain Specific Matrices: Population Process
- The following diagram depicts the processing rule which applies every time when there is a standard and domain specific matrix independently from the enterprise perspective:
Constraints and Restrictions Document
- As explained in the previous section if there is a need to create a domain specific matrix, the reasons must be captured within a Constraints and Restrictions Document.
- The document specifically outlines why a standard matrix or a previously used domain specific matrix cannot be used.
- Instances of this document are repeated wherever there is a need to replace a standard matrix with a domain specific matrix.
Capability Matrix
- A capability matrix shows the capabilities of an entity as a tabular artifact.
- This matrix type is mostly used in the application perspective for determining the functional capabilities of reference architectures, reference implementations and products.
- However, there are other perspectives where the capability matrices are employed.
- The format of the matrix depends on the type of capabilities it captures.
Roadmap
EAMF for Business Architects
- Using EAMF Standard Structural Elements in the Business Perspective
Business Perspective: Business Model
• Business Process
• A long running set of actions or activities performed with specific business goals in mind
• Business processes typically encompass multiple service invocations
• Examples of business processes are: *Initiate New Employee*, *Sell Products or Services*, and *Fulfill Order*
• In SOA terms, a business process consists of a series of operations which are executed in an ordered sequence according to a set of business rules
• The sequencing, selection, and execution of operations is termed service or process *choreography*
• Typically, choreographed services are invoked in order to respond to business events.
Business Perspective: Business Patterns
- Choreography
- A choreography is the observed sequence of messages exchanged by peer services when performing a unit of work
- Services do not need to be orchestrated to perform a unit of work (this is a concept that emerged and should have stayed in the last century)
- This is a very common misconception, actually most units of work are accomplished by a series of "orchestrated services" performing a choreography
- There are several industry efforts in the area of choreography languages, such as BPML (defined by BPMI.org), BPSS (defined by ebXML), IBM's WSFL, Microsoft's XLANG, and IBM/Microsoft/BEA's BPEL4WS and their companion specifications WS-Coordination and WS-Transaction, etc.
Business Perspective: Business Patterns
- Orchestration
- An orchestration is a generalization of composition that sequence services and provide additional logic to process data that does not include data presentation
- The same language can be used to perform a complex unit of work achieved by invoking a series of service operations
- Any given orchestration is not forced to expose a service interface
- If it does, it is a composition
- An orchestration is executed by an orchestration engine
- BPEL is an orchestration programming language
## Business Perspective: Filling up the Business Grid
<table>
<thead>
<tr>
<th>View points</th>
<th>Process</th>
<th>Process Interaction</th>
<th>Process Organization Interface</th>
<th>Organization</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>Artifacts color coded as Textual Graphical Tabular</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
### Pre-requisite) Complete Conceptual Business Architecture Diagram(s)
### Pre-Requisite) Business Model Catalogs
### Vision - Motivation
### Strategy
### Goals - Objectives
### Business Problem Description
### Business Problem Analysis
### Problem Specific Conceptual Business Architecture Diagram(s)
### Standard Business Model Matrices
### Business Architecture Constraints and Restrictions Document
### Domain Specific Business Model Matrices
### Capabilities and Requirements Matrices
---
**Architectural View:**
**Product View:**
**Deployment View:**
**Implementation View:**
There are no artifacts populated in the grid cell. The implementation view in the business perspective represents how a business process would be implemented using no technology.
An example for this may be how to sell AFLAC insurance policy without any technology like SmartApp or SNG.
Since most of AFLAC’s business is executed by the usage of technology this view will not be populated.
There are no artifacts populated in the grid cell. The product view in the business perspective represents which products are to be employed in order to achieve the business processes.
An example for this may be that an associate may use his car, pen, paper, etc. in order to sell AFLAC insurance policy without any technology like SmartApp or SNG.
Since most of AFLAC’s business is executed by the usage of technology this view will not be populated.
There are no artifacts populated in the grid cell. The deployment view in the business perspective represents how business processes are executed using the selected products to achieve business processes.
Since most of AFLAC’s business is executed by the usage of technology this view will not be populated.
Artifacts used to capture and store information within the perspective
Business Perspective:
Conceptual Business Architecture (CBA)
A business process that is accessed by only one actor or another process implies possible Application Server architecture.
A broken line oval shape that represents a collaboration between two or more human actors implies possible Collaboration architecture.
A business process that is accessed by more than one actor implies possible SOA architecture.
A business process that controls other business processes by either invoking or including them implies possible BPM architecture.
Business Perspective: Problem Specific CBA
Business Perspective: Viewpoints
- **Process**
- This viewpoint isolates the set of involved business processes
- **Process Interoperability**
- This viewpoint isolates the unique relationships between involved business processes
- **Process Organization Interface**
- This viewpoint isolates the relationship between the business processes and their interaction with the people
- **Organization**
- This viewpoint isolates the people around the business problem and its solution structure
- **Location**
- This viewpoint isolates the location of the people in the context of the business problem and its solution structure
Business Perspective: CBA-Viewpoints Relationship
Business is divided into three main viewpoints
1) Process
2) Organization
3) Location
and their intersections.
Conceptual Business Architecture: A complete, high level explanation of processes, organization and location and the relations between them.
Process – Organization Intersection: Who runs business activities?
- Process: What are the business activities?
- Related Patterns: Elementary/Composite Business Process, Short/Long Lived Process
Organization: Who are the people?
- Related Patterns: Internal (Employee), External (Customer), Privileged (Associate)
Process – Location Intersection: Where do business activities run?
- Location: Where are the offices?
- Related Patterns: Main Office, Connected/Occasionally Connected Branch
Organization – Location Intersection: Where are people located?
Business Perspective: Business Model Catalog
- Business Model Catalog is a problem independent artifact in EAMF
- It lists the available Business Reference architectures and more detailed information for each of these business reference architectures
Business Perspective: Reference Architectures Model Matrix
- Combined with the Business Perspective viewpoints the Model Matrix looks like the following tabular artifact
- There will be one populated instance of the above matrix per business reference architecture
<table>
<thead>
<tr>
<th>Business Reference Architectures Model Matrix</th>
</tr>
</thead>
<tbody>
<tr>
<td>Process</td>
</tr>
<tr>
<td>Business Architectural Styles</td>
</tr>
<tr>
<td>Business Architectural Patterns</td>
</tr>
<tr>
<td>Business Design Patterns</td>
</tr>
</tbody>
</table>
Business Perspective: Standard and Domain Specific Model Matrices
- Standard and domain specific model matrices look exactly like the catalog model matrix, except there will be one or more instances per problem description.
- While a catalog shows all applicable styles and patterns for that reference architecture a standard model matrix instance shows only the patterns that apply to the ideal solution of that problem.
- Domain Specific Model Matrix instance shows only the patterns that apply to a solution imposed by the constraints and restrictions.
Business Perspective: Capabilities and Requirements Matrix
- Capabilities and Requirements Matrix (a.k.a., CR Matrix) is used to capture the non-functional and functional, business and technical capabilities to solve a specific business problem.
- Capabilities are set of concerns that a solution tries to address.
- Requirements are entries in the matrix that describe how a solution meets a specific business requirement while addressing the capability.
<table>
<thead>
<tr>
<th>Motivation</th>
<th>Policy Type</th>
<th>Measurable (only verifiable after implementation)</th>
<th>Concrete (based on proven design)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Business Driven</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(resulting from analysis)</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Technology Driven</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(resulting from design considerations)</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Business Perspective: Adding a New Reference Architecture
- EAMF is not complete in terms of standard capability sets
- EAMF must be augmented when the experience level of the architects reach an expert level in a reference architecture such as SOA, ECM, BPM and so on
- The process of determining a more abstract capability sets is shown on the right
Business Perspective: Non-Functional Capabilities (NFCs)
- Non-functional capabilities are filled by BAs and TAs in collaboration. There are three types of non-functional requirements.
- Only the project-based capabilities are answered when filling out the CR-Matrix.
- Organizational and external non-functional capabilities represent constraints and are used when determining domain specific solutions.
Non Functional Capabilities (NFCs)
- Project-Based NFCs
- Accuracy
- Availability
- Efficiency
- Extensibility - Upgradeability – Modifiability – Adaptability - Flexibility
- Interoperability
- Portability
- Recoverability
- Reliability – Dependability
- Reusability
- Scalability – Capacity
- Security – Accessibility – Anonymity - Vulnerability
- Usability – Operability
- Organizational NFCs
- Readability – Simplicity – Understandability
- Maintainability
- Testability – Verifiability
- Traceability
- External NFCs
- Ethical
- Legislative (Privacy – Safety)
- Planning (Cost, development time)
Business Perspective: Project-Based NFCs
- **Accuracy**
- Accuracy is the quantitative measure of the magnitude of error
- **Availability**
- Degree to which a service, system or component is operational and accessible when required for use
- **Efficiency**
- Efficient is the degree to which a system or component performs its designated functions with minimum consumption of resources (CPU, Memory, I/O, Peripherals, Networks)
- **Extensibility - Upgradeability – Modifiability – Adaptability - Flexibility**
- **Adaptability**
- Ease with which software satisfies differing system constraints and user needs.
- **Flexibility**
- Ease with which a system can be modified for use in applications other than those for which it was specifically designed.
- Use Strategy Pattern, etc…
- Interoperability
- Portability
Business Perspective:
Project-Based NFCs (cont.)
- Interoperability
- Portability
- Ease with which a system or component can be transferred from one hardware or software environment to another
- Recoverability [IEEE 90]
- Recoverability is the restoration of a system, program, database or other system resource to a prior state following a failure or externally caused disaster
- Reliability – Dependability
- Reliability is the ability of a system or component to perform its required functions under stated conditions for a specified period of time
- Reusability
Business Perspective: Project-Based NFCs (cont.)
- Scalability - Capacity
- Scalability is the ease with which a system or component can be modified to fit the growing problem area. Scalability has two variants, hardware and software.
- Security – Accessibility – Anonymity – Vulnerability
- Security is the ability of a system to manage, protect and distribute sensitive information.
- Usability - Operability
- Usability is the ease with which a user can learn to operate, prepare inputs for and interpret outputs of a system or component.
Business Perspective: Organizational NFCs
- Readability – Simplicity – Understandability
- The degree to which a system's functions and those of its component statements can be easily discerned by reading the associated source code
- Maintainability
- The ease with which a software system or component can be modified to correct faults, improve performance, or other attributes, or adapt to a changed environment
- Testability – Verifiability
- The degree to which a system or component facilitates the establishment of test criteria and the performance of tests to determine whether those criteria have been met
- Traceability
- The degree to which a relationship can be established between two or more products of the development process, especially products having a predecessor-successor or master-subordinate relationship to one another
- Delivery
- Implementation
Business Perspective:
External NFCs
- Ethical
- The policies regarding ethics that a corporation adopts when conducting business
- Legislative (Privacy – Safety)
- The policies that a corporation is imposed upon when conducting business
- Planning (Cost, development time)
- The resource constraints that are imposed on a project
Business Perspective: Sample Functional Capabilities
- EAMF divides the functional capabilities in three distinct top level categories:
- OMA Specific Services
- Concurrency Service (http://www.omg.org/docs/formal/00-06-14.pdf)
- Externalization Service (http://www.omg.org/docs/formal/00-06-16.pdf)
- Event Service
- Interface Invocation Service
- Life Cycle Service
- Naming and Directory Services (http://www.omg.org/docs/formal/04-10-03.pdf)
- Notification Service
- Persistence State Service
- Security Service
- Trading Object Service
- Transaction Service
- OMA Specific Facilities
- OMA Application Objects
Roadmap
EAMF Methodology
- Using a PDA EAF
- NFR-Driven Pattern Elicitation
Using a PDA EAF
- Gather problem definition – Business Requirements
- Create Conceptual Business Architecture Diagrams
- Create Business Catalogs
- Business model matrix (BMM) captures reusable business reference architectures, architectural styles and patterns
- Business implementation matrix (BIM) captures reusable reference implementations, styles and implementation patterns
- The implementation view is prescriptive and the model view is descriptive
- Run Through Decomposition Process
- Populate Standard and Domain Specific Business Model Matrices
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Business Architectural Patterns</td>
<td>EBP. Producer</td>
<td></td>
<td>C2B Request/ Response</td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>EBP. Transformer</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td>EBP. Transformer. HighVolume</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>Business Analysis Model</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Using a PDA EAF (continued)
- Populate Capabilities and Requirements Matrix (CR-Matrix)
- Before the architects start creating instances of CR-Matrices several questions must be answered:
- What is the primary viewpoint for this business problem?
- Which patterns are related to each other across viewpoints?
- Which patterns or styles do not contribute to a technology solution pattern?
- Let us assume that the answers to the above questions are:
- The primary viewpoint is **Process**.
- The related patterns across viewpoints are **EBP.Producer.LowVolume** and **C2B.RequestResponse.FastAccess**.
- The **GroupsOfIndividuals** and **Centralized** styles do not contribute to the business problem solution.
- Then
- Create one CR-Matrix instance for each pattern in the primary viewpoint.
- Create one CR-Matrix instance for each set of related patterns across viewpoints, and do not include non-contributing patterns.
- As follows:
- EBP.Transformer.HighVolume.
- Policies are entered into the CR-Matrix
<table>
<thead>
<tr>
<th>Policy Type</th>
<th>Measurable (only verifiable after implementation)</th>
<th>Concrete (based on proven design)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Measurable</td>
<td>Measurable policies that <strong>disable</strong> business operations if not within compliance</td>
<td>Policies that <strong>disable</strong> business operations if they do not exist.</td>
</tr>
<tr>
<td>Concrete</td>
<td>Policies that may <strong>hurt</strong> the business but not disable it if not within compliance</td>
<td>Policies that may <strong>hurt</strong> business but not disable it if they do not exist.</td>
</tr>
</tbody>
</table>
Motivation
- **Business Driven** (resulting from analysis)
- **Technology Driven** (resulting from design considerations)
Using a PDA EAF (continued)
- Using a CR-Matrix
- Generation of the Conceptual Technology Architecture Diagram
- Identification and Confirmation of Appropriate Reference Architecture(s)
- Generation of a Logical Architecture Analysis Diagram
- Generation of the Analysis Model
- Identification of Applicable Pattern(s)
- Generation of a Logical Architecture Design Diagram
- Generation of the Design Model
- Identification of Applicable Reference Implementation(s)
- Identification of Applicable Implementation Pattern(s)
- Refinement of the Logical Architecture Design Diagram
- Refinement of the Design Model
- Product Mapping
- Deployment
- Working with Developer
- Deployment Mapping
NFR-Driven Pattern Elicitation
- NF policies identified in the CR-Matrices are used to determine appropriate styles and patterns for the solution
- Not all non-functional capabilities lead to software design patterns
- Some non-functional capabilities such as reliability, availability, recoverability and dependability (and possibly others) require hardware deployment patterns along with organizational behavior changes towards quality
- There is no (bullet-proof) defined process that would help an architect to identify appropriate patterns
- A pattern can be applicable to a certain problem but it may not be appropriate
- The identification of the applicable and appropriate pattern requires immense working pattern knowledge which is not only knowing and understanding what patterns are but also recognizing when and when not to use certain patterns
- NFR Framework Based Approach is suggested
NFR-Driven Pattern Elicitation: Sample Guidelines
<table>
<thead>
<tr>
<th>Motivation</th>
<th>Policy Type</th>
<th>Measurable (only verifiable after implementation)</th>
<th>Concrete (based on proven design)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Business Driven - Required - (resulting from analysis)</td>
<td></td>
<td>Efficiency.Time: 8 sec/per request/per user</td>
<td>Availability: 6:00 am - 6:00 pm Business days</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Scalability: 20 concurrent users to 40 concurrent users without software modifications</td>
<td>Security: Only authenticated and authorized AFLAC employees</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Extensibility: Same generation process with different algorithms will be supported.</td>
<td>Concurrency: Persistent State Security: Transaction</td>
</tr>
<tr>
<td>Technology Driven - Desired - (resulting from design considerations)</td>
<td></td>
<td>Efficiency.Time: 0.5 sec/per request/per user</td>
<td>Testability: Provide test harness, debugging and adjustable levels of logging capabilities.</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Readability: Follow company standards</td>
<td>Naming and Directory</td>
</tr>
</tbody>
</table>
For improvements in Efficiency.Time
Minimize I/O
I/O operations are time consuming. Try to group I/O operations in chunks and keep the retrieved data in memory for later use. Use value transfer object patterns and use them as member variables of Business Objects.
Reduce Network Calls.
Network calls are time consuming and may be unreliable. Reduce network calls by using patterns similar to Remote Façade patterns.
Separate process algorithm into Synchronous and Asynchronous layers.
Run part of an algorithm that is absolutely necessary during real time. Use Service Activator Pattern.
Optimize Algorithm
The patterns for this guideline depend on the type of algorithm.
For improvements in Extensibility
Program to interfaces rather than an implementation
Use patterns similar to Strategy and Template Method depending on your need.
For improvements in Scalability
Keep data modification blocks short and synchronized.
Table Data Gateway Pattern.
Improve Efficiency.Time
Architecture Design Method
- **Requirement Specification**
- Functional requirements
- Quality requirements
- Development (Build-time)
- Operational (Run-time)
- **Functionality-Based architectural design**
- **Application Architecture**
- **Quality-Attribute Optimizing Solutions**
- **Estimate quality attributes**
- **Architecture Transformation**
- [not OK]
- [OK]
Overview of Architecture Design Method
- **Functionality-based architectural design**
- Define system context
- Identify archetypes (core functional abstractions)
- Decompose into components
- Interfaces, domains, abstraction layers, domain entities, archetype instantiations
- Describe system instantiations
- **Assess quality attributes**
- Define quality profiles
- Scenario-based assessment
- Simulation
- Mathematical modeling
- Experience-based assessment
- **Architecture transformation**
- Impose architectural style
- Impose architectural pattern
- Impose design patterns
- Convert quality requirements to functionality
- Distribute requirements
Architecture Transformation Categories
- **Restructuring**
- Added functionality, rules, and/or constraints
**Transformation Type**
**Component**
- Convert Quality Requirement to Functionality
- Apply Design Pattern
**Architecture**
- Impose Architectural Pattern
- Impose Architectural Style
*In principle, repeat each step for each quality attribute*
Convert Quality Requirements to Functionality
- Self-monitoring
- Redundancy
- Security
- etc.
**Distribute Requirements**
- Distribute system-level quality requirements to the subsystems and components
- System quality $X$; component quality $x_i$
- $X = x_1 + x_2 + x_3 + ... + x_n$
- Separate functionally-related qualities
- e.g., Fault-tolerant computation + fault-tolerant communication
Impose an Architectural Style
- Bass *et al.*, Attribute-Based Architectural Styles (ABASs)
- Pipes and filters
- Layers
- Blackboard
- Object-Orientation
- Implicit Invocation
- etc.
Impose an Architectural Pattern
- Concurrency
- Processors, processes, threads, scheduling, etc.
- Persistence
- Database management system, application-level persistence and transaction handling, etc.
- Distribution
- Brokers, remote method invocation, etc.
- Graphical User Interface
- MVC, PAC, etc.
Apply a Design Pattern
- Gang-of-Four, Buschmann, etc.
- Façade
- Observer
- Abstract Factory
- etc.
Meta-Tools For Model Driven Architectures
As information is collected, work effort, estimates and solution becomes concrete
Patterns
Abstract Costs
Technical Solution Development
Application: - Data - Business Logic - Content (Screens)
Concrete Costs
Application Production (Approach/ Assembly/ Delivery)
Domain Analysis
User Information Gathering
User & Business Models
Information Not Specific to Domain
Preferences
Questions?
Concrete Costs
Application Server
Physical Infrastructure
NT/ UNIX
Frameworks
Abstract Costs
Analysis
Architectural Styles
- Transaction Processing
- Persistence
- etc.
Conceptual Infrastructure
Infrastructures
Domain Specific Information
Taxonomy
Domain Models
Initial Costs
Technical Solution Development
Application Models - Data Model - Business Model - Content Model
Questions?
Domain Analysis
Technical Solution Development
Application Model - Data Model - Business Model - Content Model
Questions?
Concrete Costs
Data
Business Logic - Content (Screens)
Application
Proposal End Point
Concrete
Abstract
Pattern Matching Approach
http://www.scs.carleton.ca/~weiss/research/nfr/cito.pdf
- Represent force hierarchies that match a problem domain using GRL notation
- Represent force hierarchies that characterize patterns using GRL notation
- Include pattern force hierarchy as part of individual pattern templates in the pattern catalog
- Apply algorithms to match force hierarchies for a given problem domain with known pattern force hierarchies in the pattern catalog
- Comparison algorithm
- See “Deciding on a Pattern” by Jonathan C. McPhail and Dwight Deugo
- Data mining algorithm
- Learning/Rule-based algorithm
- Perform additional matching on more specific artifacts than force hierarchies as available (e.g., architecture modeling notations, etc.)
Roadmap
Sample EAMF-Driven Pattern Elicitation:
- EAMF Process Patterns (Actors as Agents)
- EAMF GDM UCM Inter-Scenario Relationships
- Enterprise Service Lifecycle
- Service Management Architecture (SMA)
Reasoning About Business Entities and Their Dependencies and Goals
Legend:
- : GRL Modeling Constructs

1. High-Level Business Requirements (bus. obj. & informal reqs)
2. Business Model Reqs (org, location, process)
3. Value Flows Between Actors
4. Goals & Subgoals
5. Actors
6. Dependencies
7. High-Level Tasks
8. EAMF Process Patterns
Help Engineer
Refined into
Motivated By
Have
Represented In Terms of
Indicate
Have (Based on Goals Achievement)
Pattern Language Structure for Agent Patterns Selection
(http://www.scs.carleton.ca/~weiss/papers/aois03-revised.pdf)
Inter-Scenario Relationships Design
Patterns Used in EAMF’s BPM approach
Enterprise Service Lifecycle Management
ESLM Context Model
- Administration
- Transaction Management
- Reporting
Branches:
1. State Set Administration
2. Business Entity & Transaction Type Administration
3. Transaction Information Storage Structure/Access (WITTS)
4. Transaction Monitoring
5. Static Reports
6. Dynamic Reports - Dashboard - Adhoc Queries
7. Business Analysis / Business Intelligence Reports
- Archivable Transactions Monitor
- Illegal State Transition Monitor
- Expired States Monitor
- Obsolete Business Entity Instance Monitor
- Abandoned Transaction Monitor
SMA Reference Architecture: The Acronyms...
- SMA = SOA + STA
- SOA = SOP + SOI + SOM
- SOA – Service Oriented Architecture
- STA – Service Trader Architecture
- SOP – Service Oriented Process
- SOI – Service Oriented Integration
- SOM – Service Oriented Management
SMA: The Final Big Picture…
- **paper**
- **fax**
- **email**
- **Web Portal**
- **Business Services**
- **Composite Services**
- **Worker Services**
- **DBs, IBML, RRI, PeopleSoft**
**STA**
**SOP**
**SOI/SOM**
SMA: How it works...
SOI + SOM = ESB
ESB + SOP = SOA
Service Oriented vs Object Oriented
- Services cut across multiple objects
- Objects encapsulate data, but Services encapsulate behavior
- The “lower” the service, the more like an object it becomes
Service Oriented vs Application Oriented
Applications typically wrap a single “large” database
“Services” within an application are typically tightly coupled
Services don’t necessarily entirely reside “within” the corresponding application
Groupings of “high” level services begin to resemble applications
SMA: Technology Properties
- Location and platform independence
- Reuse via shared services (not copied/duplicated code)
- Strict adherence to encapsulation and public API
- Separation of service interface and service implementation (via WSDL)
- Deployment of new services and upgrades to existing services (implementation or interface extension), with NO down-time, via dynamic service end-point discovery (UDDI)
SMA: Long-range Business Benefits
- Uniform and consistent IT deployment “fabric” (virtual platform)
- Uniform and consistent support for SLAs
- Common data security and access control base-line
- Library of common support services that will enable new projects to focus on their unique attributes rather than reinventing infrastructure
- Integrated real-time monitoring and business analysis capabilities across the enterprise
- Enables 24x7 operation, despite software system (service) upgrades
SMA: Benefits, Risks, and Pitfalls
The Good
• Location and platform independence
• Non-proprietary in that ESB enables multiple service “platforms” to interoperate/communicate
• Separation of interface and implementation
• Dynamic late (re)binding
• Live upgrades/(re)deployments
• Flexible reuse supports agile IT support for business
• Enterprise IT architecture/design is driven by business needs
The Bad
• Poor initial API could limit reuse of services (or require cascading redesign/reimplementation)
• Some standards are still emerging or are in flux
• May require “retooling” of system design (thought) process
The Ugly
• More run-time overhead in extra layers and protocols
• Needs coherent and consistent enterprise “platform” management
Roadmap
Classifying Problem Types
- What is the problem?
- Problem Types
- Enterprise Problem Instance
- Pattern Cluster
- How Does EAMF Come Into Play?
What is the Problem?
- EAMF is a framework with a methodology to capture design information for similar problems.
- Before we start designing a solution we need to understand why we are designing a solution.
- In an enterprise, motivations will arise based on needs and/or problems. Change is requested and needs to be dealt with.
- When we are dealing with change, we need to create a structured environment so that we solve similar problems using similar solutions in order to reduce redundancies.
- This structured environment is not only a technical framework but a structured thinking process which helps us organize the changes in specific categories because if we can categorize the types of changes we can easier categorize the solutions that address them.
Problem Types
- A problem type identifies the essence of a problem without the details of the problem instances.
- A solution to a problem type is more generic than a solution to a problem instance.
- By the same token, a generic solution to a problem type can be applied to all problem instances in that problem category.
Problem Types (cont.)
- Atomic problem instance (api)
- Specific instance of a problem that cannot be further divided into sub-problems
- Composite problem instance (cpi)
- Specific instance of a problem that can be further subdivided into atomic problem instances, however it would be better to keep this problem instance in its composite form because the solution to the composite problem is more effective than the sum of the solutions to its atomic problem instances
- In other words, there may be such a synergy between the atomic problem instances which makes the composite problem instance more effectively solvable
- Atomic and composite problem instances are categorized into problem types
- This creates a smaller set of problem types from a larger set of atomic and composite problem instances
Problem Types (cont.)
- Categories of Problem Types
- The current problem types need to be determined with the help of business experts and business architect
- Problem types can be categorized in many different ways
- Problem types can be categorized by the type of IT solution they require (IBM does this in their eBusiness) such as
- Self-Service
- Collaboration
- Information Aggregation
- Extended Enterprise (B2B)
- Problem types can be categorized by service line they occur in such as
- Billing
- Claims
- New Business
- Etc.
Problem Types (cont.)
- Categories of Problem Types (cont.)
- Problems may be categorized by a more generic classification like
- Information Sharing
- Short Lived Business Transaction
- etc...
- Yet another way to categorize problems can be the life cycle of a specific context
- Doculabs consultants did that with their ECM problem types
- They have categorized the problem types by the life cycle of Content such as
- Create Content
- Review Content
- Approve Content
- Manage Metadata
- Etc...
- We need to find a correct way of categorization in order to achieve our goals.
Enterprise Problem Instance
- Enterprise Problem Instance (epi)
- Combination of one or more atomic and composite problem instances
- Since these problem instances are categorized as more abstract problem types, enterprise problem instances can be represented as a combination of problem types
- Since these problem instances are categorized as more abstract problem types, enterprise problem instances can be represented as a combination of problem types.
Pattern Cluster
- A **Pattern Cluster** is a set of patterns which are involved in the generic solution of a problem type.
- Since there may be more than one generic solution to a problem type:
- *Enterprise Solution Architectures are a combination of pattern clusters of one or more Enterprise Architectures*
- This conclusion identifies two additional tasks
- First we need to identify what the available Enterprise Architectures are.
- Second we need to identify the pattern clusters in these Enterprise Architectures.
Pattern Cluster (cont.)
- We have defined Enterprise Architectures as solutions provided within a context
- In the enterprise landscape not all of the contexts are at the same level of detail
- It is normal that one Enterprise Architecture uses pieces from another Enterprise Architecture to provide a solution
- Some of the architectures will be high level and make sense from a business point of view like Customer Relationship Management (CRM)
- Some of them may be more specific in focus that only deals with certain types of problems like unstructured enterprise information like Enterprise Content Management (ECM)
- CRM might use some pattern clusters from ECM in order to provide a solution
Pattern Cluster (cont.)
- So far we have established that
- Specific problem instances are categorized to a problem type
- A problem type can have one or more enterprise solutions
- An enterprise architecture contains 1 or more pattern clusters
- An enterprise solution contains one or more pattern clusters from one or more enterprise architectures
How Does EAMF Come Into Play?
- EAMF comes into play from two different views:
- A catalog view that captures pattern clusters and individual patterns in the framework’s catalog matrices
- A design view that captures enterprise solutions for a problem type and the pattern clusters and individual patterns used in that solution in the framework’s standard and domain specific matrices
- The catalog matrices are populated over time
- Every time a company realizes more experience and knowledge and identifies a pattern or a pattern cluster the cluster would be inserted into the appropriate catalog matrices
- The catalog matrices would serve as a repository which would help architects and developers to reuse solution structures in future similar problems
- The standard and domain specific matrices are populated during a project
- The usage of EAMF begins when a business or technology problem is described. The problem is being analyzed outside the focus of EAMF and a set of business requirements is created based on the problem description and analysis
Any Questions?
|
{"Source-Url": "http://www.nyu.edu/classes/jcf/CSCI-GA.2440-001_sp14/slides/session7/PatternElicitationFrameworksAndMethodologies.pdf", "len_cl100k_base": 11635, "olmocr-version": "0.1.51", "pdf-total-pages": 113, "total-fallback-pages": 0, "total-input-tokens": 164941, "total-output-tokens": 15620, "length": "2e13", "weborganizer": {"__label__adult": 0.0004658699035644531, "__label__art_design": 0.0015392303466796875, "__label__crime_law": 0.000274658203125, "__label__education_jobs": 0.005645751953125, "__label__entertainment": 0.0001251697540283203, "__label__fashion_beauty": 0.00024437904357910156, "__label__finance_business": 0.0006413459777832031, "__label__food_dining": 0.0003077983856201172, "__label__games": 0.000873565673828125, "__label__hardware": 0.0009365081787109376, "__label__health": 0.00031185150146484375, "__label__history": 0.0005588531494140625, "__label__home_hobbies": 0.00017178058624267578, "__label__industrial": 0.0006012916564941406, "__label__literature": 0.00047850608825683594, "__label__politics": 0.00026226043701171875, "__label__religion": 0.0005660057067871094, "__label__science_tech": 0.017578125, "__label__social_life": 0.00015282630920410156, "__label__software": 0.007129669189453125, "__label__software_dev": 0.9599609375, "__label__sports_fitness": 0.0003998279571533203, "__label__transportation": 0.0006709098815917969, "__label__travel": 0.0002760887145996094}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57586, 0.00266]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57586, 0.63705]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57586, 0.87919]], "google_gemma-3-12b-it_contains_pii": [[0, 224, false], [224, 278, null], [278, 523, null], [523, 1024, null], [1024, 1442, null], [1442, 1915, null], [1915, 2317, null], [2317, 3244, null], [3244, 3673, null], [3673, 3993, null], [3993, 4592, null], [4592, 5064, null], [5064, 5251, null], [5251, 5615, null], [5615, 6193, null], [6193, 6946, null], [6946, 7541, null], [7541, 8140, null], [8140, 8261, null], [8261, 8517, null], [8517, 8637, null], [8637, 8708, null], [8708, 9114, null], [9114, 9579, null], [9579, 9973, null], [9973, 10314, null], [10314, 10463, null], [10463, 10985, null], [10985, 11351, null], [11351, 11704, null], [11704, 12082, null], [12082, 12687, null], [12687, 12950, null], [12950, 13045, null], [13045, 13462, null], [13462, 13750, null], [13750, 13831, null], [13831, 14616, null], [14616, 15215, null], [15215, 15472, null], [15472, 15714, null], [15714, 16265, null], [16265, 16920, null], [16920, 17228, null], [17228, 17614, null], [17614, 18026, null], [18026, 18574, null], [18574, 19585, null], [19585, 19820, null], [19820, 20278, null], [20278, 20717, null], [20717, 20826, null], [20826, 21518, null], [21518, 22265, null], [22265, 22825, null], [22825, 24978, null], [24978, 25039, null], [25039, 25568, null], [25568, 26207, null], [26207, 27069, null], [27069, 27321, null], [27321, 28089, null], [28089, 28646, null], [28646, 29973, null], [29973, 30326, null], [30326, 31374, null], [31374, 32228, null], [32228, 32802, null], [32802, 33353, null], [33353, 34237, null], [34237, 34575, null], [34575, 35241, null], [35241, 35319, null], [35319, 37045, null], [37045, 38858, null], [38858, 39586, null], [39586, 40496, null], [40496, 42507, null], [42507, 42894, null], [42894, 43584, null], [43584, 43944, null], [43944, 44346, null], [44346, 44543, null], [44543, 44855, null], [44855, 44965, null], [44965, 46045, null], [46045, 46871, null], [46871, 47079, null], [47079, 47555, null], [47555, 47674, null], [47674, 47890, null], [47890, 48473, null], [48473, 48743, null], [48743, 48959, null], [48959, 48980, null], [48980, 49012, null], [49012, 49212, null], [49212, 49519, null], [49519, 49934, null], [49934, 50432, null], [50432, 51185, null], [51185, 51339, null], [51339, 52111, null], [52111, 52435, null], [52435, 53251, null], [53251, 53804, null], [53804, 54440, null], [54440, 54900, null], [54900, 55429, null], [55429, 56139, null], [56139, 56498, null], [56498, 57572, null], [57572, 57586, null]], "google_gemma-3-12b-it_is_public_document": [[0, 224, true], [224, 278, null], [278, 523, null], [523, 1024, null], [1024, 1442, null], [1442, 1915, null], [1915, 2317, null], [2317, 3244, null], [3244, 3673, null], [3673, 3993, null], [3993, 4592, null], [4592, 5064, null], [5064, 5251, null], [5251, 5615, null], [5615, 6193, null], [6193, 6946, null], [6946, 7541, null], [7541, 8140, null], [8140, 8261, null], [8261, 8517, null], [8517, 8637, null], [8637, 8708, null], [8708, 9114, null], [9114, 9579, null], [9579, 9973, null], [9973, 10314, null], [10314, 10463, null], [10463, 10985, null], [10985, 11351, null], [11351, 11704, null], [11704, 12082, null], [12082, 12687, null], [12687, 12950, null], [12950, 13045, null], [13045, 13462, null], [13462, 13750, null], [13750, 13831, null], [13831, 14616, null], [14616, 15215, null], [15215, 15472, null], [15472, 15714, null], [15714, 16265, null], [16265, 16920, null], [16920, 17228, null], [17228, 17614, null], [17614, 18026, null], [18026, 18574, null], [18574, 19585, null], [19585, 19820, null], [19820, 20278, null], [20278, 20717, null], [20717, 20826, null], [20826, 21518, null], [21518, 22265, null], [22265, 22825, null], [22825, 24978, null], [24978, 25039, null], [25039, 25568, null], [25568, 26207, null], [26207, 27069, null], [27069, 27321, null], [27321, 28089, null], [28089, 28646, null], [28646, 29973, null], [29973, 30326, null], [30326, 31374, null], [31374, 32228, null], [32228, 32802, null], [32802, 33353, null], [33353, 34237, null], [34237, 34575, null], [34575, 35241, null], [35241, 35319, null], [35319, 37045, null], [37045, 38858, null], [38858, 39586, null], [39586, 40496, null], [40496, 42507, null], [42507, 42894, null], [42894, 43584, null], [43584, 43944, null], [43944, 44346, null], [44346, 44543, null], [44543, 44855, null], [44855, 44965, null], [44965, 46045, null], [46045, 46871, null], [46871, 47079, null], [47079, 47555, null], [47555, 47674, null], [47674, 47890, null], [47890, 48473, null], [48473, 48743, null], [48743, 48959, null], [48959, 48980, null], [48980, 49012, null], [49012, 49212, null], [49212, 49519, null], [49519, 49934, null], [49934, 50432, null], [50432, 51185, null], [51185, 51339, null], [51339, 52111, null], [52111, 52435, null], [52435, 53251, null], [53251, 53804, null], [53804, 54440, null], [54440, 54900, null], [54900, 55429, null], [55429, 56139, null], [56139, 56498, null], [56498, 57572, null], [57572, 57586, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, true], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57586, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57586, null]], "pdf_page_numbers": [[0, 224, 1], [224, 278, 2], [278, 523, 3], [523, 1024, 4], [1024, 1442, 5], [1442, 1915, 6], [1915, 2317, 7], [2317, 3244, 8], [3244, 3673, 9], [3673, 3993, 10], [3993, 4592, 11], [4592, 5064, 12], [5064, 5251, 13], [5251, 5615, 14], [5615, 6193, 15], [6193, 6946, 16], [6946, 7541, 17], [7541, 8140, 18], [8140, 8261, 19], [8261, 8517, 20], [8517, 8637, 21], [8637, 8708, 22], [8708, 9114, 23], [9114, 9579, 24], [9579, 9973, 25], [9973, 10314, 26], [10314, 10463, 27], [10463, 10985, 28], [10985, 11351, 29], [11351, 11704, 30], [11704, 12082, 31], [12082, 12687, 32], [12687, 12950, 33], [12950, 13045, 34], [13045, 13462, 35], [13462, 13750, 36], [13750, 13831, 37], [13831, 14616, 38], [14616, 15215, 39], [15215, 15472, 40], [15472, 15714, 41], [15714, 16265, 42], [16265, 16920, 43], [16920, 17228, 44], [17228, 17614, 45], [17614, 18026, 46], [18026, 18574, 47], [18574, 19585, 48], [19585, 19820, 49], [19820, 20278, 50], [20278, 20717, 51], [20717, 20826, 52], [20826, 21518, 53], [21518, 22265, 54], [22265, 22825, 55], [22825, 24978, 56], [24978, 25039, 57], [25039, 25568, 58], [25568, 26207, 59], [26207, 27069, 60], [27069, 27321, 61], [27321, 28089, 62], [28089, 28646, 63], [28646, 29973, 64], [29973, 30326, 65], [30326, 31374, 66], [31374, 32228, 67], [32228, 32802, 68], [32802, 33353, 69], [33353, 34237, 70], [34237, 34575, 71], [34575, 35241, 72], [35241, 35319, 73], [35319, 37045, 74], [37045, 38858, 75], [38858, 39586, 76], [39586, 40496, 77], [40496, 42507, 78], [42507, 42894, 79], [42894, 43584, 80], [43584, 43944, 81], [43944, 44346, 82], [44346, 44543, 83], [44543, 44855, 84], [44855, 44965, 85], [44965, 46045, 86], [46045, 46871, 87], [46871, 47079, 88], [47079, 47555, 89], [47555, 47674, 90], [47674, 47890, 91], [47890, 48473, 92], [48473, 48743, 93], [48743, 48959, 94], [48959, 48980, 95], [48980, 49012, 96], [49012, 49212, 97], [49212, 49519, 98], [49519, 49934, 99], [49934, 50432, 100], [50432, 51185, 101], [51185, 51339, 102], [51339, 52111, 103], [52111, 52435, 104], [52435, 53251, 105], [53251, 53804, 106], [53804, 54440, 107], [54440, 54900, 108], [54900, 55429, 109], [55429, 56139, 110], [56139, 56498, 111], [56498, 57572, 112], [57572, 57586, 113]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57586, 0.03556]]}
|
olmocr_science_pdfs
|
2024-12-04
|
2024-12-04
|
2e14408203bf2eefba50e60f3093382e82a8e13d
|
Transformations in Information Supply
B. van Gils, H. A. Proper, P. van Bommel, Th.P. van der Weide
University of Nijmegen* Sub-faculty of Informatics, IRIS Group,
Toernooiveld 1, 6525 ED Nijmegen, The Netherlands
basvg@acm.org, erikp@acm.org, pvb@cs.kun.nl, tvdw@cs.kun.nl
PUBLISHED AS:
Abstract. In this article, we present a model for transformation of resources in information supply. These transformations allow us to reason more flexibly about information supply, and in particular its heterogeneous nature. They allow us to change the form (e.g. report, abstract, summary) and format (e.g. PDF, DOC, HTML) of data resources found on the Web. In a retrieval context these transformations may be used to ensure that data resources are presented to the user in a form and format that is apt at that time.
1 Introduction
The Web today can be seen as an information market, on which information supply meets information demand: information is offered via the Web in the form of resources, which can be accessed (sometimes at a cost) by anyone interested in these resources. Information supply can be said to be heterogeneous because:
– there are many different ways to represent information. For example using a webpage, a document, an image or some interactive form.
– there are many different formats that may be used to represent information on the Web. For example, using formats such as PDF, HTML, GIF.
The following example illustrates this heterogeneity. Suppose you are browsing the Web from a PDA over a mobile-phone connection. You are on your way to an important meeting with stockholders of your company and need some last minute information on the price of your stock and that of your most important competitors. Using your favorite search engine you find a large spreadsheet with not only the latest stock price, but also their respective history, several graphs and predictions for the near future. In itself, this is a very useful resource. However, several problems occur at this point. First of all, the document is rather large which is inconvenient because you are on a slow (and possibly buggy) connection. Secondly, it may be that your PDA does not have the proper software to view this spreadsheet. Last but not least, you may not have the time
* The investigations were partly supported by the Dutch Organization for Scientific Research (NWO).
to study a complex spreadsheet, hence the form of the resource is off too. We hypothesize that transformations may cure this type of problems, for example by integrating a "transformation broker" in the retrieval engine in such a way that resources are transformed in a desirable format before sending them back to the user. The transformations in this article are considered in the context of web resources. As such they are not particularly tailored to database transformations (see e.g. our earlier work on transformations in [1,2]).
The above mentioned forms of heterogeneity may pose problems in a retrieval setting if there is a mismatch between the user's wishes on the one hand and the form and/or format of resources on the other hand. In order to investigate the problem area more closely we have developed a conceptual model for information supply [3,4]. This model may contribute to more insights in this complex area. Furthermore it is the basis for a prototype implementation of a retrieval engine which we will discuss briefly1. The main contribution of this article is twofold. We firstly extend our model with a typing mechanism, which is a prerequisite for the second contribution: a formal model for transformations on in the information market. With transformations we will be able to deal with the form/format issues described above.
The remainder of this article is organized as follows: we start by introducing our model for information supply in Section 2. In Section 3 we formalize the (relevant) parts of this model. A more elaborate overview is presented in [3]. Section 4 formally introduces the typing mechanism that we use in our model. This typing mechanism is also the basis for Section 5 in which we discuss transformations in detail. In Section 6 we present our conclusions.
2 The model
In this section we present our model in two steps. We start out by informally introducing our model (Section 2.1) after which we constrain it by presenting its formal properties in Section 3.
2.1 Overview
Our model of information supply is based on the distinction between data and information. The entities found on the Web, which can be identified by means of a URI [6], are data resources. These data resources are "information", if and only if they are relevant with regard to a given information need as it is harbored by some user. Data resources may, at least partially, convey the same information for some information need. Hence, we define information resources to be the abstract entities that make up information supply. Each information resource has at least one data resource associated to it. Consider for example the situation in which we have two data resources: the painting Mona Lisa, and a very detailed description of this painting. Both adhere to the same information resource in the sense that a person seeking for information on 'the Mona Lisa' will consider both to be relevant.
In a way, data resources implement information resources; a notion similar to that reported in [7] where 'facts' in the document subspace are considered to be 'proof' for hypotheses in the knowledge subspace. Note that each data resource may implement the information resource in a different way. One data resource may be a "graphical representation" of an information resource whereas another data resource may be a "textual representation" of the same information resource. We define a representation to be the combination of a data resource and an information
1 For a detailed discussion on this architecture the reader is referred to [5,3]
resource, and a *representation type* to indicate exactly how this data resource implements the information resource it is associated to. Examples of representation types are: full-content, abstract, keyword-list, extract, audio-only etcetera.
As an example, consider the information resource called Mona Lisa which has two data resources associated to it. One of these resources is a photograph of this famous painting whereas another may be a very detailed description of the Mona Lisa. For the former data resource the representation type would be "graphical full-content" whereas the other would have representation type "description".
Many different types of data resources can be distinguished on the Web today, such as documents in different formats (HTML, PDF, etc.), databases and interactive Web-services. This is reflected in our model by the fact that each data resource has a *data resource type*. Furthermore, data resources may have several attributes such as a price or a measurement for its quality. Such attributes can be defined in terms of an *attribute type* and the actual value that a data resource has for this given attribute type.
Last but not least, data resources can be interrelated. The most prominent example of this interrelatedness on the Web is the notion of *hyperlinks* [8, 9], but other types of relations between data resources exist as well. Examples are: an image may be *part of* a webpage and a scientific article may *refer to* other articles.
The following summarizes our model:
- Information Resources have at least one Data Resource associated to them;
- A Representation denotes the unique combination of an Information Resource and a Data Resource;
- Representations have at least one Representation Type;
- Data Resources have at least one Data Resource Type;
- Data Resources are related via Relations with a source and a destination;
- Relations have at least one Relation Type;
- Data Resources may have attributed values which are typed;
- An Attribute denotes the combination of a Data Resource and a Data Value;
- Attributes have at least one Attribute Type.
3 Formalization of resource space
As discussed in the previous sections, *resource space* consists of two types of resources: *information resources* and *data resources*. Information resources form an abstract landscape presenting the "semantics"; the "things we know something about". Data resources, on the other hand, are information that is "physically" stored in one way or the other. The *representations* relation, as discussed above, forms a bridge between these two worlds. Furthermore, in the data resource world we distinguish two types of relations: *attributions*, which couple a data value to a data resource, and *relations* between data resources. Formally, the basic concepts of our model are: information resources, representations, data resources, attributions and relations. They are represented by the following sets:
<table>
<thead>
<tr>
<th>Information resources: $\mathcal{IR}$</th>
<th>Representations: $\mathcal{RP}$</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data resources: $\mathcal{DR}$</td>
<td>Attribution: $\mathcal{AT}$</td>
</tr>
<tr>
<td>Data values: $\mathcal{DV}$</td>
<td>Relations: $\mathcal{RC}$</td>
</tr>
</tbody>
</table>
Because we consider these to be elementary (for example, it does not make sense if something is a relation and at the same time also a data resource), these sets must be disjoint:
**Axiom 1 (Disjoint Base Sets)** \( TR, RP, DR, DV, AT, RL \) are disjoint sets
Collectively, the data values and data resources are referred to as data elements:
\[
\mathcal{DL} \triangleq DR \cup DV
\]
Attributions connect data values to their respective data resources, and relations are used to interconnect data resources. Hence, attributions and relations form all possible connections between the data elements. Let \( CN \) be the set of all these connections:
\[
CN \triangleq RL \cup AT
\]
The sources and destinations of connections between data elements are yielded by the functions \( Src, Dst : CN \rightarrow \mathcal{DL} \) respectively. Since these are total functions it follows that if a \( c \in CN \) exists then its source and destination can not be void. Even more, we state that the source and destination can not be the same element:
**Axiom 2 (Source and Destination of connections)**
\[
c \in CN \implies \exists e_1, e_2 \in \mathcal{DL} [\text{Src}(c) = e_1 \land \text{Dst}(c) = e_2 \land e_1 \neq e_2]
\]
The destination of an attribution should be a data value:
**Axiom 3 (Attribute Values)**
\[
\forall a \in AT [\text{Src}(a) \in DR \land \text{Dst}(a) \in DV]
\]
Similarly, the destination of a relation should be a data resource:
**Axiom 4 (Relations)**
\[
\forall r \in RL [\text{Src}(r) \in DR \land \text{Dst}(r) \in DR]
\]
As an abbreviation we introduce:
\[
s \overset{c}{\leadsto} d \triangleq \text{Src}(c) = s \land \text{Dst}(c) = d
\]
\[
s \overset{c}{\leadsto} d \triangleq \exists e [s \overset{e}{\leadsto} d]
\]
For example, \( a.zip \overset{c}{\leadsto} b.doc \) denotes that \( a.zip \) and \( b.doc \) are related via some relation (for example, the document may be part of the ZIP archive). Another example is \( x.html \overset{c}{\leadsto} \text{UTF-8} \), which denotes that \( x.html \) uses the UTF-8 encoding.
Recall that a representation is the combination of an information resource and a data resource. They form the bridge between the abstract world of information resources and the concrete world of data resources. Hence we define \( IRes : RP \rightarrow TR \) to be a function yielding the information resource that is associated to a representation and \( DRes : RP \rightarrow DR \) to be a function providing the data resource associated to a representation.
In sum, we define resource space to be defined by the following signature:
\[
\Sigma_r \triangleq \langle TR, RP, DR, DL, AT, DV, IRes, DRes, Src, Dst \rangle
\]
4 Typing mechanism for descriptive elements
Before we are able to discuss transformations on data resources, we first need to introduce a typing mechanism on resource space. This typing mechanism allows us to limit the applicability of transformations to specific types of resources. In this section we therefore aim to extend resource space \( \Sigma_r \) with a typing mechanism.
All elements in resource space can be typed. Let \( \mathcal{RE} \) therefore be the set of all elements in resource space:
\[
\mathcal{RE} \triangleq DR \cup RP \cup DR \cup RL \cup AT \cup DV
\]
The resource space elements form basis for a uniform typing mechanism. Data resources are allowed to have a type that is either “basic” or “complex”. This is explained in more detail in Section 4.2.
Let \( TP \) to be the set of all types and \( \text{HasType} \subseteq \mathcal{RE} \times TP \) be the relation for typing descriptive elements in our model. Our typing mechanism is inspired by abstract data types as introduced in e.g. [10]. This implies that we can perform operations on the instances of these types. Note that such a strategy can deal with both static as well as dynamic resources. For example, the approach as described in [11] actually uses many-sorted algebra’s to formalize the behavior of objects as used in object-oriented approaches. In the case of data resources, examples of these operations/methods are:
- give me the first byte,
- give me the \( n \)’th character,
- (in the case of an XML document) give me the first node in the DOM-tree.
4.1 Types and population
Given some element from resource space, we can use \( \text{HasType} \) to determine the set of types of this element. For example, the types of a given file may be XML, SGML and file or, the type of a relation may be “part of” or “refers to”. Conversely, we can also determine the set of elements of a given type. Formally, we use the functions \( \tau \) and \( \pi \) respectively to yield these sets:
\[
\tau(e) \triangleq \{ t \mid e \text{ HasType } t \} \quad \pi(t) \triangleq \{ e \mid e \text{ HasType } t \}
\]
These functions may be generalized to sets of elements and types respectively:
\[
\tau(E) \triangleq \bigcup_{e \in E} \tau(e) \quad \pi(T) \triangleq \bigcup_{t \in T} \pi(t)
\]
If \( X \) is one of the base sets, such as \( RL, DR \), then we will abbreviate \( \tau(X) \) as \( X_\tau \).
Using the definitions of \( \tau \) it follows that an element may have more then one type. An example from the domain of data resources illustrates this. Suppose that \( E = \{1.\text{htm}, 2.\text{xml}\} \) such that 1.\text{htm} HasType HTML, 1.\text{htm} HasType XML and 2.\text{xml} HasType XML. In this case \( \tau(E) = \{\text{HTML}, \text{XML}\} \). We now have:
\[
\pi(\text{HTML}) = \{1.\text{htm}\} \quad \tau(\pi(\text{HTML})) = \{\text{HTML}\}
\]
\[
\pi(\text{XML}) = \{1.\text{htm}, 2.\text{xml}\} \quad \tau(\pi(\text{XML})) = \{\text{HTML}, \text{XML}\}
\]
This example also shows that \( \tau(\pi(\text{HTML})) \subset \tau(\pi(\text{XML})) \). We will get back to this when we discuss subtyping in Section 4.3.
We assume that all elements have a type:
Axiom 5 (Total typing) \( \tau(e) \neq \emptyset \)
Conversely, in our model we presume types to exist only when they have a population:
Axiom 6 (Existential typing) \( \pi(t) \neq \emptyset \)
In the approach we take, typing of resource space is derived from the available resources. In other words, a new type of resources can only be introduced to the model if and only if instances (data elements) of this (new) type exist. This is particularly convenient since our model has to “fit” on an existing situation: the Web. In the case of database design, for example, the opposite holds: first the schema is defined, then it is populated with instances.
The partitioning of elements from resource space over \( IR, RP, DR, DV, AT, RL \) should be obeyed by their types as well:
Axiom 7 \( IR_\tau, RP_\tau, DR_\tau, DV_\tau, AT_\tau, RL_\tau \) form a partition of \( TP \)
### 4.2 Complex data resources
Data resources may depend on the existence of other elements from resource space. For example, some data resource may be constructed in terms of other data resources, and/or it may have some data value associated to it as an attribute. A data resource that is dependent on the existence of other elements is called a complex data resource.
In the case of a data resource which is considered to be (partially) constructed by means of other data resources, we are essentially dealing with a subset of the relations in \( RL \) which we regard as being compositions. Let therefore \( CM \subseteq RL \) be the set of relations that are considered to be compositions of complex data resources.
The compositions, in conjunction with the attributions, are the only ways of constructing complex data resources. The compositions and attributions used to construct the complex data resources are referred to as accessors; they offer access to the underlying composing elements. We define the set of accessors formally as:
\[
AC \triangleq CM \cup AT
\]
The types of complex data resources, the underlying data resources/values, and the composition/attribution relations between them, have a special relationship: at the instance level, accessors can be thought of as “handles” which provide access to the that data elements were used to create the instance of a complex type. At the typing level, these “handles” are reflected by the accessor types. For example, a ZIP-file may have an accessor (with type “payload”), which offers access to the files that were used to create this specific ZIP archive.
The construction of instances of complex types is restricted in the sense that cyclic behavior is forbidden: it is considered illegal if an instance \( a \) is used to construct \( b \) while at the same time \( b \) is used to construct \( a \):
Axiom 8 (Acyclic construction) The relation \( R \) defined as \( e_1 R e_2 \triangleq \exists a \in AC \left[ e_1 \xrightarrow{a} e_2 \right] \) is acyclic.
Not all types of complex data resources, such as "ZIP-file" and "multi-part E-mail", will have a "payload". For example, in the case of a complex type such as "postal address" it does not make sense to use an accessor of type "payload" on its instances. This kind of restriction must be reflected at the typing level, and pertains to the fact that only instances of a specific type may be involved in an accessor. To formally represent this, we introduce the relation:
\[ \sim \subseteq TP \times \mathcal{A}_r \times TP \]
If \( s \sim t \), then the intuition is that complex type \( s \) has, via accessor type \( u \), at its base the type \( t \).
As an example, let \( t_1 = \text{ZIP} \), \( a = \text{’payload’} \) and \( t_2 = \text{file} \), then \( t_1 \stackrel{a}{\sim} t_2 \) represents the fact that ZIP-files have a payload consisting of files.
Using the definition of \( \sim \), we define the set of complex types to be:
\[
TP_c \triangleq \left\{ t_1 \in TP \mid \exists a \in \mathcal{A}_r, t_2 \in TP \left[ t_1 \stackrel{a}{\sim} t_2 \right] \right\}
\]
At the instance level, accessors should behave as stipulated at the type level:
**Axiom 9 (Correct types)**
\[ e_1 \stackrel{a}{\sim} e_2 \implies \exists t_1 \in \tau(e_1), t_2 \in \tau(e_2) \left[ t_1 \stackrel{a}{\sim} t_2 \right] \]
The set of accessors that is associated to a complex type is defined by:
\[ \text{Acc}(t_1) \triangleq \left\{ t \in \mathcal{A}_r \mid \exists t_2 \left[ t_1 \sim t_2 \right] \right\} \]
This definition can be generalized to the instance level:
\[ \text{Acc}(e) \triangleq \bigcup_{t \in \tau(e)} \text{Acc}(t) \]
Note that it may be the case that some of the accessor types in an instance of a complex type are unused. For example, not every ZIP file has a comment or a password associated to it.
If two complex types have the same set of accessor types, such that the types at the base of these accessor types are the same, then the two complex types are really the same:
**Axiom 10 (Equality of Complex Types)** If \( \text{Acc}(s_1) = \text{Acc}(s_2) \), then:
\[ \forall u \in \text{Acc}(s_1), t \in TP \left[ s_1 \sim t \iff s_2 \sim t \right] \implies s_1 = s_2 \]
As an example of how the accessor mechanism works in practice, consider the following example: suppose \( x.zip \) is a ZIP-file, while it’s payload consists of three files, \( a.doc, b.ps \) and \( c.pdf \). They can be accessed via their respective accessors \( a_1, a_2 \) and \( a_3 \), which all have accessor type "payload". Note that this accessor type is really a composition (CM)! Furthermore, there is a comment and a password attached to the ZIP-file which are accessed via accessors \( a_4 \) and \( a_5 \).
which have accessor types “comment” and “password” respectively. These accessor types originate from attributions. More formally:
\[
\pi(DR) = \{x.zip, a.doc, b.ps, c.pdf\}
\]
\[
\pi(DR) = \{ZIP, DOC, PS, PDF, file\}
\]
\[
\pi(DV) = \{"some comment", "secret"\}
\]
\[
\pi(DT) = \{String\}
\]
\[
\pi(CM) = \{a_1, a_2, a_3\}
\]
\[
\pi(CM) = \{"payload"\}
\]
\[
\pi(AT) = \{a_4, a_5\}
\]
\[
\pi(AT) = \{"comment", "password"\}
\]
Note that for \(a \in \{a_1, a_2, a_3\}\) it holds that ZIP \(\rightarrow file^2\). Similarly, for \(a \in \{a_4, a_5\}\) it holds that ZIP \(\rightarrow String\).
Figure 1 provides a graphical depiction of the above sketched situation. The left-hand side of the figure is at the instance level, whereas the right-hand side is at the typing level.
\[
\text{Fig. 1. Accessors}
\]
\[
\text{4.3 Subtyping}
\]
We assume the existence of subtyping. Let \(\text{SubOf} \subseteq TP \times TP\) therefore define a subtyping relationship, where \(s \text{ SubOf } t\) indicates that type \(s\) is a subtype of, or equal to type \(t\). Based on this definition, we introduce the notion of proper subtypes:
\[
s \text{ SubOf } t \triangleq s \text{ SubOf } t \land \neg t \text{ SubOf } s
\]
We presume \(\text{SubOf}\) to be transitive, reflexive and antisymmetric:
**Axiom 11 (Behavior of SubOf)**
\[
t \in TP \implies t \text{ SubOf } t
\]
\[
t \text{ SubOf } s \land s \text{ SubOf } t \implies t = s
\]
\[
s \text{ SubOf } t \land s \text{ SubOf } u \implies s \text{ SubOf } u
\]
\footnote{The notion of subtyping is introduced in Section 4.3.}
From this we can prove:
**Lemma 1** SubOf is irreflexive, asymmetric and transitive
At the instance level, if \( s \text{ SubOf } t \) then the population of \( s \) must be a subset of, or equal to the population of \( t \):
**Axiom 12 (Population and SubOf)**
\[ s \text{ SubOf } t \implies \pi(s) \subseteq \pi(t) \]
From this we can prove that:
**Lemma 2** \( s \text{ SubOf } t \implies \pi(s) \subseteq \pi(t) \)
For example, if XML SubOf SGML and \( x \in \pi(\text{XML}) \) then Lemma 2 states that also \( x \in \pi(\text{SGML}) \). Recall that, at the instance level, the type of a resource can be seen as the interface with which instances can be accessed. Hence, an instance with type XML can also be accessed via an “SGML-interface”.
If a complex type has a subtype then the accessor types of the supertype are inherited:
**Axiom 13 (Inheritance of accessor types)**
\[ s_1 \text{ SubOf } s_2 \implies \text{Acc}(s_1) \subseteq \text{Acc}(s_2) \]
This axiom forbids the situation that a type with 2 accessor types is a subtype of another type with 3 accessor types (the converse is allowed, and is akin to specialization in object-orientation).
Types that are at the base of a specific accessor type (in the context of a single complex type) should be subtypes:
**Axiom 14 (Subtyping of accessor bases)**
\[ s_1 \text{ SubOf } t_1 \land s_1 \text{ SubOf } t_2 \implies t_1 \text{ SubOf } t_2 \]
Even more, the set of types that are at the base of an accessor type comprises all relevant super types:
**Axiom 15 (Inclusion of super types)**
\[ s_1 \text{ SubOf } t_1 \land s_1 \text{ SubOf } t_2 \implies s_1 \subseteq t_2 \]
If a complex type has a subtype then the underlying base types must obey this subtyping as well:
**Axiom 16 (Base types obey subtyping)**
\[ s_1 \text{ SubOf } s_2 \land s_1 \text{ SubOf } t_1 \land s_2 \text{ SubOf } t_2 \implies t_1 \text{ SubOf } t_2 \]
From the above Axiom, in combination with Axiom 10, it follows that if two complex types are proper subtypes, then there is at least one accessor type whose base types show this proper subtyping:
**Lemma 3** \( s_1, s_2 \in TP_c \land s_1 \text{ SubOf } s_2 \implies \exists t_1, t_2 \left[ t_1 \text{ SubOf } t_2 \land t_1 \text{ SubOf } t_2 \right] \)
4.4 Typed resource space
In sum, we define a typed resource space to be defined by the following signature:
\[ \Sigma ^+ _r \triangleq (\Sigma _r, TP, CM, \text{HasType}) \]
5 Transformations
In this section we introduce transformations, a way to change the nature / structure of instances. These transformations can be very used in practice to solve several problems. For example:
- Suppose we have an image in EPS file that we want to view. Unfortunately we don’t have a viewer for this file-type. We do have a viewer for JPEG files, though. By means of a transformation we may be able to transform the EPS file to JPEG and thus access the information we need.
- Managers of large organizations often have to read many lengthy reports. Because of time constraints it is not always possible to read all these reports. Again, transformations may help. Transformations exists to generate abstracts of these documents.
In other words, transformations help us to have a more flexible view on the information landscape. In generl, one can distinguish between an extensional database and intentional database [12,13]. The extensional database corresponds to the a set of basic facts known about the world, whereas the intentional database represents the facts that may be derived from the extensional database by applying inference rules. The transformations can be regarded as inference rules on the extensional database (information supply as we know it), resulting in a larger intentional database.
The remainder of this section is organized as follows. In Section 5.1 we define what transformations are and show their basic properties. Section 5.2 elaborates and presents complex transformations.
5.1 Basic Properties
Recall that IRes finds the unique information resource associated to a representation, and that DRes finds the unique data resource associated to a representation. Essentially, a representation is information represented on a medium, and the representation type expresses how / to what extent this is done.
As was stated before, with transformations we can transform data resources. This paper does not present a language for specifying what a specific transformation does / a language for composing transformations. We focus on general properties of transformations and, hence, view them as a “black box” for the time being.
Let \( TR \) be the set of all transformations. The semantics of a transformation \( T \in TR \) is given by the function:
\[ \text{SEM} : TR \rightarrow (DR \rightarrow DR) \]
In other words, transformations transform a representation to another. As an abbreviation, let \( \overline{T} \triangleq \text{SEM}(T) \), \( T \in TR \). Furthermore, let \( i \vdash d \) denote that data resource \( d \) is associated to information resource \( i \) via some representation:
\[
i \vdash d \triangleq \exists r \in RP \; [\text{Res}(r) = i \land \text{DRes}(r) = d]
\]
If a data resource is transformed, then the resulting data resource is associated to the same information resource as the original information resource.
**Axiom 17 \( (IR \text{ neutral transformations}) \)**
\[
i \vdash d \land \overline{T}(d) = d' \implies i \vdash d'
\]
Any given transformation has a fixed input and output for which it is defined, similar to the notion of mathematical functions having a domain and a range: Input, Output : \( TR \rightarrow \tau(DR) \). Let \( t \xrightarrow{T} u \) denote the fact that transformation \( T \in TR \) can be applied on instances of type \( t \) and results in instances of type \( u \):
\[
t \xrightarrow{T} u \triangleq \text{Input}(T) = t \land \text{Output}(T) = u\]
Any given transformation is only defined for all instances that are of the correct input-format. Even more so, it can only produce instances of its output-format:
**Axiom 18 (I/O of Transformations)**
\[
\text{if } t \xrightarrow{T} u \text{ then } T : n(t) \supseteq n(u)
\]
This allows us to define how a transformation \( T \) can be applied to a set of data resources. Let \( E \subseteq DR \) be a set of data resources. Then:
\[
\overline{T}(E) \triangleq \{ e \mid e \in E \land e \notin \text{Input}(T) \} \cup \left\{ \overline{T}(e) \mid e \in E \land e \in \text{Input}(T) \right\}
\]
Another property of transformations is the fact that they are transitive:
**Axiom 19 (Transitivity of Transformations)**
\[
e \xrightarrow{T_1} f \land f \xrightarrow{T_2} g \implies \exists T_3 \left[ e \xrightarrow{T_3} g \land T_3 = T_1 \circ T_2 \right]
\]
This property can be used to transform data resources into an appropriate format even if there is no 1-step transformation is available. It is, for example, possible to generate an abstract of a large ASCII-file and transform that to PS by sequencing the two transformations.
### 5.2 Complex Transformations
In the previous section we presented a framework for transformations and showed how transformations can be composed by sequencing them using the \( \circ \) operator. In this section we discuss a more complex way of composing transformations, relying heavily on the accessor types presented in previous sections. We define a transformation to be complex if the transformation operates on instances that were used to create an instance of a complex type (that is, instances at the base of an instance of a complex type). There are two types of complex transformations which, like all transformations, may be sequenced using the \( \circ \) operator.
The first complex transformation is used to remove an accessor and the instance(s) at its base. For example, it may be desirable to remove a comment from a ZIP-file, or to remove an attachment from an E-mail. Such transformation:
- takes an instance with a complex type as input;
- removes a specified accessor and its base from an instance with a complex type;
- leaves other accessors (and their bases) untouched.
More formally, Let $e$ be an instance with a complex type and $a \in \text{Acc}(\tau(e))$:
$$\varrho_a(e) = e' \triangleq e' \bowtie a = \emptyset \land \forall_{b \neq a} [e \bowtie b = e' \bowtie b]$$
In the above definition we have used the following shorthand notation:
$$c \bowtie t \triangleq \{ d \mid c \bowtie_d d \land a \in \pi(t) \}$$
The intuition behind this shorthand is that $c \bowtie ad$ retrieves all data elements that are used in constructing complex data resources $c$ via accessors of type $t$.
This type of transformations can be performed on each instance with a complex type, since such an instance must have at least one accessor. If the last accessor of an instance is removed then $\varrho$ is said to destruct the instance.
**Axiom 20 (Existence of $\varrho$)**
If $t \in \text{TP}_c$, $a \in \text{Acc}(T)$ then $\exists T \in \text{TR} [t \xrightarrow{T} t \bowtie \overline{T} = \varrho_a]$.
The second class of complex transformations does a little more work; they are deep transformations in the sense that instances at the base of a complex type are transformed. For example, all DOC files in a ZIP archive may be transformed to PDF. These transformations:
- takes an instance with a complex type as input, and returns an instance with a (possibly different) complex type;
- Transform the instances at the base of an accessor;
- leave other accessors (and their bases) untouched.
More formally, Let $e$ be an instance of a complex type, $a \in \text{Acc}(\tau(e))$ and $T \in \text{TR}$:
$$\alpha_{a,T}(e) = e' \triangleq e' \bowtie a = T(e \bowtie a) \land \forall_{b \neq a} [e \bowtie b = e' \bowtie b]$$
These transformations are defined for all types $t_1, t_2$ as long as they have the same accessor types. Even more, transformation $T$ must at least be defined for the instances at the base of the specified accessor:
**Axiom 21 (Existence of $\alpha$)**
If $\text{Acc}(t_1) = \text{Acc}(t_2)$ and $a \in \text{Acc}(t_1)$ and $\exists b_1, b_2 [t_1 \xrightarrow{a} b_1 \land t_2 \xrightarrow{a} b_2 \land b_1 \xrightarrow{T} b_2]$ then $\exists T' \in \text{TR} [t_1 \xrightarrow{T'} t_2 \bowtie \overline{T'} = \alpha_{a,T}]$.
To illustrate how such a deep transformation can be used to transform an instance from complex type $t_1$ to complex type $t_2$, consider the following situation. $t_1$ is the format for an E-mail for which the body is in UTF-8 encoding, and $t_2$ has its body in UTF-16 encoding. That is, $t_1$ has an accessor with type UTF-8 and some text formatted accordingly at its base and the same accessor has, in the context of type $t_2$, accessor type UTF-16. If $T$ is a transformation capable of transforming text in UTF-8 encoding to UTF-16 encoding then Axiom 21 dictates that a $T''$ must exist such that $t_1 \xrightarrow{T'} T_2$.
5.3 Example
In this section we present an example that relies on Axioms 19, 20 and 21. Consider the following:
Let backup.zip be a ZIP archive. Two files (report.doc and letter.doc) form the payload of this archive. Also, a comment ("backup") and a password ("secret") are associated to it. In other words:
\[
\begin{align*}
\tau(\text{backup.zip}) &= \text{ZIP} \\
\text{Acc}(\text{backup.zip}) &= \{\text{payload, comment, password}\} \\
\text{backup.zip} \times \text{payload} &= \{\text{report.doc, letter.doc}\} \\
\text{backup.zip} \times \text{comment} &= \text{"backup"} \\
\text{backup.zip} \times \text{password} &= \text{"secret"}
\end{align*}
\]
Now, let \( T_1 \) be a transformation with \( \text{Input}(T) = \text{DOC} \) and \( \text{Output}(T) = \text{PDF} \). Then, \( \alpha_{\text{payload}} \circ T_1 \) is a transformation that transforms the documents in the payload of any ZIP archive to PDF. Let \( \alpha_{\text{password}} \) be a transformation that removes the password of a ZIP archive.
If we want to transform backup.zip such that the documents in its payload are transformed to PDF and its password is removed then we can achieve this as follows:
\[
\begin{align*}
T &= \alpha_{\text{payload}} \circ T_1 \circ \alpha_{\text{password}} \\
T \circ \text{(backup.zip)} &= \text{new.zip}
\end{align*}
\]
The result of this transformation is a new archive new.zip such that:
\[
\begin{align*}
\tau(\text{new.zip}) &= \text{ZIP} \\
\text{Acc}(\text{new.zip}) &= \{\text{payload, comment}\} \\
\text{new.zip} \times \text{payload} &= \{\text{report.pdf, letter.pdf}\} \\
\text{new.zip} \times \text{comment} &= \text{"backup"}
\end{align*}
\]
5.4 Open issues
In this section we have presented a theoretical framework for transformations and their basic properties. This framework allows us to reason more efficiently about the information that is supplied to us via the Web. In [5] we have presented a retrieval architecture called Vimes that makes use of these transformations in a retrieval-setting. The main idea behind Vimes is that data resources on the Web may be transformed in a format suitable for the user.
What is missing still, though, is a mechanism to examine the effects of transformations, and transformation paths in particular. Suppose a transformation from \( p \) to \( q \) is needed, and two sequences of transformations are possible to achieve this. Which sequence is "best"? Based on which properties / quality attributes can such a decision be made? Devising a mechanism is part of future research.
6 Conclusion
In this article we set out to do two things: present a formal model for information supply, the totality of information available to us via the Web, and present a framework of transformations to add flexibility to this model.
The basic model stems from earlier work [3, 4] with basic elements: data resource, information resource, representation, value, attribution and relation. In this article we extended it with an extensive typing mechanism with an explicit distinction between basic and complex types. An instance is said to be complex if other instances (data resources or attributed values) were used to construct it. An example is a ZIP-file with several documents, a password and a comment associated to it.
For our transformation framework we defined that transformations work on data resources. A distinction is made between the semantics of a transformation (pertaining to its signature), and its actual application on real instances. Transformations have a fixed input type and output type similar to mathematical functions having a domain and a range.
We distinguish two types of transformations: transformations on instances of simple types and deep transformations (which operate on instances used to construct the instance of a complex type). Furthermore, a property of all transformations is that they may be transitively nested.
Even though our model covers both “simple” and “complex” transformations, much work needs to be done still. First of all, the effects of transformations must be studied still. That is, by performing a transformation on a data resource it’s (perceived) quality may change. Even more so, if a transformation from one type to another may be achieved via two possible sequences of transformation, a choice must be made: which one is the best, and why? Last but not least, a language to constrain our model and transformations in this model must be developed still. Last but not least, we are currently working on an implementation of our transformation framework and refer the interested reader to [5, 3] for details.
References
|
{"Source-Url": "https://repository.ubn.ru.nl/bitstream/handle/2066/60336/60336.pdf?sequence=1", "len_cl100k_base": 9689, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 32851, "total-output-tokens": 11526, "length": "2e13", "weborganizer": {"__label__adult": 0.0003695487976074219, "__label__art_design": 0.0008573532104492188, "__label__crime_law": 0.0005803108215332031, "__label__education_jobs": 0.004154205322265625, "__label__entertainment": 0.0001819133758544922, "__label__fashion_beauty": 0.00026988983154296875, "__label__finance_business": 0.0010824203491210938, "__label__food_dining": 0.0005130767822265625, "__label__games": 0.0006442070007324219, "__label__hardware": 0.0009059906005859376, "__label__health": 0.0010547637939453125, "__label__history": 0.0005507469177246094, "__label__home_hobbies": 0.00016617774963378906, "__label__industrial": 0.000637054443359375, "__label__literature": 0.0012254714965820312, "__label__politics": 0.0004048347473144531, "__label__religion": 0.0005755424499511719, "__label__science_tech": 0.34375, "__label__social_life": 0.00021922588348388672, "__label__software": 0.044647216796875, "__label__software_dev": 0.59619140625, "__label__sports_fitness": 0.0002244710922241211, "__label__transportation": 0.0006136894226074219, "__label__travel": 0.00025534629821777344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40533, 0.01476]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40533, 0.82388]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40533, 0.85362]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2810, false], [2810, 6387, null], [6387, 9648, null], [9648, 12342, null], [12342, 15519, null], [15519, 18437, null], [18437, 21160, null], [21160, 22748, null], [22748, 25019, null], [25019, 27551, null], [27551, 30728, null], [30728, 33735, null], [33735, 36534, null], [36534, 40533, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2810, true], [2810, 6387, null], [6387, 9648, null], [9648, 12342, null], [12342, 15519, null], [15519, 18437, null], [18437, 21160, null], [21160, 22748, null], [22748, 25019, null], [25019, 27551, null], [27551, 30728, null], [30728, 33735, null], [33735, 36534, null], [36534, 40533, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40533, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40533, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2810, 2], [2810, 6387, 3], [6387, 9648, 4], [9648, 12342, 5], [12342, 15519, 6], [15519, 18437, 7], [18437, 21160, 8], [21160, 22748, 9], [22748, 25019, 10], [25019, 27551, 11], [27551, 30728, 12], [30728, 33735, 13], [33735, 36534, 14], [36534, 40533, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40533, 0.0119]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
cde34c21bcd95ae58632ed9a286cb6e0d7ce516e
|
Advanced large language models and visualization tools for data analytics learning
Jorge Valverde-Rebaza*, Aram González, Octavio Navarro-Hinojosa and Julieta Noguez
Tecnologico de Monterrey, School of Engineering and Sciences, Monterrey, NL, Mexico
Introduction: In recent years, numerous AI tools have been employed to equip learners with diverse technical skills such as coding, data analysis, and other competencies related to computational sciences. However, the desired outcomes have not been consistently achieved. This study aims to analyze the perspectives of students and professionals from non-computational fields on the use of generative AI tools, augmented with visualization support, to tackle data analytics projects. The focus is on promoting the development of coding skills and fostering a deep understanding of the solutions generated. Consequently, our research seeks to introduce innovative approaches for incorporating visualization and generative AI tools into educational practices.
Methods: This article examines how learners perform and their perspectives when using traditional tools vs. LLM-based tools to acquire data analytics skills. To explore this, we conducted a case study with a cohort of 59 participants among students and professionals without computational thinking skills. These participants developed a data analytics project in the context of a Data Analytics short session. Our case study focused on examining the participants’ performance using traditional programming tools, ChatGPT, and LIDA with GPT as an advanced generative AI tool.
Results: The results shown the transformative potential of approaches based on integrating advanced generative AI tools like GPT with specialized frameworks such as LIDA. The higher levels of participant preference indicate the superiority of these approaches over traditional development methods. Additionally, our findings suggest that the learning curves for the different approaches vary significantly. Since learners encountered technical difficulties in developing the project and interpreting the results. Our findings suggest that the integration of LIDA with GPT can significantly enhance the learning of advanced skills, especially those related to data analytics. We aim to establish this study as a foundation for the methodical adoption of generative AI tools in educational settings, paving the way for more effective and comprehensive training in these critical areas.
Discussion: It is important to highlight that when using general-purpose generative AI tools such as ChatGPT, users must be aware of the data analytics process and take responsibility for filtering out potential errors or incompleteness in the requirements of a data analytics project. These deficiencies can be mitigated by using more advanced tools specialized in supporting data analytics tasks, such as LIDA with GPT. However, users still need advanced programming...
1 Introduction
Artificial Intelligence (AI) is permeating an ever-growing array of domains within daily life, and its utilization is on the rise in professional contexts such as healthcare (Alhashmi et al., 2024), marketing (Haleem et al., 2022), education (Chen et al., 2020; Zhang and Aslan, 2021), and beyond. AI tools in education have revolutionized the educational landscape by providing personalized learning experiences and assisting in administrative tasks such as assessment and the customization of instructional strategies. Thus, from intelligent tutoring systems to chatbots and virtual assistants, AI tools in education enhance learning experiences by fostering efficiency, adaptability, and inclusivity (Laupichler et al., 2022; Srinivasan, 2022; Wolters et al., 2024).
Programming education has made significant advancements in recent decades. Once perceived as a skill limited to a select few with strong computational thinking competencies, programming has evolved into a critical tool for tackling complex real-world challenges, and driving innovation (Nouri et al., 2020). As a result, proficiency in programming has become indispensable for success across various sectors, especially in the business domain (Yilmaz and Yilmaz, 2023), proving its resilience even in global crises such as the COVID-19 pandemic (Pesonen and Hellas, 2022). This growing recognition of the importance of programming skills has led to their inclusion in university and continuing education courses.
Despite the increasing interest in programming education, learning to program remains a hard, and intricate endeavor for many individuals. Consequently, a considerable number of learners discontinue their learning journey before achieving proficiency (Rouhani et al., 2022; Saqr and López-Pernas, 2024). AI tools effectively address challenges such as the requirement for comprehensive guidance and support, the complexities of debugging code errors, and, most crucially, the comprehension of underlying concepts. Despite their capability, these challenges persist (Pedro et al., 2019).
The introduction of ChatGPT in November 2022 marked a pivotal moment in the landscape of AI tools, marking a clear delineation between the pre- and post-eras of AI tools (OpenAI, 2022). ChatGPT, as an application of Large Language Models (LLMs), has captivated the world with its remarkable capability to execute highly intricate tasks and its notable aptitude for engaging in natural conversation. This includes seamlessly responding to user inquiries and providing feedback, stimulating ongoing dialogue through continuous interaction. Such capabilities distinguish ChatGPT from previous AI tools, offering users a uniquely immersive experience (Rospigliosi, 2023; Mai et al., 2024). Thus, ChatGPT shaped and popularized generative AI tools, encompassing platforms such as Google Bard, Falcon, Cohere, Llama, Bing Chat, Gemini, and others.
In the realm of teaching and learning, the emergence of ChatGPT and other generative AI tools has elicited diverse perspectives among educators, as their potential applications have the capacity to revolutionize existing educational methodologies. Thus, in <2 years since these technologies became widely accessible, numerous studies have already explored their opportunities and threats (Mai et al., 2024), significance and impact (Kasici et al., 2023), ethical implications (Vaccino-Salvadore, 2023), risk factors (Morales-Garcia et al., 2024), and other aspects.
Due to its ability to generate content, define terms, and serve as a programming assistant, ChatGPT and other generative AI tools have the potential to contribute significantly to the process of teaching and learning programming skills in ways that previous chatbots could not achieve (Yilmaz and Yilmaz, 2023; da Silva et al., 2024). Furthermore, generative AI tools can play a significant role in teaching and learning more advanced computational skills, which typically demand higher levels of abstraction or computational thinking capacity, such as building data analytics solutions (Ellis and Slade, 2023; Bringula, 2024; Xing, 2024) and, even more, helping to understand what is being programmed (Nam et al., 2024).
Despite the advantages that potentially position ChatGPT and other generative AI tools as technologies that democratize support for teaching and learning programming and data analytics skills, new challenges arise, especially when instructing learners who lack computational thinking competencies. Therefore, in this work, we investigate how the utilization of technologies that integrate generative AI tools directly into learners’ data analytics projects can support the learning process of programming and data analytics skills in contrast to the traditional use of generative AI tools.
For this study, we employ LIDA (Dhiba, 2023), a novel tool designed to comprehend the semantics of data to set pertinent visualization objectives and produce visualization specifications, infographics, and data narratives. LIDA can be used with various LLM providers, including OpenAI, Azure OpenAI, PalM, Cohere, and Huggingface, allowing for seamless incorporation into the user’s data analytics projects. This approach simplifies knowledge to properly configure this connection via API. There is a significant opportunity for generative AI tools to improve their performance, providing accurate, complete, and convincing results for data analytics projects, thereby increasing user confidence in adopting these technologies. We hope this work underscores the opportunities and needs for integrating advanced LLMs into educational practices, particularly in developing computational thinking skills.
KEYWORDS
ChatGPT, data analytics learning, generative AI tools, programming skills development, large language models in education, educational innovation, higher education, professional education
programming by leveraging natural language prompts to generate code snippets that are effortlessly integrated into the existing codebase. This approach enables learners to concentrate more on crafting solutions for their projects rather than delving into the intricate details of programming. This paper aims to provide a perspective into how educators can leverage LIDA, or similar technologies, in conjunction with generative AI tools to enhance learning outcomes related to programming and data analytics skills. This is particularly valuable in contexts where learners do not yet possess advanced computational thinking abilities.
The structure of this article is organized as follows: Section 2 provides a comprehensive review of the existing literature on innovation in education focusing on the use of tools based on LLMs. Section 3 details the methodology employed in this study, including a thorough description of the case study utilized. Section 4 presents the findings from our case study, incorporating an exploratory analysis of the collected data. Finally, Section 5 concludes with a discussion of our findings, highlighting the implications and potential impact of this research.
2 Background and literature
In this section, we present the evolution of AI tools in education, focusing on tools that facilitate teaching and acquiring computational thinking skills, particularly those related to data analytics.
2.1 AI for programming education
Effective learning methods in programming education can enhance how students learn and interact with computer programming and coding environments. These methods encourage learners to progress further and embark on the development of data analytics and data science projects (Saqr and López-Pernas, 2024). The integration of AI into these methodologies can significantly enhance this process. Popenici and Kerr (2017) reviewed AI’s potential impact in higher education, noting its benefits, such as augmenting human capabilities, personalizing learning, and supporting skill development in critical thinking and problem-solving. Authors also highlighted risks, including educator replacement, bias reinforcement, job displacement, loss of human interaction, and reduced critical thinking due to over-reliance on technology.
Similar concerns, and additional recommendations, have been raised after the introduction of ChatGPT (Baidoo-Anu and Ansah, 2023; Chinonso et al., 2023; Kasneci et al., 2023; Rahman and Watanobe, 2023). The integration of ChatGPT as well as other generative AI tools into educational settings has the potential to revolutionize programming instruction by providing personalized learning experiences, formative assessments, and enhanced teaching strategies. Kiesler and Schifflner (2023) assessed the performance of ChatGPT-3.5 and ChatGPT-4 on 72 Python tasks from CodingBat using unit tests. The LLMs achieved high accuracy, with 94.4–95.8% correct responses, highlighting their effectiveness in solving introductory programming tasks.
Additionally, LLMs’ capability to generate code and provide textual explanations offers new opportunities for integrating them into educational settings. These capabilities enable the design of programming tasks, the provision of formative feedback, support for novice learners, and offer accessibility and inclusivity by aiding students with disabilities or those who struggle with traditional methods. However, LLMs’ present limitations in addressing more complex problems that require a deeper understanding of programming concepts (Chinonso et al., 2023; Kiesler and Schifflner, 2023; da Silva et al., 2024).
Despite their advantages, generative AI tools are not without their limitations and potential drawbacks (Azaria et al., 2024). They may generate inaccurate information, perpetuate biases from their training data, and raise privacy concerns when handling sensitive student data. Additionally, their contextual understanding is often limited, leading to potentially incorrect or irrelevant results in specific searches. Moreover, the outputs from these tools might be difficult to interpret, posing challenges for inexperienced users (Phung et al., 2023). Furthermore, studies suggest that an over-reliance on AI-powered tools could diminish students’ critical thinking skills, as they increasingly rely on technology for problem-solving (Ifelebugwu et al., 2023; Memarian and Doleck, 2023; Mosaiyebzadeh et al., 2023).
Thus, to fully leverage the advantages of generative AI tools in programming education, educators and students should collaborate on establishing guidelines for responsible AI integration and usage. Both parties should also focus on addressing the associated limitations and explore integrating these tools with complementary technologies to effectively handle more extensive or complex tasks.
2.2 LLMs for data analytics learning
The power afforded by LLMs can be decisively harnessed to support the teaching and learning of comprehensive skills within the context of computational thinking. Specifically, ChatGPT and other generative AI tools can support the acquisition of skills that facilitate the rapid and consistent execution of projects in data analytics, data science, data mining, and related fields.
Since the emergence of LLMs, several authors have developed strategies to leverage the potential of generative AI tools to enhance data analytics education. Tu et al. (2023) explored the transformative potential of LLMs in data science education, highlighting their ability to amplify human intelligence, foster critical thinking, and promote ethical awareness. By streamlining repetitive tasks such as data cleaning and machine learning model building, LLMs allow students to concentrate on higher-level concepts and provide contextually relevant examples, exercises, and explanations tailored to individual needs. Zheng (2023) reported that ChatGPT enhances the understanding of new and existing complex technical concepts related to data science and data analytics and improves coding skills by generating code for common algorithms and tasks. Furthermore, ChatGPT facilitates learning at an individual’s pace through simple prompts in their native language.
Despite the potential of LLMs to support data analytics education, few studies in the literature, to the best of our knowledge, report concrete and formal efforts in this direction. Therefore, one of the objectives of this work is to contribute to narrowing this gap.
## 2.3 Generative AI tools for data analytics learning
While ChatGPT and other generative AI tools have been used as assistants in programming education, new tools have emerged to enhance this process. Chen et al. (2023) developed GPTutor, an extension for Visual Studio Code that leverages the uses OpenAI’s GPT API to offer detailed code explanations by integrating relevant source code into its prompts, delivering more precise and concise insights compared to existing code explainers. Yang et al. (2024) introduced the Conversational REpair Framework—(CREF), which employs LLMs to semi-automatically repair programs by integrating augmented information and human guidance aiming to improve productivity, elevate code quality, facilitate interactive learning, and broaden access to high-quality programming education.
Prasad and Sane (2024) proposed a self-regulated learning (SRL) framework for programming problem-solving using generative AI technologies like LLMs. They emphasize the importance of SRL skills in effectively leveraging LLMs and explore how these technologies influence students’ problem-understanding, solution evaluation, and regulation strategies. Their SRL framework provides a theoretical foundation for educational interventions that enhance SRL skills, improving students’ ability to use AI-powered tools in programming tasks. A key advantage of this framework is its ability to promote self-regulation by encouraging deep problem analysis, fostering problem decomposition skills, and enhancing computational thinking through prompt engineering and conversational AI.
Other efforts include LLM-based assistants like Code Interpreter by OpenAI (2024) and Open Interpreter by Lucas (2023). Both tools work as Python code assistants using GPT, facilitating programming tasks.
However, these generative AI tools primarily support the teaching and learning of programming-related skills. Few tools have been specifically designed for developing skills focused on supporting data analytics or data science learning. One of the pioneering tools in this area is LIDA, a novel tool for generating grammar-agnostic visualizations and infographics. Developed by Dibia (2023), LIDA approaches visualization generation as a multi-stage process, arguing that well-orchestrated pipelines based on LLMs and Image Generation Models (IGMs) are effective for addressing data analytics tasks. LIDA leverages the language modeling and code writing capabilities of state-of-the-art LLMs to enable four core automated visualization capabilities: (i) Summarizer, which converts data into a rich but compact natural language summary; (ii) Goal Explorer, which enumerates visualization goals based on the data; (iii) VisGenerator, which generates, refines, executes, and filters visualization code; and, (iv) Infogapher, which produces data-faithful styled graphics using IGMs. Additionally, LIDAs data visualization capabilities extend to four operations on existing visualizations: explanation, self-evaluation, automatic repair, and recommendation. LIDAs characteristics make it a direct support tool for both, development and education-related, activities.
Recently, Hong et al. (2024) introduced Data Interpreter, an LLM-based agent that emphasizes three pivotal techniques to enhance problem-solving in data science: (i) dynamic planning using hierarchical graph structures for real-time data adaptability; (ii) dynamic tool integration to improve code proficiency during execution, thereby enriching the necessary expertise; and (iii) identification of logical inconsistencies in feedback and efficiency enhancement through experience recording. Although it is possible to direct Data Interpreter toward educational purposes, the agent primarily focuses on automating the development of data science and data analytics projects in an agile and reliable manner.
## 3 Materials and methods
Our objective is to measure the impact of generative AI tools on the learning process of data analytics. To achieve this, we conducted a case study involving students and professionals with minimal or underdeveloped computational thinking skills. Below, we detail the research model, study group, and case study conditions.
### 3.1 Research model
This article examines how learners perform and their perspectives when using traditional tools versus LLM-based tools to acquire data analytics skills. To explore this, we employed the case study method. A case study entails a thorough examination and analysis of an individual, group, organization, or event. It delves deeply into a specific topic, elucidating a phenomenon or seeking to understand the efficacy of certain strategies or approaches in a particular situation (Yilmaz and Yilmaz, 2023).
Participants developed a data analytics project in the context of a Data Analytics short session as described in Section 3.4. Thus, our case study focused on examining the participants’ performance while also considering the instructors’ opinions on the quality of the solutions developed as presented in Section 3.5.
### 3.2 Participants
We conducted a case study with a cohort of 59 participants affiliated with higher education programs at Tecnologico de Monterrey, a private university in Mexico. The cohort included 43 undergraduate students enrolled in a Data Analytics course and 16 professionals from a continuing education course focused on Data Analytics. It is important to highlight that our analysis was guided by the perspective of the participants’ roles, specifically distinguishing between students and professionals.
To examine potential differences in responses due to the gender gap in motivation for developing computational competencies, the study documented the gender distribution of the participants (Jung Won Hur and Marghitu, 2017; Kurti et al., 2024). From our cohort, 32 participants identified as female, 27 as male, and 1 preferred...
Figure 1 presents the distribution of gender across different roles among the participants in our case study. All participants were affiliated with different departments, ensuring diversity in areas of expertise and indicating the depth of their computational background. Specifically, 88% of participants came from fields such as finance, business, social sciences, and others, while the remaining 12% were from engineering disciplines including sustainable engineering, chemical engineering, biomedical engineering, and industrial engineering. This distribution is detailed in Figure 2.
Moreover, the cohort included individuals from a wide range of age groups: 22 participants were between 18 and 20 years old, 19 were between 21 and 22, while smaller groups fell into older age brackets, with 2 participants each in the ranges of 23–25, 26–30, 31–35, and 36–40 years. Additionally, 4 participants were between 40 and 50 years old, and 5 were over 50 years old, as shown in Figure 3.
Collecting data on participants’ age, gender, and professional background enabled us to examine variations in responses influenced by these demographics. This information is crucial for analyzing the impact of generative AI tools on learners with varying levels of experience across different fields. All participants’ responses were analyzed to assess their performance and perspectives on using traditional and LLM-based tools.
for developing data analytics skills, ensuring a comprehensive understanding of their effectiveness in diverse educational and professional contexts.
### 3.3 Case study materials
The focal point of our case study is centered on developing a single data analytics project for all participants. The following materials were defined for carrying out the case study:
1. **Programming environment:** We selected Google Colaboratory (2017), a collaborative programming environment hosted in the cloud, which allows users to focus on programming, without worrying about technical details such as package installation, programming configurations, memory management, etc. Participants required a free Google Colaboratory account to work on the project.
2. **Datasets:** We selected two well-established datasets from the literature: the Iris and the Wine datasets (Dua and Graff, 2019):
- Iris dataset: This dataset was used by the instructors to illustrate the development of a data analytics project.
- Wine dataset: This dataset is similar to the Iris dataset, and was given to learners to be worked on entirely by them.
While the datasets are commonly known, the instructors provided them directly to avoid confusion and variations.
3. **Project methodology:** The project was developed following the de-facto standard and industry-independent process model CRISP-DM (Schröer et al., 2021). Only 3 of the 6 phases of CRISP-DM were performed:
- Business understanding: The business situation should be assessed to get an overview of the available and required resources. The project's goal establishment is one of the most important aspects of this phase. Thus, the instructors formulated one goal (G1) for the project based on the Iris dataset and one goal (G2) for the one based on the Wine dataset. These goals were carefully put together to align with the analytical challenges faced by learners and the educational goals of our case study.
- Data understanding: Exploring and describing the dataset and checking the data quality are essential tasks in this phase. To make it more concrete, it is recommended to carry out a statistical exploratory analysis. Depending on the established goal, it is possible to reach a feasible solution at this point.
- Evaluation: The results are reviewed according to the established goal. Therefore, the results must be interpreted and further actions are defined. Furthermore, the process is to be reviewed in general.
It is recommended that participants have a basic understanding of data analytics projects' pipeline. Nevertheless, the instructors provided fundamental highlights.
4. **ChatGPT:** An LLM web application based on a model specifically trained to follow instructions from prompts and provide detailed responses (OpenAI, 2022). For this study, the participants required a free ChatGPT access account.
5. **GPT via API:** This is the core of ChatGPT, namely, the model itself, which can be accessed directly via API service (OpenAI, 2020). This is a technical resource primarily used in specialized software development projects. Due to the cost of accessing GPTs via API, the instructors provided an OpenAI token free of charge to facilitate access to this resource.
6. **LIDA:** An open-source library for generating data visualizations and data-faithful infographics, compatible with multiple LLM providers (Dibia, 2023).
### 3.4 Case study process
A special 135-min session was scheduled for our participants, referred to as learners, to take part in the study. The session was led by the instructors, who are the authors of this work, following the step-by-step actions described below.
1. **Presentation (5 min):** The session begins with a welcome to the participants, an explanation of the session's purpose, and an overview of how the data regarding their performance and impressions will be collected.
2. **Introduction (10 min):** A brief overview of the development of data analytics projects following the CRISP-DM methodology is provided. It is noted that we will undertake a project using three different approaches: traditional development, utilizing ChatGPT, and employing LIDA in combination with GPT.
3. **Approach 1—traditional development (30 min):** A new project is initiated in Google Colaboratory, with development centered on achieving the defined goal (G1) on the Iris dataset: *Is there a relationship between sepal length and petal width in different iris species?*
This approach emphasizes the traditional development of a data analytics project using standard Python packages, including pandas, scikit-learn, matplotlib, and seaborn. Thus, the instructors provided the pre-developed source code and guided learners on every step throughout the entire process, from data reading to the interpretation of the results.
a. **Activity proposal (5 min):** The Wine dataset is presented to learners as well as the respective goal (G2): *Do the chemical components of a wine allow us to identify the class of wine to which it belongs?*
Learners are instructed about the Activity 1 which consists on develop the data analytics project to address G2 using standard Python packages. Participants are allocated 10 min to work on the project and are encouraged to progress as far as possible within this time frame.
b. **Activity 1 development (10 min):** Participants work on the project, focusing on solving G2 using Approach 1. During this period, no technical support is provided by the instructors.
4. **Approach 2—ChatGPT-based development (20 min):** A new chat window in ChatGPT is initiated. The instructor recommends using the most recent ChatGPT version. For this case study, the instructor gave the freedom for the learners to choose to use ChatGPT-3.5 or ChatGPT-4.
The instructor begins developing G1 again, this time with ChatGPT. Using prompt engineering, the instructor defines ChatGPT’s role and outlines expectations. ChatGPT is informed about the programming environment, the dataset, and the desired goal. The source code responses generated by ChatGPT are copied to a new project in Google Colaboratory for execution. The results are observed and analyzed. The instructor then returns to the ChatGPT window to request explanations and interpretations of the results. The ChatGPT explanation is discussed and compared against the instructor’s interpretation. New prompts may be made to adjust the results, enhance the visual aspects of the plots, and so on.
a. **Activity proposal (3 min):** Learners are instructed about the Activity 2, which consists on develop the data analytics project to address G2 using ChatGPT-based development. Participants are allotted a 10-min period to work on the project, during which they are encouraged to achieve as much progress as they could.
b. **Activity 2 development (10 min):** Participants work on the project, focusing on solving G2 using Approach 2. During this time, the instructors do not provide any technical assistance.
5. **Approach 3—LIDA + GPT development (25 min):** A new project is initiated in Google Colaboratory. Within this environment, instructors demonstrated how to install and configure LIDA. They also guided the integration of LIDA with the preferred GPT model using OpenAI’s API, ensuring it aligned with the GPT model used in Approach 2. This process included detailed instructions on how to create and use prompts directly from the Google Colaboratory programming environment by integrating LIDA + GPT to address G1. Given that this combined approach provides a compact and efficient solution for G1, we further explored its capabilities to refine and enhance the results.
a. **Activity proposal (2 min):** Learners are instructed about the Activity 3 which consists on develop the data analytics project to address G2 using LIDA + GPT development. Participants are given 10 min to advance the project and are encouraged to make as much progress as possible within the allotted time.
b. **Activity 3 development (10 min):** Participants worked on the project, focusing on solving G2 using Approach 3. During this time, the instructors do not offer any technical assistance.
6. **Form filling and closing (15 min):** Participants are directed to a Google Form questionnaire, specifically designed to capture their information. The session concluded after all the participants filled out the form.
The instructors can provide an additional 10–15 min for Q&A. Moreover, it is important to note that the objective of each of the three activities proposed to participants is, in addition to demonstrating different ways of solving a data analytics project, to measure the level of complexity of the technologies and the background required for their appropriate use.
In Activity 1, participants were tasked with completing the project using conventional Python programming techniques without any AI assistance. This activity aimed to set a baseline for comparing the effectiveness and efficiency of the other methods. In Activity 2, participants used ChatGPT as an external programming assistant. This setup allowed us to measure the impact of integrating a conversational AI assistant into the data analytics workflow. This activity also lets us analyze the advantages and potential challenges of using ChatGPT in a specialized context. Finally, in Activity 3, participants experienced the use of LIDA integrated with GPT as a specialized assistant for data-related projects. This approach aimed to create a workflow with assistance from an AI specialized in Data Analytics, all within the programming environment itself.
### 3.5 Data collection from questionnaire
Data collection was conducted immediately after the session concluded. The authors created an electronic questionnaire using Google Forms, and the link to the online form was distributed to the learners in the class. Learners were then instructed to complete the web form using their computers.
The questionnaire was prepared to collect sufficient data to generate a robust profile of each participant, encompassing three critical aspects: demographics, previous programming and data analytics experience, and data analytics learning experience during the session.
Regarding demographic information, the focus was on collecting data on gender, age, affiliation, and role, as detailed in Section 3.2. Regarding previous programming and data analytics experience, we collected the following data:
- **Programming experience:** To assess their technical background, we inquired about participants’ prior experience in programming. This information is vital for evaluating how programming skills might influence their interactions with the analytical tools used in the study, as well as the speed at which participants developed the activities assigned during the session.
- **Experience in data analytics:** It is necessary to understand the participants’ familiarity with data processing projects, as this could affect their ease of use and efficiency with different analytical methods.
- **Experience using programming tools:** It is necessary to assess the participants’ knowledge and experience using programming tools, such as Google Colaboratory, to determine their potential proficiency with technologies related to data analytics.
- **Experience with generative AI:** We asked participants about their experience with generative AI technologies. This is crucial for understanding their readiness to leverage advanced AI tools to address professional challenges.
Regarding the data analytics learning experience during the session, we collected the following data:
- **Developing time:** Participants provided the time range required to complete the project for each approach. If a participant did not finish the activity within the allotted time,
they were asked to estimate the additional time needed to complete it.
- **Contribution to workflow development:** Participants assessed the extent to which each approach contributed to the project's development concerning the specified goal, with a particular emphasis on the quality of the solution obtained.
- **Ease of use:** Participants were asked which approach they found easiest to use for developing the step-by-step process of a data analytics project. This helps identify the most user-friendly approach, which is critical for adoption in real-world settings.
- **Result achievement speed:** Participants were asked to indicate which approach enabled them to achieve results the quickest, providing insights regarding the efficiency of each approach in solving a data analytics challenge.
- ** Appropriateness.** Participants evaluated which method they considered the most suitable for the type of work they were performing. This question assesses the perceived relevance and effectiveness of each approach.
- **Correctness:** We asked participants which approach they deemed most correct in relation to the progressive and overall obtaining of results. This question addresses their perceptions of the validity, quality, and reliability of the results obtained with each approach.
4 Findings
To evaluate participants’ programming experience, they were asked: “Before today’s session, have you had any experience with programming in any language?” The response options were: “yes,” “no,” and “some.” Analyzing this aspect by participant’s roles, 65% of the students reported having programming experience, while the remaining 35% indicated they had some experience. Among the professionals, 69% stated they had programming experience, 25% reported having minimal experience, and 6% indicated they had no programming experience at all. Figure 4 shows these distributions.

**FIGURE 4**
Distribution displaying participants’ programming experience based on their roles as students (left), and professionals (right).

**FIGURE 5**
Distribution displaying participants’ programming experience by role, ranging age, and gender.
FIGURE 6
Distribution displaying participants’ experience in developing data analytics projects based on their roles as students (left), and professionals (right).
FIGURE 7
Distribution of participants’ experience in data analytics-related skills by role, age range, and gender.
Since it is important to understand possible gaps in gender and age in the process of acquiring computational thinking-related skills, Figure 5 details the participants’ experience based on these two demographic factors considering their roles. The figure shows no significant disparity in programming experience across all roles, genders, and age groups, except for professionals over 50 years, where we found participants identified as female with no prior programming experience. Additionally, among students, the youngest group (18–20 years old) shows a majority of identified as females with previous programming experience. In the 21–22 age range, the predominant group is such identified as male.
To assess participants’ experience in data analytics, they were asked: “Before today’s session, had you had any experience developing any data analytics projects?” The response options were: “yes,” “no,” and “some.” Considering their roles, we observed that 56% had experience, 40% had no experience, and 5% had minimal experience. Among professionals, 50% of students had previous experience developing data analytics projects or related tasks, while 38% had no experience, and 12% had some experience. These distributions can be observed in Figure 6.
Analyzing Figures 4, 6, we note that all students had at least some minimum experience in programming, while only 6% of professionals reported having no experience at all. However, participants with programming experience did not necessarily have experience in developing data analytics projects. Consequently, there is a greater number of participants with no prior experience in data analytics projects compared to those with programming experience. Furthermore, as shown in Figure 7, the gender group that presents the greatest disparity in data analytics-related skills is female across roles and age groups. This is most clearly seen in the younger groups, where half or more of the males have at least some experience in data analytics, while among females, half or fewer possess these skills.
To assess participants’ experience with programming tools, we asked, “Before today’s session, were you familiar with programming tools like Google Colab, Python, and others?” The response options were: “yes,” “no,” and “some.” As shown in Figure 8, only 8% of participants, regardless of their role, indicated they had no prior exposure to programming tools. This percentage is entirely represented by professionals who reported having none or minimal programming experience because they are just beginning their journey into acquiring these skills. Conversely, some students had already taken or were taking an introductory data analytics course that included programming tuition.
To assess participants’ experience with generative AI, we asked four specific questions: “Before today’s session, have you had any experience using ChatGPT to the extent of creating prompts on various topics?” “Before today’s session, have you had any experience using ChatGPT for any programming tasks?” “Before today’s session, have you had any experience using ChatGPT for any data analytics tasks?” and “Before today’s session, have you had any experience using any OpenAI API or other generative AI provider’s API?” For each question, the participants had to respond with one of the following options: “yes,” “no,” or “some.” Results for these four questions are shown in Figure 8.
In Figure 9 we can observe an unexpected finding. Despite being just over 2 years since the launch of ChatGPT, given the popularity of the platform, one could assume that all participants would have had some prior experience with it. However, our data reveals that 15% of participants had no prior interaction with this generative AI tool. More further insights are observed when found that a significant portion of the participants, 27%, had never used ChatGPT for programming tasks. Moreover, an even larger segment, 37%, had not utilized ChatGPT for data analytics project development. These results indicate that, contrary to expectations, a substantial number of participants were yet to integrate ChatGPT into their workflows for these specific tasks. Moreover, also is interesting to observe that a significant portion of participants with programming and data analytics experience also had some experience using generative AI APIs. This implies a considerable level of expertise that allows for a greater critical appreciation of the session that learners have taken.
The time each participant spent developing Activities 1, 2, and 3 is crucial for quantifying the effort required to tackle the same project using different approaches. As shown in Figure 10, only when using Approach 2, which relied on ChatGPT as an external programming assistant, and Approach 3, which integrated the LIDA framework with GPT via OpenAI’s API, were some students and professionals able to complete the project in <5 min. Conversely, when using Approach 1, which involved traditional programming packages, the majority of participants required more than 10 min to complete the project. This highlights the efficiency of Approaches 2 and 3 compared to Approach 1.
Another noteworthy observation, as depicted in Figure 10, is that ~40% of professionals managed to develop the project within 10 min using either Approach 2 or Approach 3. This indicates a relatively high efficiency among professionals with these approaches. In contrast, students required more time and effort; only 35% of them completed the project in up to 10 min using Approach 2, and a mere 15% achieved this with Approach 3. This disparity suggests that professionals might be better equipped to leverage the capabilities of ChatGPT and the LIDA + GPT integration efficiently. Furthermore, professionals also spend less time working on Approach 1 to complete the project than students. This implies that, in general, professionals are more adept at tackling a data analytics project using any approach compared to students.
Additionally, in Figure 10, we can observe that 20% of students and 10% of professionals took more than 30 min to complete the project in Approach 3. This significant delay might indicate potential technical challenges associated with integrating LIDA with GPT via API. The extended time could reflect difficulties in configuring and effectively using the LLM, as the integration process still requires several complex setup steps. This suggests that while LIDA with GPT integration offers powerful capabilities, it also demands a higher level of technical proficiency or more refined implementation to avoid such delays.
We analyzed participants’ perception of three approaches to solving the same data analytics project focusing on ease of use, speed in achieving results, appropriateness, and correctness. To obtain this perception, we asked four questions:
- **Which of the approaches for developing an analytics project seemed easiest to you?** Ease refers to a general understanding of the process and practical implementation of the activity. In which of the approaches do you consider you could develop a data analytics project more efficiently, focusing more on analytics rather than programming details?
- **Which of the approaches for developing an analytics project seemed fastest to you?** Speed refers to which approach allowed you to progress the most in the 10 min offered for the activity development. In which do you feel you progressed the most or could potentially advance faster to achieve the aimed results?
- **Which of the approaches for developing an analytics project seemed most appropriate to you?** Appropriateness refers to the development experience. Which of the approaches do you consider has a more analytics-focused approach, reducing the effort on programming details?
Which of the approaches for developing an analytics project seemed most correct to you? Correctness refers to offering a coherent response that addresses the project goal in an objective, clear, visually appealing, and explanatory manner.
For each question, participants could respond with one of the following options: (i) Approach 1—Traditional method: Using standard Python libraries; (ii) Approach 2—ChatGPT as an external programming assistant; (iii) LIDA with GPT integration.
via API; and, (iv) None. Figures 11, 12 show the participants’ perceptions regarding these four aspects, considering their roles and gender, respectively. Specifically in Figure 12, aiming to maintain the legibility of the chart, we opted to exclude the individual who chose not to disclose their gender.
As stated in Figure 11, regarding the ease of use aspect, both students and professionals agree that Approach 2 offers greater advantages. Some students attribute this advantage to Approach 3, while very few students consider Approach 1 to be easier to use. Here it is important to notice that all professionals completely agree that using ChatGPT as a programming assistant is the easiest way to tackle data analytics projects, while students’ opinions are diverse. This perception is also reflected from a gender perspective, as depicted in Figure 12, which illustrates that both males and females predominantly consider Approach 2 to be the easiest to use. This preference suggests that regardless of gender and role, participants found ChatGPT to be more user-friendly and easier to use compared to the other approaches.
When we look at the speed factor of obtaining results in both Figures 11, 12, we see that most students and professionals, whether male or female, consider Approach 2 to be faster. Here we observe that a significant number of participants consider Approach 3, which integrates LIDA with GPT via OpenAI’s API, to be the fastest method for developing the project. This suggests that the streamlined workflow provided by this integration can be highly efficient. However, it is important to note that the speed advantage of Approach 3 is somewhat nuanced. The immediate response to a prompt in ChatGPT is inherently quicker because it bypasses the additional steps required for integrating and configuring the prompt to work within the LIDA + GPT environment. This additional setup in Approach 3 can introduce delays, even though the overall approach might offer superior functionality and efficiency once fully operational.
When Figures 11, 12 examine the appropriateness of different approaches in minimizing the effort required on programming details for data analytics projects, both by role and by gender, Approach 3 emerges as the preferred method. This indicates that integrating LIDA with GPT is widely recognized for its potential to streamline programming efforts effectively. However, it is noteworthy that a significant proportion of students also find Approach 2 to be a competitive option in this regard. This suggests that while the advanced integration capabilities of Approach 3 are appreciated, the straightforward and immediate assistance provided by ChatGPT in Approach 2 remains highly valued, particularly among students.
In examining the correctness of results across different approaches, as shown in Figures 11, 12, Approach 3 consistently emerges as the preferred choice among participants, irrespective of their role or gender. However, it is noteworthy that there is a
closer alignment of preferences with Approach 2 and, surprisingly, also with Approach 1. Given that this factor assesses the quality of results produced by each approach, it is expected that Approach 3 would be preferred for its specialized support in data analytics projects provided by the integration of LIDA with GPT. This preference underscores its effectiveness in delivering high-quality outcomes with minimal manual programming effort. Approach 2 also received a favorable reception due to its capability to provide valuable assistance, though ChatGPT requires participants to craft precise prompts and possess expertise in data analytics project development. It is noteworthy that some participants, particularly students identified as female, found Approach 1, which relies on traditional programming packages, to offer greater correctness in results. This might reflect their comfort and familiarity with conventional methods or a preference for the precision and control that manual coding provides. Overall, while advanced and integrated approaches such as Approaches 2 and 3 are favored for their efficiency and support in data analytics, traditional methods like Approach 1 still hold significant value for certain participant groups regarding perceived correctness and reliability.
Finally, evaluations were conducted on the projects optionally submitted by the participants. From the instructors’ perspective, projects utilizing Approach 3 demonstrated enhanced comprehension and application of data analytics concepts among participants, irrespective of their computational background. Integrating LIDA with a GPT led to project solutions of higher quality, indicating a heightened proficiency in data management and application development. Moreover, instructors considered that Approach 3 fostered an immersive and engaging learning experience in learners, significantly more so than those developed using other approaches. Such enriched narrative elements improve the project’s clarity and impact. Those elements also contribute to a more compelling presentation of data insights, highlighting the added value of integrating advanced generative AI tools with traditional data analytics frameworks.
5 Discussion and final remarks
This work highlights the potential of employing generative AI-based tools to revolutionize the development of data analytics competencies among students and professionals, regardless of their computational background. To this end, we presented a case study that, to our knowledge, is the first to evaluate the use of these technologies in the data analytics learning process, comparing them with each other and with traditional approaches based on programming packages.
A key lesson from our case study is the transformative potential of approaches based on integrating advanced generative AI tools
like GPT with specialized frameworks such as LIDA. The higher levels of participant preference indicate the superiority of these approaches over traditional development methods. However, it is important to highlight that when using general-purpose generative AI tools such as ChatGPT, users must be aware of the data analytics process and take responsibility for filtering out potential errors or incompleteness in the requirements of a data analytics project. These deficiencies can be mitigated by using more advanced tools specialized in supporting data analytics tasks, such as LIDA with GPT. However, users still need advanced programming knowledge to properly configure this connection via API.
Additionally, our findings suggest that the learning curves for the different approaches vary significantly. Since learners encountered technical difficulties in developing the project and interpreting the results, Approach 1 has a steep learning curve. Approach 2, which involves consolidating the ChatGPT responses into a cohesive project, has a shallow learning curve due to the challenge of verifying the suitability of the solution. Approach 3, using LIDA integrated with GPT, has a J-curve pattern, with initial developing difficulties related to establishing the connection via API and configuring the LLM, followed by a smooth and efficient process once set up.
It is important not to disregard that some users may feel insecure about the solutions generated by AI tools, leading them to prefer the traditional approach to developing data analytics projects. Therefore, there is a significant opportunity for generative AI tools to improve their performance, providing accurate, complete, and convincing results for data analytics projects, thereby increasing user confidence in adopting these technologies.
Some limitations concerning this work include the heterogeneity of participants' affiliations and ages, the short time allocated for completing activities for each approach, and the need for further studies to address the insecurity aspects related to the use of AI-based tools by some participants. Additionally, more extensive validation is required to assess the acquisition of critical thinking skills.
Nevertheless, we hope this work highlights the opportunities and needs for integrating advanced LLMs into educational practices, particularly in developing computational thinking skills. Our findings suggest that such integration can significantly enhance the learning of advanced skills, especially those related to data analytics. We aim to establish this study as a foundation for the methodical adoption of generative AI tools in educational settings, paving the way for more effective and comprehensive training in these critical areas. In future work, we plan to replicate this study with a larger participant pool and compare LIDA with similar technologies. Additionally, we intend to evaluate performance across various LLMs beyond GPT.
Data availability statement
The raw data supporting the conclusions of this article will be made available by the authors, without undue reservation.
Ethics statement
The studies involving humans were approved by Cynthia Karyna López Botello, Tecnologico de Monterrey. The studies were conducted in accordance with the local legislation and institutional requirements. The participants provided their written informed consent to participate in this study. Written informed consent was obtained from the individual(s) for the publication of any potentially identifiable images or data included in this article.
Author contributions
JV-R: Conceptualization, Data curation, Formal analysis, Funding acquisition, Investigation, Methodology, Project administration, Resources, Supervision, Writing – original draft, Writing – review & editing. AG: Conceptualization, Data curation, Formal analysis, Investigation, Methodology, Validation, Writing – review & editing. ON-H: Conceptualization, Data curation, Formal analysis, Investigation, Methodology, Validation, Writing – review & editing. JN: Conceptualization, Formal analysis, Methodology, Validation, Writing – review & editing.
Funding
The author(s) declare financial support was received for the research, authorship, and/or publication of this article. This work was partially supported by the NOVUS grant: 2023-419283 (PEP No. PHHT085-23ZZNV041).
Acknowledgments
We would like to thank the Writing Lab from the Institute for the Future of Education for helping in the publication of this work. We also thank the Cyber Learning Lab and the Computer Department of Tecnologico de Monterrey, Mexico City Region.
Conflict of interest
The authors declare that the research was conducted in the absence of any commercial or financial relationships that could be construed as a potential conflict of interest.
The handling editor GC declared a shared affiliation with the authors at the time of review.
Publisher’s note
All claims expressed in this article are solely those of the authors and do not necessarily represent those of their affiliated organizations, or those of the publisher, the editors and the reviewers. Any product that may be evaluated in this article, or claim that may be made by its manufacturer, is not guaranteed or endorsed by the publisher.
Supplementary material
The Supplementary Material for this article can be found online at: https://www.frontiersin.org/articles/10.3389/feduc.2024.1418006/full#supplementary-material
|
{"Source-Url": "https://www.frontiersin.org/journals/education/articles/10.3389/feduc.2024.1418006/pdf?isPublishedV2=false", "len_cl100k_base": 10738, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 43200, "total-output-tokens": 11863, "length": "2e13", "weborganizer": {"__label__adult": 0.0007233619689941406, "__label__art_design": 0.0017786026000976562, "__label__crime_law": 0.0007686614990234375, "__label__education_jobs": 0.302001953125, "__label__entertainment": 0.0002503395080566406, "__label__fashion_beauty": 0.000507354736328125, "__label__finance_business": 0.0013952255249023438, "__label__food_dining": 0.0009851455688476562, "__label__games": 0.0013370513916015625, "__label__hardware": 0.0016117095947265625, "__label__health": 0.0018644332885742188, "__label__history": 0.0010461807250976562, "__label__home_hobbies": 0.0004992485046386719, "__label__industrial": 0.0011186599731445312, "__label__literature": 0.0012454986572265625, "__label__politics": 0.0007357597351074219, "__label__religion": 0.0011415481567382812, "__label__science_tech": 0.09674072265625, "__label__social_life": 0.0006923675537109375, "__label__software": 0.02587890625, "__label__software_dev": 0.5556640625, "__label__sports_fitness": 0.0005941390991210938, "__label__transportation": 0.0010986328125, "__label__travel": 0.0005497932434082031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57286, 0.01901]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57286, 0.52242]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57286, 0.92955]], "google_gemma-3-12b-it_contains_pii": [[0, 2945, false], [2945, 8858, null], [8858, 15094, null], [15094, 21289, null], [21289, 22708, null], [22708, 28514, null], [28514, 34556, null], [34556, 36759, null], [36759, 39099, null], [39099, 44864, null], [44864, 45348, null], [45348, 48376, null], [48376, 51229, null], [51229, 56716, null], [56716, 56716, null], [56716, 57286, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2945, true], [2945, 8858, null], [8858, 15094, null], [15094, 21289, null], [21289, 22708, null], [22708, 28514, null], [28514, 34556, null], [34556, 36759, null], [36759, 39099, null], [39099, 44864, null], [44864, 45348, null], [45348, 48376, null], [48376, 51229, null], [51229, 56716, null], [56716, 56716, null], [56716, 57286, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57286, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57286, null]], "pdf_page_numbers": [[0, 2945, 1], [2945, 8858, 2], [8858, 15094, 3], [15094, 21289, 4], [21289, 22708, 5], [22708, 28514, 6], [28514, 34556, 7], [34556, 36759, 8], [36759, 39099, 9], [39099, 44864, 10], [44864, 45348, 11], [45348, 48376, 12], [48376, 51229, 13], [51229, 56716, 14], [56716, 56716, 15], [56716, 57286, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57286, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
447d16c6ae1cf4a28739badd16ee9889f331a560
|
Characterizing Experimentation in Continuous Deployment: a Case Study on Bing
Katja Kevic
University of Zurich
Switzerland
kevic@ifi.uzh.ch
Brendan Murphy
Microsoft Research
United Kingdom
bmurphy@microsoft.com
Laurie Williams
North Carolina State University
United States of America
lawilli3@ncsu.edu
Jennifer Beckmann
Microsoft
United States of America
jennifer.beckmann@microsoft.com
Abstract—The practice of continuous deployment enables product teams to release content to end users within hours or days, rather than months or years. These faster deployment cycles, along with rich product instrumentation, allows product teams to capture and analyze feature usage measurements. Product teams define a hypothesis and a set of metrics to assess how a code or feature change will impact the user. Supported by a framework, a team can deploy that change to subsets of users, enabling randomized controlled experiments. Based on the impact of the change, the product team may decide to modify the change, to deploy the change to all users, or to abandon the change. This experimentation process enables product teams to only deploy the changes that positively impact the user experience.
The goal of this research is to aid product teams to improve their deployment process through providing an empirical characterization of an experimentation process when applied to a large-scale and mature service. Through an analysis of 21,220 experiments applied in Bing since 2014, we observed the complexity of the experimental process and characterized the full deployment cycle (from code change to deployment to all users). The analysis identified that the experimentation process takes an average of 42 days, including multiple iterations of one or two week experiment runs. Such iterations typically indicate that problems were found that could have hurt the users or business if the feature was just launched, hence the experiment provided real value to the organization.
Further, we discovered that code changes for experiments are four times larger than other code changes. We identify that the code associated with 33.4% of the experiments is eventually shipped to all users. These fully-deployed code changes are significantly larger than the code changes for the other experiments, in terms of files (35.7%), changesets (80.4%) and contributors (20.0%).
Keywords—continuous deployment; experimentation; empirical analysis; full deployment cycle
I. INTRODUCTION
As the software industry has moved towards a service model, different companies have adopted techniques such as continuous deployment, in which software is continually released to users [24]. Increasing the rate of releasing software, radically changes the way software is developed and deployed [5]. Previously product changes occurred as part of major releases while in continuous deployment products evolve. Some organizations have chosen to couple this rapid deployment with an experimental framework to assess the impact of changes on the end user using a practice referred to as continuous experimentation [12]. Some products, such as Bing, have been using online controlled experiments, since 2009 [15]. Visibility of continuous experimentation increased with the build-measure-learn cycles advocated in the Lean StartUp methodology [26] in 2011 based upon experiences at IMVU. As the value of continuous experimentation is more and more recognized, large organizations, such as Facebook, Google, and Netflix, increasingly employ continuous experimentation [25].
These incremental, rapid deployments offer the opportunity for development teams to formulate hypotheses about expected user behavior due to a software change, define metrics needed to be collected to verify the hypotheses, and continuously learn how users react. The process to verify hypotheses is through controlled experiments1 [22]. Different versions of the product are exposed to randomly-chosen user subgroups. By measuring users behavior in each group, development teams have the ability to make a data-driven decision of whether to modify, delay, or abandon the given software change [15], [20], [21]. If a software change is abandoned the code associated with it, is removed from the system.
While a few works investigated the experimentation process, they often focus on the use of the process to evolve small products or services (e.g., [21]), or share experience reports and lessons learned (e.g. [17], [28]). The full life-cycle from an experiment’s first code change all the way to the analysis of the captured usage measurements has not been characterized. Parts of product strategies evolve based on experiments’ outcome [12], [11]. Therefore, knowing how quickly a product team can learn from experiments may help to better plan product strategies. Furthermore, knowing more about the code changes used for experiments may allow the elaboration of different experimentation procedures tailored to different kinds of code changes. Finally, we determine how many experiments are ultimately deployed to all users. Knowing more about the amount of deployed experiments helps to assess the efficiency of continuous experimentation approaches for products in different maturity stages. Previous research has not addressed how the code changes for experiments that were deployed to all users differ from the code changes which were not
1 Also called A/B tests, split tests, bucket testing, randomized experiments, online field experiments, canary, flighting, or gradual rollouts.
deployed to all users. Knowing more about these differences might enable efficiencies in the product development and experimentation processes.
The goal of this research is to aid product teams to improve their deployment process through providing an empirical characterization of an experimentation process when applied to a large-scale and mature service. In particular, we investigate the following research questions:
- **RQ1**: What are the characteristics of experiments and their development efforts, in terms of time spans, number of people involved, files and changes in a large-scale and mature product?
- **RQ2**: What percentage of experiments are ultimately deployed to all users?
- **RQ3**: How do the experiments which are deployed to all users differ from the experiments which were not deployed to all users in terms of time spans, number of people involved, files and changes?
To answer these questions, we conducted a large-scale empirical analysis of Bing, Microsoft’s search engine. We analyzed 21,220 experiments conducted in Bing since 2014, and all code changes that occurred during the same period of time. These experiments include a variety of different kinds of hypotheses that are tested. These hypotheses range from testing tweaks in algorithms to the impact of user interface or configuration changes on the end users. Through establishing a procedure to link specific change sets within Bing’s change history to specific experiments, we analyzed the code changes committed for experiments. A change set includes one or multiple files changed at the same time. Through this analysis, we inferred whether the code changes for an experiment were ultimately deployed to all users. Change sets which we could not link to experiments were also analyzed.
The remainder of this paper is structured as follows. First, we present background on continuous experimentation and the related work which has been conducted in this area. Then, we describe how experiments are conducted within a large-scale and mature product, i.e. Bing. We describe the main points which increase the complexity of the experimentation process. Section IV describes the historical data that we used to analyze characteristics of experiments and infer whether the software change for the experiment was ultimately shipped to all users. The results of this analysis are described in Sections V, VI, and VII. We then discuss the threats to validity in Section VIII, our findings in Section IX, and conclude our work in Section X.
II. BACKGROUND AND RELATED WORK
In this section, we provide background and related work on continuous deployment and continuous experimentation.
A. Background
We define and differentiate four terms used in this paper:
- **Continuous Integration** Software is developed in smaller, incremental change sets which are regularly integrated into the codebase of the complete product, where a process automatically builds and runs a test suite daily, hourly, or even per individual change [10].
- **Continuous Delivery** The automated implementation of an application’s build, deploy, test, and release process [13].
- **Continuous Deployment** A continuation of the continuous delivery process, where the application or service is automatically deployed to the customer [13].
- **Continuous Experimentation** All changes require a clear hypothesis of their impact on the end customer, and that hypotheses are verified against a subset of customers prior to full deployment [12].
We found that the terms delivery and deployment are often incorrectly used interchangeably in literature on this subject. One of the prerequisites for continuous experimentation, is that a product team deploys code changes frequently through continuous delivery or continuous deployment. Continuous integration enables both, continuous delivery and continuous deployment processes.
Through verifying the product at both, unit and system level, bugs can be detected soon after they have been introduced, and the quality of the software can be measured and analyzed over time. For example, the Apollo space mission, in the 1960s, incorporated all changes made during the day into a single overnight computer run [23]. Hence, developers can be increasingly confident about the quality of their code change. Further, by including feedback mechanisms into each step in the continuous integration pipeline, developers have the possibility to react immediately to merge conflicts, to bugs or to irregularities within the collected measures. One of the main benefits of employing the principles of continuous integration is that the product remains in a deployable state and could be released at any point in time.
Further advancements in technology beyond continuous integration enabled continuous delivery and continuous deployment practices. These later two practices originated in the Software-As-A-Service area, whereby changes to the code base could be rapidly deployed to the service and the impact of these changes on the end users can be measured.
In an experiment, different versions of the product are exposed to different randomly chosen user groups. One version of the product includes a change or a new feature, referred to as the treatment, and the other version is the current version of the product, referred to as the control [22].
For each experiment a prior hypothesis is formulated which states that the treatment is not better than the control when evaluated with a measure, which measures the targeted aspect of the user behavior [20]. As the experiment runs for a predefined amount of time, the initial hypothesis is evaluated through testing for statistical differences between the treatment and the control. If the null hypothesis can be rejected, the users, in fact, react differently to each version of the product.
Five main components enable developers to run experiments [20], [12], [11], [24]:
2Also called the overall evaluation criterion (OEC), response, dependent variable, outcome, evaluation metric, key performance indicator, endpoint or fitness function.
1) a hypothesis on the experiment’s objective which is modeled in measurable metrics;
2) the instrumentation of the product;
3) a randomization algorithm;
4) an assignment method;
5) and a data path.
The product is instrumented such that the metrics defined to verify the hypothesis can be captured. The randomization algorithm is used to identify the users that are exposed to either the treatment or the control of an experiment. One difficulty for a large-scale product in which parallel experiments are run, is that the randomization algorithm has to ensure that there are no correlations between the assignments of experiments. The assignment method is the mechanism in place used to route user requests to the specified version of the product.
Users can be assigned to specific version of the product using techniques, such as traffic splitting, page rewriting, client-side assignment, and server-side assignment. Kohavi et al. [20] elaborate the advantages and disadvantages of each method. Finally, the data path is responsible for collecting the defined metrics and preparing the statistical analysis.
B. Continuous Experimentation at Microsoft
Different works analyzed the experimentation process within Bing. Kohavi and colleagues [17], [18], [19] and Crook and colleagues [6] share their insights and lessons learned while running an experimentation process at a large-scale. They work out seven rules of thumb for running controlled experiments and seven pitfalls to be avoided when running controlled experiments. They identify three main categories of challenges, including organizational challenges, engineering challenges, and the challenge of having a trustworthy experiment outcome. While Kohavi et al. [15] further look into the cultural aspects and share valuable real-world examples, Kohavi et al. [20] focus on the technical aspects in more detail and summarize the cost of experimentation when using different assignment methods. The trustworthiness of experiments is further elaborated through the analysis of five experiments’ outcomes by Kohavi et al. [16]. Deng et al. [9] investigate how the percentage of users to which the experiment is exposed or the exposure duration of the experiment can be reduced while the same statistical power can be observed. Deng [8] explores an objective Bayesian A/B testing framework to analyze metrics. In this paper we build upon that work with a focus on the full life-cycle of experiments, characterizing experiment and code changes attributes.
C. Other Continuous Experimentation Research
Several case studies have been conducted which identified the challenges which are faced when employing experimentation. Other researchers [7], [15], [17], [21] have identified the cultural shifts often necessary in development teams to be one of the major challenges. In particular, the risk of individuals losing power or prestige due to experiment results contrary to their own intuitions and the importance of a consistent reward system which rewards the volume of valuable experiments regardless of outcome have been observed as the main cultural challenges. Lindgren and Münch [21] further identified that slow development cycles, the product instrumentation and the identification of the metrics to measure the user experience are further challenges. Rissanen and Münch [27] largely confirmed these challenges when they studied experimentation in a B2B environment. They further found that the capturing and transferring of user data becomes a further challenge, as legal agreements come into play.
Fagerholm et al. [11], [12] explore a model of continuous experimentation and how experiments are related to the vision and the strategy of a startup company’s product. They found that the results from experiments altered the strategy of products, but the vision of the product remained unchanged. Within their suggested model, called RIGHT, the experimentation process is structured into build-measure-learn blocks. In our research, we approximate the duration of such a block.
While these case studies and experience reports focused on identifying challenges within an experimentation process and analyzed how experiments influence a product’s strategy, we focus on the source code development efforts which are involved in an experimentation process.
D. Experimentation - the State of Practice.
Systematic experimentation processes are prevalent in large companies that offer SaaS services [4], [5], [17], [21], [29]. For example, at Google every change that can impact customers goes through an experimentation process [28]. Thereby, many types of changes to the product are run as experiments: from visual enhancements to changes within back-end algorithms. These companies have developed scalable platforms which offer the infrastructure to run experiments in a systematic way. Many of these advanced experimentation platforms have further tools to support the data analysis integrated. For example, LinkedIn’s XLNT analysis dashboard [29] supports experimenters to make a data-driven decision of whether the experiment improved the user experience by presenting summarized views. Other tools and platforms to run systematic experiments are emerging. Google’s Analytics experiment framework [1] and Facebook’s PlanOut [2] are two examples of such frameworks that support an experimentation process.
When Lindgren and Münch [21] surveyed ten smaller software companies to understand the current state of the practice of experimentation processes applied, they found that the surveyed companies recognize the value of experimentation but only few companies run systematic experiments often. As more and more services and even desktop applications such as Chrome or Mozilla Firefox, adapt principles of continuous delivery [3], experimentation can become an integral part within the development cycle of a wide range of different products.
While all these case studies and experience reports enable important insights into different experimentation processes, we add to the existing body of research the first empirical study on
a large-scale and mature experimentation process. In particular, compared to previous works, we describe the full life-cycle of an experiment from the first code change to the deployment of the experiment.
III. BING EXPERIMENTATION PROCESS
For this case study, we analyze Microsoft’s search engine Bing. Bing includes the main search results pages from Bing.com, as well as several services that are consumed by other Microsoft products, such as Cortana. Bing’s richness in a variety of services enabled us to study the experimentation process in different environments. While the majority of the services are customer based, some are development support services for the rest of Bing (e.g. developing the deployment software). Bing is broken down into a large number of independent components, where components are either library components or dedicated to specific services. Since 2009, Bing and other services across Microsoft, increasingly use the Experimentation Platform (ExP). ExP was introduced by the Experimentation Platform team within Microsoft that was formed in 2006. ExP is a highly scalable platform that enables a systematic experimentation process [15]. In the following, we characterize the individual steps of the experimentation process in Bing (see Figure 1).
A. Experiment Design
In a first step, developers formulate a hypothesis that defines the aspects of the users’ behaviors they seek to improve. Then, they identify the set of metrics that allow the formulated hypothesis to be tested. ExP provides a wide range of predefined metrics that can be used to capture the users’ behaviors. If this set of predefined metrics does not properly test the developers’ hypothesis, the developers need first to implement or request the needed instrumentation within the product to capture additional aspects of the users’ behaviors. The set of metrics that is identified for the experiment are then captured within an ExP scorecard. Furthermore, experimenters need to decide on the number of users that are exposed to each group within the experiment and the amount of time the experiment will be exposed to the users. A rigorous experiment design is indispensable for being able to make a data-driven decision of whether the feature should be deployed.
B. Pre-Study
Development teams have the possibility to rapidly evaluate a predetermined hypothesis by creating an internal pre-experiment prior to fully developing the software change. Internal experiments are usually mock-ups or quick-hacks of the idea that are submitted to an internal crowd-platform. Within this crowd-platform, the mock-ups or quick-hacks are shown to a chosen set of people, without identifying which is the treatment and which is the control. The outcome of these human judgments is then used to evaluate if the idea should be further implemented and then run through the full experimentation process or if the idea does not show potential. Furthermore, product teams use the outcomes of these internal experiments to prioritize the planned experiments.
C. Source Code Development and Deployment
The development team for each of the Bing services has the autonomy to choose their own software development process. Each service has its own development environment managed through its own branching structure. Also the deployment process varies among the different services and is often based on the characteristics of the service itself. For instance, the service that manages the user interface (UI) has an hourly development and deployment cycle, where the deployment process rolls out the changes in a controlled manner and rolls back changes that have bugs. Conversely, the development and deployment of complex state based services, such as the index server can require additional verification: deployment cycles can be weekly or longer.
D. Experiment Execution
After the source code is changed and deployed, the experiment execution starts. Experiments generally run for one or two weeks. To lower unforeseeable risks of system failures, an experiment generally starts by directing a small percentage of users to the advanced version, the treatment, of the product. After some time, where no failures are detected, the percentage of users directed to the treatment gradually increases. This mechanism ensures that if there was an issue with an experiment only a small percentage of users experienced it. There are different metrics which are continuously captured while the experiment is running. One group of metrics, the guardrail metrics, is the sentinel to the health of the product. If metrics in this group change drastically, egregious issues with the experiment are detected and ExP informs an alert system, which shuts the experiment automatically down and all traffic will be sent to the prior version. An example of a guardrail metrics is the page load time.
Since ExP allows multiple experiments to run in parallel, the risk of different experiments interacting with each other increases. Because the interaction of experiments can corrupt the metrics captured for each experiment and possibly harm the user experience with the product, it is pivotal that a possible interaction is prevented. If the prevention was bypassed, the corruption it is quickly detected. ExP incorporates mechanisms to prevent and detect interactions. To prevent interactions between different experiments, each experiment defines constraints. These constraints are used to identify the experiments that should not be exposed to the same user. To detect interactions between running experiments, ExP scans and analyzes the metrics of pairs of running experiments. If interactions between experiments are recognized, an alert is raised and the owners of the experiment involved in the interaction are informed. They then decide whether to stop one of the experiments.
If a bug in the changed code or in the experiment configuration is detected, another alert is raised which informs the owners of the experiments. If no issues are detected during the
experiment execution, the experiment is stopped automatically after the exposure duration specified by the experimenter.
E. Data Analysis
To inform experimenters of the status of a running experiment, ExP allows the creation of scorecards on a periodic basis. A more extensive data analysis occurs after the experiment completed.
If the experiment ran without any issues (i.e. no alerts from the alert system reported and no bugs in the source code detected), it is considered to be a valid execution of the experiment. Developers can now decide between three alternatives: deploy the experiment, abandon the experiment, or iterate the experiment. Each experiment within Bing aims to improve user behavior on two levels. The first level is the same for each experiment within Bing. Metrics in this level are called the main metrics which each experiment tries to improve. These metrics target long-term goals of the product, such as the number of clicked search results. The second level is experiment-specific and targets the metrics that were defined in the product team’s hypothesis for the experiment. Examples of experiment-specific metrics are the elapsed time until a first search result is clicked or whether a suggested query completion was used. Based on the product team’s hypothesis and the gathered metrics a data-driven decision of whether to ship, abandon, or iterate the code change is made.
If the overall evaluation criterion (OEC) measurably improved with the new version of the product, then the treatment of the experiment is shipped and abandoned in the contrary. In practice, the OEC takes several factors into account, such as the user experience and revenue, and allows to trade one factor off for another. If the product team cannot make a data-driven decision based on the metrics that were collected, the product team iterates on the experiment design and defines a new set of metrics to test the hypothesis on. If the correct metrics have been collected for the experiment, but more user data is needed to enable a data-driven decision, then a new iteration of the experiment is launched. Finally, the product team can also decide to iterate on the source code change, but to validate the same hypothesis.
If the experiment executed with issues, then it is an invalid execution. If there was a bug in the changed code or in the experiment configuration detected, the product team iterates on a further code change to eliminate the bug. If the experiment was stopped because the metrics indicated that they were harming the user experience, then it might be abandoned.
F. Complexity of Experimentation
We observed that running a thorough experimentation process on a large scale service is very complex. Figure 1 depicts the experimentation process currently used by Bing. The complexity of the experimentation process stems from different aspects. First, while it is possible to rapidly verify that a deployment does not break the user experience, it takes time to verify that the user experience is improved or not degraded by the change. Experiments have to be exposed to the user groups for at least one week. There are many reasons for this: one reason is that users interact with the product differently on different days of the week. While it is imaginable that users search, for example, may be more work related on a Monday morning, they would rather search for social related activities over the weekend. Another reason is that it is important to have enough users for statistical validity for trustworthy comparison. Depending on the size of the change and the prominence of the feature, it takes time until a large enough number of users interacted with it to gain enough data for statistical validity. Second, since Bing has users all over the world and runs on different devices, the results of the experiment can be country and device dependent. This segmentation adds complexity to the configuration of the service. Third, there is a limited capacity to run experiments. Parallel experiments can be run for each deployment and each data center. Finally, after running a series of experiments it needs to be tested how these experiments interact with each other and whether the combined user experience is still improved.
IV. Study Data and Method
Our dataset consists of 21,220 experiments that were conducted within Bing over the last 2.5 years. Bing offers the possibility to study experimentation in inherently different components of the product. Since these different components have slightly different procedures to capture and implement experiments, the following analysis does not capture all experiments for all components within Bing.
A. Experiments
As the experimentation process within Bing emerged and changed over time, we restricted the analysis to only experiments that were created since the beginning of 2014. Our dataset comprises historical data of 21,220 experiments run within 19 components of Bing. We downloaded information about these experiments through an API offered by ExP. ExP stores attributes about experiments and stores the exposure duration of each experiment, which reflects the amount of time the experiment’s treatment was exposed to end users of the product. In our analysis, we included only experiments for which a positive exposure duration was stored (occasionally experiments were created, but never run and hence the exposure duration is zero). Furthermore, ExP stores for each experiment a list of people who are responsible for the experiment, i.e. the owners of the experiments. Finally, we also retrieved the information showing which experiments are iterations of one another (i.e. the experiments which belong to the same experiment group).
Using another API offered by ExP, we downloaded for each experiment the created scorecards, which include several metrics measured over the experiment duration. ExP generates scorecards on a regular basis throughout an experiment. Hourly and daily scorecards measure the early hours of experiments and look for serious negative results that indicate a regression or bug in the product. As time goes on, the system
generates fewer scorecards, because the bugs are typically detected early on, and the goal is now to determine the validity of the hypothesis. In our analysis, we considered only the last scorecard that was created for a particular experiment.
B. Linking Source Code and Experiments
No explicit link exists between experiments and the source code. To re-establish this link, we analyzed all change sets within Bing’s source code change history since 2014.
Experiments in Bing are generally controlled through configuration initialization files (INI). As Bing is a large product, consisting of multiple components and developed by hundreds of developers, different syntax are used to configure experiments.
In a first step, we filtered all change sets identifying those that include the editing of at least one INI file. In a second step, we iterated through all the INI files identified in the first step and parsed the files using a regular expression to identify those INI files used to configure experiments. In a third step, we iterated through all INI files identified in the second step. We parsed each version of the files using another regular expression to identify whether the specific file version includes a configuration for one of the 21,220 experiments in our data set. Through this method, we created a link between a specific change set and a specific experiment.
As a result of this analysis, we were able to categorize and label every change occurring in the Bing development environment since 2014 into one of the following four categories:
**Matched Change**
The change set includes an INI file that was linked to a particular experiment.
**High Probability Change**
The change set includes an INI file for which we know at least one version has been used to configure experiments.
**Low Probability Change**
The change set includes at least one arbitrary INI file, but the INI file contains no syntax that implies it is used to configure experiments.
**Other Code Change**
The change set includes no INI file.
Due to the variety of complex syntax used in INI files, we concede that we may missed matched changes. However, these experiments are represented in the high probability category.
Prior to releasing the code for an experiment, a development team may iterate the code multiple times. Each code iteration is referred to as a change set. The change sets prior to the deployment of the code for an experiment are referred to as related change sets. To identify how much effort goes into an experiment, related change sets must be identified.
To identify the related change sets, we use the fact that a file in Bing has 1.3 iterations per year. As a result, we made the assumption that if the same file changes within a 5 day period then we can assume that the change sets containing the file are related. The small percentage (0.07%) of files that change very frequently (greater than 15 times per year) are excluded from the analysis. The following algorithm is applied to identify and process all related changes. Every change set edited by Bing since 2014 is processed, starting with the latest change set and working backwards. For each file in the change set the process identifies if the file was previously edited within the 5 day time window. If so, the change label for the change set, that the file belongs to, is altered based on the value of the label of the initial change set. If the label on the initial change set is matched change it overrides all other categories. If the label is high probability this overrides low probability and other code changes and if it was low probability this overrides other code changes. Walking backwards through the change sets will result in a cascading effect, where edits that occur within 5 days of the re-labeled change sets will also be re-labeled.
We also analyzed the identification of related changes over a time span of ten days. As the association of related changes
remains roughly the same, we decided to use a time span of 5 days in this analysis.
C. Parsing the Experiment Outcome
The experiments for which we could identify one or more matched changes, allowed us to infer whether the treatment of the experiment was ultimately deployed to all users. In particular, we analyzed the sequences of changed lines (diffs) within the matched changes of an experiment.
Occasionally, the configuration names of experiments are reused. In this circumstance, we cannot infer whether the treatment of the experiment was shipped or not. The syntax for controlling the shipment of experiments’ treatments is complex. The parser currently does not cover all options.
V. EXPERIMENT CHARACTERIZATION (RQ1)
RQ1: What are the characteristics of experiments and their development efforts, in terms of time spans, number of people involved, files and changes in a large-scale and mature product?
We answer this research question from two perspectives. First, we analyze how much time an average experiment within Bing takes (Section V-A). Further, we characterize other attributes of the development efforts and of experiments, such as the people who are involved. Due to substantial differences between components of Bing, we summarize these features for each component separately in Table I. Second, we analyze Bing’s change history of the past 2.5 years and compare the changes that are used for experiments to those changes not used for experiments (Section V-B).
A. Experiment Life-Cycle
Change sets for experiments are rapidly deployed. The average time between the first code change for an experiment and its deployment (last code change observed before the start of the experiment) is 1.5 days ($SD = 1.4$). Depending upon the specific component of Bing, an experiment iteration is generally exposed for one or two weeks to a user group. On average, experiments are iterated 1.8 times ($SD = 1.8$) and owned by 4.8 ($SD = 2.3$) people. On average, 1409 different metrics ($SD = 488$) are collected for an experiment. Over an experiment group, we observed 6.4 separate changes to software files submitted by 2.3 people ($SD = 1.7$). See Table I for details on the major Bing components. The analysis of the captured data and additional code changes between iterations adds additional time to the execution of the experiments. Our analysis identified that the experimentation process, from the start of the experiment to the completion of the last iteration of an experiment, takes an average of 42 days, including multiple iterations of one or two week experiment runs. Through characterizing the life-cycle of experiments, a product team is enabled to identify potential bottlenecks. Knowing where the bottlenecks are within the development cycle, enables to appoint either more resources or synchronize resources in an improved way.
B. Experimental Activity within Bing
As described in Section IV-B, we categorized each code change in Bing’s change history into one of the four categories: matched change, high probability change, low probability change, and other code change. We assume that many of the changes that we could not link to experimental activity and hence were grouped into the other code changes category are tool-based changes, test related, or bug fixes. Of the changes that we could link to experimental activity, we grouped 12.1% into the matched category, 45.5% into the high probability category and 42.4% into the low probability category. We observed that changes that are related to the matched and high probability category include more files than changes which are categorized into the low probability or other change category. We observed, on average, 78.9 files ($SD = 9.6$) for the matched changes, 122.2 files ($SD = 10.3$) for the high probability changes, 37.2 files ($SD = 10.4$) for low probability changes, and 11.7 ($SD = 8.2$) files for other code changes. See Figure 2.
We also found that changes categorized as matched or high probability changes have more related changes (on average 2.0 related changes for the matched changes and 1.8 related changes for the high probability changes) than the low probability or other changes (on average, 0.6 related changes for low probability changes, and 0.6 related changes for other code changes). In summary, our analysis indicates that changes that we relate to experiments are generally larger in terms of the files changed and have more related changes.
Bing can now use these results to identify the challenges that hindered developers from launching experiments. The challenges identified can then be addressed within the experimental framework.
VI. SUCCESS RATE OF EXPERIMENTS (RQ2)
RQ2: What percentage of experiments are ultimately deployed to all users?
Our empirical analysis indicates that 33.4% of the experiment groups were ultimately deployed to all users. Our observation supports Kohavi et al. [15] who reported that about a third of the experiments improve the metrics they were designed to improve. For 18% of the experiment groups, our procedure cannot infer whether the experiment was deployed to all users, these would require additional analysis to identify their status (see Section IV-B for details). We also found
considerable differences between the components within Bing. While components related to multimedia deploy 50.7% of the experiments to all customers, the rate is lower for components related to the index server (24.9%) for example. The varying rates of deployed experiments among components in Bing indicate that different components have different levels of difficulty to innovate enhancements which significantly improves the user experience. Bing developers mentioned that they are happy that they do not have a specific target of successful experiments, enabling them to try out new ideas. We further observed that the percentage of non-deployed experiments is increasing over time. One possible root cause might be that it becomes more difficult to find a niche for innovation as the product matures. On the other hand, since ExP facilitates systematic experiments, developers might test different variants of the same feature in separately captured experiments. Through our analysis, Bing is enabled to analyze the metrics that lead to a data-driven decision. Knowing which metrics are crucial for a particular component, opens the possibility to further automate a data-driven decision and offer an improved scorecard interface.
VII. DIFFERENCES BETWEEN DEPLOYED AND NON-DEPLOYED EXPERIMENTS (RQ3)
RQ3: How do the experiments which are deployed to all users differ from the experiments which were not deployed to all users in terms of time spans, number of people involved, files and changes?
To answer RQ3, we opposed several characteristics that we captured for the deployed and non-deployed experiments. We did not observe significant differences for the experiments’ exposure durations, number of iterations conducted within an experiment group, number of experiment owners, and number of metrics collected. We found differences in the way the code is developed for an experiment. A Welch two sample t-test indicates that experiments for which the treatment was ultimately deployed to all users have significantly more changes ($M = 5.1$) associated than treatments of experiments which have not been deployed ($M = 2.9$) at the time of the analysis, $t = -15.86, p < .001$. Furthermore, significantly more people contributed these changes for the deployed experiments ($M = 2.0$) than for the non-deployed experiments ($M = 1.6$), $t = -9.05, p < .001$. We also found that the code changes for deployed experiments are overall larger, in terms of the files that were changed ($M = 22.1$ for deployed experiments, $M = 14.2$ for non-deployed experiments, $t = -11.23, p < .001$), the unique files that were changed ($M = 14.4$ for deployed experiments, $M = 10.7$ for non-deployed experiments, $t = -7.30, p < .001$), and the number of lines that were changed ($M = 690$ for deployed experiments, $M = 231$ for non-deployed experiments, $t = -2.58, p = .01$).
We can infer for experiments which were ultimately deployed to all users that the captured metrics allowed a data-driven decision. At this point of our analysis, we cannot infer for the experiments that were not deployed to all users whether the metrics indicated that the user experience is decreased or whether there was no significant difference observed between the treatment and the control. Nevertheless, our results indicate that the collaboration of more contributors leads to the fruitful execution of an experiment. To better understand whether the collaboration of more people causes more files being changed or whether the need to change more files requires more people to collaborate, is planned for future work. Understanding the differences between deployed and non-deployed experiments, teams may be able to identify which category of experiments are more likely to be more successful and which category of experiments may require more monitoring.
VIII. THREATS TO VALIDITY
The external validity of our empirical analysis is threatened by the analysis of only one project. Because Bing is a mature large service, our results are not generalizable to less mature
<table>
<thead>
<tr>
<th>Bing component</th>
<th>development efforts</th>
<th>experimentation time</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td># contributors</td>
<td># files</td>
</tr>
<tr>
<td>Ads</td>
<td>2.2</td>
<td>12.1</td>
</tr>
<tr>
<td>Cortana</td>
<td>1.8</td>
<td>11.7</td>
</tr>
<tr>
<td>Datamining</td>
<td>1.6</td>
<td>9.4</td>
</tr>
<tr>
<td>Engagement</td>
<td>1.7</td>
<td>13.2</td>
</tr>
<tr>
<td>Index</td>
<td>2.0</td>
<td>15.5</td>
</tr>
<tr>
<td>Infrastructure</td>
<td>1.2</td>
<td>5.6</td>
</tr>
<tr>
<td>Local</td>
<td>2.2</td>
<td>14.0</td>
</tr>
<tr>
<td>Multimedia</td>
<td>1.9</td>
<td>18.3</td>
</tr>
<tr>
<td>Relevance</td>
<td>2.6</td>
<td>13.8</td>
</tr>
<tr>
<td>Segments</td>
<td>2.3</td>
<td>9.2</td>
</tr>
<tr>
<td>UX</td>
<td>2.1</td>
<td>15.3</td>
</tr>
<tr>
<td>Windows Search</td>
<td>1.7</td>
<td>16.2</td>
</tr>
</tbody>
</table>
products. Furthermore, we also believe that the experimental process is more complex for on-premises products. However, the project which we analyzed comprises several inherently different components. We tried to mitigate this difference by considering each component separately. Furthermore, due to data consistency reasons we limited our analysis to experiments of the past 2.5 years.
The *internal validity* of our analysis is threatened by the fact that components within Bing use slightly different ways to capture, configure and deploy experiments. Bing is a composition of very large services that use different programming languages. Further, Bing is developed by hundreds of developers, who implement source code for experiments in different ways. Therefore, we were limited in the development of parsers to link code changes to experiments and to infer whether experiments have been shipped. Hence, our analysis does not cover all experiments run within Bing, but presents an analysis on a subset of Bing’s experiments. Furthermore, our analysis on the experiments’ life-cycle does not capture the time spent on designing the experiment and analyzing the gathered user data. Our analysis is therefore a first approximation of the actual time needed to conduct controlled experiments in a large-scale software product.
**IX. Discussion**
The opportunity to experiment with products drastically changed the way software is deployed within Bing. Our empirical analysis showed that experimentation has become an integral part within the deployment cycle. In the following, we discuss different aspects of the experimentation process and our planned future work.
A. Should Experimentation be Done for All Code Changes?
Bing has significantly increased the number of experiments since 2009 [17]. Further, many people are involved in the execution of an experiment who spend time preparing and executing experiments. The experimentation process is now a substantial part within the deployment cycle. We also observed that experiments can become a limiting factor of the cycle time within the deployment cycle, and hence we suggest that practice as well as research should not only focus on methods to accelerate the deployment of code changes, but on methods to identify experiments which are worthwhile to run and on methods to ensure that the experiment is run without issues.
We observed that generally larger code changes are linked to experiments. While it is possible to run a controlled experiment with each kind of change, we conclude that smaller changes have other priorities than improving the user experience. As an example, for a bug fix, the most important issues are to rapidly understand whether the deployed fix does not introduce further issues and whether the change fixes the bug. For small code changes, users may be less likely to significantly react. On the other side of the spectrum, the difficulty in the experiment design, measurement, and analysis is substantially increased for large code changes as many different aspects about the larger change can influence user behaviors. Therefore, adapting experimentation means to understand the trade-off between running a controlled experiment and other means to verify a code change or to offer different experimentation processes for different kinds of changes. We believe that the cost of a controlled experiment could be dramatically decreased for bug fixes, if these changes could be deployed after a shorter amount of time and do not have to improve the user experience necessarily. Requiring a hypothesis for every change is too great an overhead for small changes, such as big fixes. Therefore, we believe that an experimentation process tailored to the different kinds of code changes may be more efficient.
B. Size of the Code Changes.
We observed that code changes which we classified as matched changes or high probability changes have overall more development activity associated with them than changes which we classified as low probability or other changes. This observation raises the question whether experimentation in a mature system is only enabled by changes big enough to cause measurable effects on the end users of the product. On the other hand, developers may not want to spend additional time for experimentation if the change is reasonably small. Hence, we suggest that different experimentation processes and frameworks should be used for different kinds of changes. For future work, we plan to investigate further the relation between bigger releases and the amount of experiments run and compare these findings to experimentation activity in a less mature system. Furthermore, we plan to investigate how continuous experimentation influences the way developers work.
C. Developers as Data Analysts.
We observed that on average 1409 metrics about the users’ behavior for each version of the product are identified and analyzed by experimenters. Further, experimentation frameworks offer to analyze an ongoing experiment multiple times a day. The collected metrics are not always straight-forward to interpret, as Kohavi et al. [16] illustrate on five real-world examples. This difficulty of interpreting the collected metrics suggests an inevitable shift of traditional development work to rigorous data analyses. This observation agrees with the observations of Kim et al. [14] who found that data scientist are increasingly important within software development teams. As these data analyses have potential to impact the annual revenue of a product [16], proper data analyses is of superior importance. As Lindgren and Münch [21] found out when interviewing people of different roles in ten software companies, a lack of time and missing expertise were named as reasons of inadequate data analysis. This lack of data analysis expertise was also identified for experiments run in a B2B environment [27]. Hence, the team around the Experimentation Platform introduced one-day classes in statistics and experimentation design, which nowadays even have wait lists [15]. We plan to further investigate how developers can be supported in coping with the captured metrics about the user behavior,
for example through improved user interfaces and summarized views.
D. Success of Experiments.
The success of an experiment can be considered from different standpoints. In our analysis, we first verified whether the code change is eventually shipped to all users. We observed that experiments which were shipped are significantly larger and that more people contributed source code for the experiment. However, an experiment can also be considered successful if a data-driven decision of whether to ship or abandon a code change was enabled and hence a development team had the possibility to learn more about their users. In a next step, we plan to analyze this learning value of experiments and we plan to figure out what the characteristics of experiments are that enable a data-driven decision.
X. Conclusion
The opportunity to experiment with a software product denotes a radical change in how software is deployed. While previously every change was deployed to all users, now only the changes which have a measurable improvement on the user experience are deployed to all users. We characterized such an experimentation process employed in a large-scale and mature product, i.e. Bing. We further analyzed 21,220 experiments over the past 2.5 years and observed that 33.4% of these experiments have been deployed to all users of the product. Our characterization of the experiments and their development activities revealed that experiments which are eventually shipped to all users, have generally more development activity.
Acknowledgment
We would like to thank the Experimentation Platform team for sharing historical data of experiments and helpful discussions of this work. We also thank the people who reviewed this paper, in particular the NCSU Realsearch research group, for providing valuable feedback.
References
|
{"Source-Url": "http://www.ifi.uzh.ch/dam/jcr:bafebc0f-ac0c-46d9-934b-4a0d5e2aab14/Characterizing_Experimentation_SEIP2017.pdf", "len_cl100k_base": 10033, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 32297, "total-output-tokens": 12488, "length": "2e13", "weborganizer": {"__label__adult": 0.00034117698669433594, "__label__art_design": 0.00029969215393066406, "__label__crime_law": 0.00021982192993164065, "__label__education_jobs": 0.001903533935546875, "__label__entertainment": 6.765127182006836e-05, "__label__fashion_beauty": 0.0001270771026611328, "__label__finance_business": 0.0004684925079345703, "__label__food_dining": 0.0002562999725341797, "__label__games": 0.0004916191101074219, "__label__hardware": 0.0004878044128417969, "__label__health": 0.0003116130828857422, "__label__history": 0.00026297569274902344, "__label__home_hobbies": 6.479024887084961e-05, "__label__industrial": 0.00021755695343017575, "__label__literature": 0.0003223419189453125, "__label__politics": 0.0001838207244873047, "__label__religion": 0.00029540061950683594, "__label__science_tech": 0.0073699951171875, "__label__social_life": 0.0001024007797241211, "__label__software": 0.00684356689453125, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.0002112388610839844, "__label__transportation": 0.00035643577575683594, "__label__travel": 0.00017380714416503906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58219, 0.02192]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58219, 0.44485]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58219, 0.93361]], "google_gemma-3-12b-it_contains_pii": [[0, 5563, false], [5563, 11667, null], [11667, 17773, null], [17773, 23821, null], [23821, 29983, null], [29983, 33955, null], [33955, 39219, null], [39219, 44730, null], [44730, 50937, null], [50937, 58219, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5563, true], [5563, 11667, null], [11667, 17773, null], [17773, 23821, null], [23821, 29983, null], [29983, 33955, null], [33955, 39219, null], [39219, 44730, null], [44730, 50937, null], [50937, 58219, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58219, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58219, null]], "pdf_page_numbers": [[0, 5563, 1], [5563, 11667, 2], [11667, 17773, 3], [17773, 23821, 4], [23821, 29983, 5], [29983, 33955, 6], [33955, 39219, 7], [39219, 44730, 8], [44730, 50937, 9], [50937, 58219, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58219, 0.07653]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
ea795afe0bc43f897d3f681f72024621d0951707
|
Techniques for designing efficient parallel programs
Citation for published version (APA):
Document status and date:
Published: 01/01/1991
Document Version:
Publisher’s PDF, also known as Version of Record (includes final page, issue and volume numbers)
Please check the document version of this publication:
• A submitted manuscript is the version of the article upon submission and before peer-review. There can be important differences between the submitted version and the official published version of record. People interested in the research are advised to contact the author for the final version of the publication, or visit the DOI to the publisher’s website.
• The final author version and the galley proof are versions of the publication after peer review.
• The final published version features the final layout of the paper including the volume, issue and page numbers.
Link to publication
General rights
Copyright and moral rights for the publications made accessible in the public portal are retained by the authors and/or other copyright owners and it is a condition of accessing publications that users recognise and abide by the legal requirements associated with these rights.
• Users may download and print one copy of any publication from the public portal for the purpose of private study or research.
• You may not further distribute the material or use it for any profit-making activity or commercial gain
• You may freely distribute the URL identifying the publication in the public portal.
If the publication is distributed under the terms of Article 25fa of the Dutch Copyright Act, indicated by the “Taverne” license above, please follow below link for the End User Agreement:
www.tue.nl/taverne
Take down policy
If you believe that this document breaches copyright please contact us at:
openaccess@tue.nl
providing details and we will investigate your claim.
Eindhoven University of Technology
Department of Mathematics and Computing Science
Techniques for Designing Efficient Parallel Programs
by
Pieter Struik
Computing Science Note 91/32
Eindhoven, December 1991
This is a series of notes of the Computing Science Section of the Department of Mathematics and Computing Science Eindhoven University of Technology. Since many of these notes are preliminary versions or may be published elsewhere, they have a limited distribution only and are not for review.
Copies of these notes are available from the author.
Copies can be ordered from:
Mrs. F. van Neerven
Eindhoven University of Technology
Department of Mathematics and Computing Science
P.O. Box 513
5600 MB EINDHOVEN
The Netherlands
ISSN 0926-4515
All rights reserved
editors: prof.dr.M.Rem
prof.dr.K.M.van Hee.
Techniques for Designing Efficient Parallel Programs
Pieter Struijk
Department of Mathematics and Computing Science
Eindhoven University of Technology
P.O. Box 513, 5600 MB Eindhoven, the Netherlands
Abstract
In this paper we present techniques for designing parallel programs. These techniques are calculational, i.e. starting from a formal specification of the problem we design a program by transforming the specification in a number of steps. The programs that we obtain are correct by design. We demonstrate two techniques by means of an example. First, we illustrate the derivation of a fine grained program. Since the communication overhead of such a program is too large, it can not be implemented on a processor network (e.g. transputer network) efficiently. We, subsequently, demonstrate two techniques for designing programs of a parameterized grain size. For obtaining efficient execution, such programs offer the possibility of tuning to the characteristics of the machine on which it is executed. Finally, we give a complexity analysis of the techniques presented and compare the results from the analysis to experimental results obtained from a transputer implementation.
keywords: design techniques, parallel programming, grain size
1 Introduction
In this paper we present techniques for deriving parallel programs of parameterized grain size. We consider a parallel program to be a collection of processes that interact with each other by exchanging messages. For efficient execution of parallel programs it is important that the partitioning of programs into processes is done properly. In particular, the grain size of processes is important. Processes that perform a lot of computations between successive communications with other processes are said to have a large grain size.
When designing a parallel program it is a difficult to determine a grain size that yields a good performance when the program is executed [1, 2]. It is therefore advantageous to
postpone this design decision by designing a parallel program that has a parameterized grain size. Such a program offers the possibility of tuning it to the characteristics of the machine on which it is executed.
Much research has been done on extracting parallelism from sequential programs [3]. In our technique, however, we follow the opposite direction. Starting from a fine grained parallel program we construct programs of parameterized grain size.
This paper is organized as follows. In Section 2 we briefly discuss a technique for deriving fine grained parallel programs. This technique is illustrated by means of a so-called window computation, viz. the Occurrence Count Last problem (OCL). We conclude Section 2 by giving a short complexity analysis of the program. In Section 3 the basic idea of this paper is presented. Based on the program derived in Section 2, we construct parallel programs of parameterized grain size for the OCL problem. We demonstrate two techniques. In Section 4, we present some experimental results obtained from a transputer implementation of the problem. Experiments have been carried out on a 51-transputer network. The results will be related to the complexity analysis worked out in Section 3. Finally, Section 5 gives some concluding remarks.
2 Design of a fine grained parallel program
In this section, we present the derivation of a fine grained program for the OCL problem. Starting from a specification, we construct a linear array of processes that communicate with each other by exchanging messages over channels. We derive a set of equations that define the values communicated along output channels in terms of received values along input channels. Since inputs on which an output depends should be received before producing that output, the set of defining equations gives rise to a partial order on communications along channels. Given this partial order we construct a consistent communication behavior that specifies in which order communications along the channels of a process take place. Given the communication behavior and the set of equations, the program text of a process can easily be written. We conclude this section with a short complexity analysis of the constructed program. Since the topic of this paper is not on the design of fine grained programs, we only briefly discuss the design method. For more examples of the design method we refer to [4, 5, 6]. The derivation of a fine grained program for a particular problem constitutes a basis that can be fruitfully exploited when designing a program of parameterized grain size.
2.1 Specification of the OCL problem
For a fixed \( N \) (\( N \geq 1 \)) and an input stream \( A \) of integers, the OCL problem is the computation of output stream \( B \) satisfying
\[
B(i) = (\# j : i-N < j \leq i : A(j) = A(i))
\]
\(^1\text{acquired through a grant from the European Community, Parallel Computing Action of ESPRIT, PCA No. 4038}\)
for $i \geq 0$, where $(\# j : R : B.j)$ denotes the number of $j \in R$ satisfying boolean expression $B.j$. Elements of streams are indexed from 0.
The OCL problem is called a window computation since $B(i)$ is determined by the $N$ elements of window $A(i-N..i)$. Parameter $N$ is called the window length. In this computation, from each window of length $N$ of the input stream $A$ it is computed how many times the last element of that window occurs in it. For $i<N$, the window contains negatively indexed elements of input stream $A$. In the sequel, we assume $A(-j)=0$ for $j>0$. Each successive element of stream $B$ is obtained by computing a function on the previous window that is shifted over one position. As a result, the program can produce one element of the output stream for each element of the input stream it receives.
### 2.2 A fine grained program for the OCL problem
We construct a fine grained program that consists of a linear network of $N$ processes, numbered from 0 (see Figure 1). Each process $k$ ($0 \leq k < N$) has an output channel $b_k$ specified as follows
$$b_k(i) = (\# j : i-N+k < j \leq i : A(j) = A(i))$$
The specification of channel $b_k$ is a generalization of the specification of output stream $B$. Notice that process 0 produces output stream $B$, since $b_0(i) = B(i)$.
For process $N-1$ we have $b_{N-1}(i)=1$ and for the other processes we derive
$$b_k(i) = \begin{cases} \text{ specification } b_k \\ (\# j : i-N+k < j \leq i : A(j) = A(i)) \\ \text{ split off term } j=i-N+k+1 \\ [A(i-N+k+1) = A(i)] + (\# j : i-N+k+1 < j \leq i : A(j) = A(i)) \end{cases}$$
$$= \begin{cases} \text{ specification } b_{k+1} \\ [A(i-N+k+1) = A(i)] + b_{k+1}(i) \end{cases}$$
where [true] = 1 and [false] = 0.
From this derivation we infer that in order to compute $b_k(i)$ process $k$ needs to have at its disposal two elements of the global input stream $A$, viz. $A(i-N+k+1)$ and $A(i)$. The
indices of both elements are equal for process \(k = N-1\). Hence, process \(N-1\) should access input stream \(A\). We, therefore, decide that \(A(i-N+k+1)\) and \(A(i)\) are communicated to process \(k\) by process \(k+1\) and introduce two additional output channels for process \(k\)
\[
\begin{align*}
c_k(i) & = A(i-N+k) \\
d_k(i) & = A(i)
\end{align*}
\]
For the first output along channel \(c_k\) we have \(c_k(0) = A(-N+k)\). Since negatively indexed element of \(A\) equal 0, we have \(c_k(0) = 0\). Furthermore, we have \(c_k(i+1) = c_{k+1}(i)\) and \(d_k(i) = d_{k+1}(i)\). Summarizing, we have the following equations for the output channels of process \(k\) (\(k \neq N-1\))
\[
\begin{align*}
b_k(i) & = [c_{k+1}(i) = d_{k+1}(i)] + b_{k+1}(i) \\
c_k(0) & = 0 \\
c_k(i+1) & = c_{k+1}(i) \\
d_k(i) & = d_{k+1}(i)
\end{align*}
\]
A communication behavior of process \(k\) that is consistent with this set of equations and, moreover, introduces minimal buffering – i.e. a minimal number of variables per process – is
\[(b_{k+1}, c_{k+1}, d_{k+1}; b_k, c_k, d_k)^*\]
In this communication behavior, a semi-colon ‘;’ denotes sequential composition, the Kleene star ‘*’ denotes repetition, and a comma ‘,’ between two communications denotes that we do not assign any particular order upon the execution (both actions may even be executed in parallel). Since neighbor processes access shared channels in the same order, deadlock is avoided.
Programs are written in a CSP-like notation, where \(c?x (c!x)\) denotes the receipt (sending) of variable \(x\) along channel \(c\). Translation of such a program into OCCAM is straightforward. The program text of process \(k\) reads
\[
\begin{align*}
vcc & := 0 \\
; \ ( b_{k+1}?vb, c_{k+1}?vc, d_{k+1}?vd \\
; \ vb, vc, vcc := vb + [vc = vd], vcc, vc \\
; \ bk!vb, ck!vc, dk!vd \\
)\*
\end{align*}
\]
In this program we have four variables of type integer \((vb, vc, vcc, \text{and} \ vd)\).
Although in an implementation on a processor network we are not that much interested in the number of variables a program uses, we nevertheless mention this number, since our programs can also be implemented as a VLSI circuit where chip area (heavily depending on the number of variables used) is one of the main design restrictions [7].
2.3 A short complexity analysis
We conclude this section with a short complexity analysis of the fine grained parallel program. We assume that each process is allocated to a separate processor. A so-called sequence function $\sigma$ is used to analyse the time complexity of the program. $\sigma(e, i)$ denotes the time on which the $i$-th communication along channel $e$ can be scheduled. Computations, denoted by $\tau$, are also taken into account. On account of symmetry between channels $b_k$, $c_k$, and $d_k$, the communication behavior of process $k$ (including computations) can be simplified to $(d_{k+1}; \tau; d_k)$. As a complexity measure for a (concurrent) communication statement and for the computation, $\tau$, we take $\alpha$ and $\beta$ time units, respectively. We obtain the following sequence function
$$\sigma(d_k, i) = \alpha + (N-k)(\alpha+\beta) + i(2\alpha+\beta)$$
This sequence function is correct on account of $\sigma(d_k, i) - \sigma(d_{k+1}, i) = \alpha + \beta$ and $\sigma(d_{k+1}, i+1) - \sigma(d_k, i) = \alpha + \beta$. We are primarily interested in channel $b_0$. The time needed for the production of $L$ outputs along channel $b_0$ is denoted by $t(L)$. Hence, $t(L) = \sigma(d_0, L-1)$ giving
$$t(L) = \alpha(N+2L-1) + \beta(N+L-1)$$
A sequential program takes approximately $s(L) = LN\beta$ time units. For $L \gg N$, our program has a speedup of $\frac{s(L)}{t(L)} = \frac{LN\beta}{2\alpha+2\beta} = N\left(\frac{\beta}{2\alpha+\beta}\right)$. The efficiency of the program is defined by the quotient of the speedup and the number of processors used. In our example, $N$ processors are used. We, therefore, obtain an efficiency of $\frac{\beta}{2\alpha+\beta} = \frac{1}{2(\alpha/\beta)+1}$.
Notice that the communication overhead $\frac{2\alpha}{\beta}$ determines both speedup and efficiency. The larger the communication overhead the lower the speedup of the parallel program. For $\frac{2\alpha}{\beta} \approx 0$, i.e. the communication time can be neglected in comparison with the computation time, we have an optimal efficiency of 1.
3 Design of coarse grained parallel programs
The complexity analysis of the previous section shows that the efficiency of a parallel program is determined by the communication overhead $\frac{2\alpha}{\beta}$. For the OCL problem a transputer implementation would, by counting the number of cycles a computation and communication takes [8], typically give $\frac{2\alpha}{\beta} \approx 7$, yielding only $\frac{1}{8}$-th of the optimal efficiency. Although a transputer has a relatively efficient means of communication, the communication overhead of the fine grained program is too large for efficient execution (other processor networks suffer from even larger communication overheads). We, therefore, need a technique to reduce the communication overhead in order to design efficient parallel programs for processor networks. A VLSI implementation would typically give a communication overhead of $\frac{2\alpha}{\beta} \approx \frac{1}{2}$ [7].
In the remainder of this paper we discuss two techniques for reducing the communication overhead. By reducing the communication overhead we obtain parallel programs of a
One technique for enlarging the grain size of a parallel program is to compose larger processes from a number of processes, say $M$, of the fine grained program. This technique is called an $[M,1]$-transformation. The computation time within such a process increases by a factor $M$, giving a communication overhead of $\frac{2\alpha}{M\beta}$. A second technique for enlarging the grain size is a combination of composing larger processes and composing larger messages, i.e. messages that consist of a number of values that are communicated as a single packet. Assuming that a communication takes a communication setup time and a number of time units depending on the amount of data to be transferred, we are able to save $(K-1)$ times a communication setup time by transferring a single packet of $K$ values instead of $K$ single values. In the sequel, we will always compose $K$ processes of the fine grained program when introducing packet size $K$, thereby expecting a communication overhead of at most $\frac{2\alpha}{K\beta}$. We refer to this technique as a $[K,K]$-transformation.
### 3.1 The $[M,1]$-transformation
In an $[M,1]$-transformation the computation time within a process is increased by composing a process from $M$ processes of the fine grained program. The fine grained program for the OCL problem consists of $N$ processes. As a result, the program obtained by applying an $[M,1]$-transformation consists of $\frac{N}{M}$ processes (assume that $M$ is a divisor of $N$). With each process $k$ ($0 \leq k < \frac{N}{M}$) of the transformed program we associate an output channel $B_k$ that is specified as
$$B_k(i) = (\# j : i - N + kM < j \leq i : A(j) = A(i))$$
Notice that process 0 produces output stream $B$, since $B(i) = B_0(i)$. For process $k$ ($k \neq \frac{N}{M} - 1$) we derive
$$B_k(i) = \{\text{specification } B_k\}$$
$$= (\# j : i - N + kM < j \leq i : A(j) = A(i))$$
$$= \{\text{split off } j : i - N + kM < j \leq i - N + (k+1)M\}$$
$$= (\# j : i - N + kM < j \leq i - N + (k+1)M : A(j) = A(i))$$
$$+ (\# j : i - N + (k+1)M < j \leq i : A(j) = A(i))$$
$$= \{\text{rewrite range of quantification; specification } B_{k+1}\}$$
$$= (\# j : 0 < j \leq M : A(kM + i - N + j) = A(i)) + B_{k+1}(i)$$
From this relation we infer that $A(i)$ and $A(kM + i - N .. (k+1)M + i - N)$ are needed for the computation of $B_k(i)$. We decide that $A((k+1)M + i - N)$ and $A(i)$ are communicated to process $k$ by process $k+1$ along channels $C_{k+1}$ and $D_{k+1}$. This gives rise to the following two specifications
$$C_k(i) = A(i - N + kM)$$
$$D_k(i) = A(i)$$
Moreover, we introduce array \( V \) of dimension \( M \) local to process \( k \) satisfying
\[
V(h) = A(i-N+kM+h)
\]
for \( 0 \leq h < M \). With these definitions we come to the following structure of the program of process \( k \) in which only statement list \( S \) has to be determined
\[
m := 0; \text{do } m \neq M \rightarrow V(m) := 0; m := m + 1 \text{ od}
\]
\[
i := 0;
\]
\[
( B_{k+1} ?vb, C_{k+1} ?vc, D_{k+1} ?vd
\]
\[
\{ V(h) = A(i-N+kM+h) \land vb = B_{k+1}(i) \land vc = C_{k+1}(i) \land vd = D_{k+1}(i) \}
\]
\[
S
\]
\[
\{ V(h) = A(i+1-N+kM+h) \land vb = B_k(i) \land vc = C_k(i) \land vd = D_k(i) \}
\]
\[
; B_k!vb, C_k!vc, D_k!vd
\]
\[
i := i + 1
\]
\]
For statement list \( S \) we find
\[
vc, V(0) := V(0), vc
\]
\[
m := 0; \text{do } m \neq M-1 \rightarrow V(m), V(m+1) := V(m+1), V(m); m := m + 1 \text{ od}
\]
\[
vb := vb + (#j : 0 \leq j < M : V(m) = vd)
\]
Array \( V \) can more efficiently be implemented as a cyclic array. Therefore, the execution time of \( S \) is determined by the calculation of \( B_k(i) \), i.e. assignment of variable \( vb \).
In the above program we have, apart from some auxiliary variables, \( M+3 \) variables, viz. array \( V \) and variables \( vb \), \( vc \), and \( vd \).
As expected, an \([M,1]\)-transformation where \( M=1 \) yields a program that resembles the fine grained solution of the OCL problem.
### 3.2 The \([K, K]\)-transformation
In a \([K, K]\)-transformation not only the computation time is increased by composing larger processes out of processes of the fine grained solution, but also the communication time is decreased by composing larger messages. Communication time of a messages containing \( K \) values is modeled as \( \alpha_0+\alpha_1 \), where \( \alpha_0+\alpha_1 \) is the time for communicating a single value: \( \alpha_0+\alpha_1=\alpha \). Since \( K \) fine grained processes are composed, the number of processes in a \([K, K]\)-transformation is \( N/K \). Along output channel \( b_h \) of process \( h \) arrays of values are communicated. The \( p \)-th index of the array communicated in the \( i \)-th communication along channel \( b_h \) is denoted by \( b_h(i)[p] \) and specified as \( (0\leq h< N/K) \)
\[
\bar{b}_h(i)[p] = (#j : ik+p-N+hK < j \leq ik+p : A(j) = A(iK+p))
\]
for \( i \geq 0 \) and \( 0 \leq p < K \). Notice that \( \bar{b}_0(i)[p] = B(iK+p) \). In the derivation of a program for the \([K, K]\)-transformation two additional output channels, \( \bar{c}_h \) and \( \bar{d}_h \), for process \( h \) have to
be introduced (cf. derivations of the fine grained program and the $[M, 1]$-transformation). The specification of both channels is
\[
\begin{align*}
\tilde{c}_h(i)[p] &= A((i+h)K-N+p) \\
\tilde{d}_h(i)[p] &= A(iK+p)
\end{align*}
\]
Given these specifications we derive for $\tilde{b}_h(i)[p]$ ($0 \leq h < \frac{N}{K} - 1$)
\[
\begin{align*}
\tilde{b}_h(i)[p] &= \{ \text{ specification } \tilde{b}_h \} \\
\quad \{ \text{ specification } \tilde{b}_{h+1} \} \\
\quad \{ \text{ split range of quantification; specification } \tilde{b}_{h+1} \} \\
\quad \{ \text{ calculus } \}
\end{align*}
\]
The program text of process $h$ for the $[K, K]$-transformation now boils down to
\[
p := 0; \text{do } p \neq K \rightarrow VCC(p) := 0; p := p + 1 \text{ od}
\]
\[
\begin{align*}
&; ( \tilde{b}_{h+1} ! V B, \tilde{c}_{h+1} ! V C, \tilde{d}_{h+1} ! V D \\
&; p := 0 \\
&; \text{do } p \neq K \\
&; \quad \quad + (\# j : 0 < j \leq K \land p+j \geq K : V C[p+j-K] = V D[p]) \\
&; \quad ; p := p + 1 \\
&; \text{od}
\end{align*}
\]
where variables $V B, V C, V CC,$ and $V D$ are arrays of dimension $K$.
### 3.3 A complexity analysis
The programs of both the $[M, 1]$-transformation and the $[K, K]$-transformation have the same structure as the fine grained program of Section 2.3. For the communication time and
computation time of the \([M, 1]\)-transformation we take \(\alpha\) and \(M\beta\) time units, respectively. Considering that the number of processes equals \(\frac{N}{M}\), we have
\[
\sigma(D, t) = \alpha + \left(\frac{N}{M} - k\right)(\alpha + M\beta) + i(2\alpha + M\beta)
\]
The time for producing \(L\) outputs along channel \(B_0\), denoted by \(t_M(L)\), then is
\[
t_M(L) = \sigma(D_0, L - 1) = \alpha\left(\frac{N}{M} + 2L - 1\right) + \beta(N + LM - M)
\]
resulting in a speedup of \(\frac{LN\beta}{2La + LM\beta} = \frac{N}{M}\left(\frac{M\beta}{2\alpha + M\beta}\right)\) and an efficiency of \((\frac{1}{(2\alpha/M\beta)+1})\), for \(L \gg N\). The communication overhead for an \([M, 1]\)-transformation is \(\frac{2\alpha}{M\beta}\), like we expected it to be.
For the communication time and computation time of the \([K, K]\)-transformation we take \(\alpha_0 + Ka_1\) and \(K^2\beta\) time units, respectively. Here, the number of processors equals \(\frac{N}{K}\). We have
\[
\sigma(\tilde{d}_h, i) = (\alpha_0 + Ka_1) + \left(\frac{N}{K} - h\right)((\alpha_0 + Ka_1) + K^2\beta) + i(2(\alpha_0 + Ka_1) + K^2\beta)
\]
If the time needed for the production of \(L\) outputs along channel \(\tilde{b}_0\) is denoted by \(t_K(L)\), we have
\[
t_K(L) = \sigma(\tilde{d}_0, \frac{L}{K} - 1) = (\alpha_0 + Ka_1)\left(\frac{N}{K} + 2\frac{L}{K} - 1\right) + \beta(NK + LK - K^2)
\]
since \(\frac{L}{K}\) messages contain \(L\) values. As a result, we obtain a speedup of \(\frac{L\beta}{2(\frac{L}{K})/(\alpha_0 + Ka_1) + LK\beta} = \frac{N}{K}\left(\frac{K^2\beta}{2(\alpha_0 + Ka_1) + K^2\beta}\right)\) and an efficiency of \((\frac{1}{(2\alpha_0/(\alpha_0 + Ka_1) + K^2\beta)+1})\). As expected, the \([K, K]\)-transformation yields a communication overhead of \(\frac{2(\alpha_0 + Ka_1)}{K^2\beta} (\leq \frac{2\alpha_0}{K^{2}\beta} = \frac{2\alpha_0}{K\beta})\).
Next, we consider the number of variables needed in the programs. Auxiliary variables are not considered. In the fine grained program, 4 variables have been declared for each process, resulting in a total number of \(4N\) variables. A process of the \([M, 1]\)-transformation requires \(M+3\) variables. This results in \(\frac{N}{M}(M+3) = N + \frac{3N}{M}\) variables, since a program consists of \(\frac{N}{M}\) processes. For the \([K, K]\)-transformation, we obtain a total of \(4N\) variables.
In VLSI, one of the main design restrictions, chip area, depends mostly on the number of variables needed in the program and an \([M, 1]\)-transformation offers the possibility to reduce that number.
4 Experimental results
In this section we present the experimental results obtained from an OCCAM implementation of the OCL problem on a 51 T800-transputer network. Experimental results will be related to the complexity analysis of the previous section.
In the implementation each processor executes at most one process. This choice resembles the assumptions made in the complexity analysis and, thereby, makes verification of theoretical results by experiments possible. Allocating multiple processes at a single
processor requires another theoretical complexity analysis that is beyond the scope of this paper.
In the experiments, we do not measure the time for producing \(L\) output values, but for consuming \(L\) input values (i.e., we consider throughput). The reason for that is not fundamental, it only made the implementation simpler. When verifying the theoretical results we should consider the sequence function of the input channel, instead of the output channel.
### 4.1 Experimental Results for the \([M, 1]\)-transformation
We carried out experiments for two problem instances, viz. one problem of problem size \(N=50\) and one of problem size \(N=500\). We measured the time for consuming \(L=100,000\) input values. The results are summarized in the following table (\(et =\) elapsed time in ms; \(pr =\) number of processes involved in the computation)
<table>
<thead>
<tr>
<th>(N = 50)</th>
<th>(M)</th>
<th>(et)</th>
<th>(pr)</th>
<th>(N = 500)</th>
<th>(M)</th>
<th>(et)</th>
<th>(pr)</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>1</td>
<td>2781</td>
<td>50</td>
<td></td>
<td>10</td>
<td>5301</td>
<td>50</td>
</tr>
<tr>
<td></td>
<td>2</td>
<td>3060</td>
<td>25</td>
<td></td>
<td>20</td>
<td>8267</td>
<td>25</td>
</tr>
<tr>
<td></td>
<td>5</td>
<td>3900</td>
<td>10</td>
<td></td>
<td>25</td>
<td>9707</td>
<td>20</td>
</tr>
<tr>
<td></td>
<td>50</td>
<td>5300</td>
<td>5</td>
<td></td>
<td>50</td>
<td>16899</td>
<td>10</td>
</tr>
<tr>
<td></td>
<td>25</td>
<td>9700</td>
<td>2</td>
<td></td>
<td>100</td>
<td>31299</td>
<td>5</td>
</tr>
<tr>
<td></td>
<td>50</td>
<td>16100</td>
<td>1</td>
<td></td>
<td>250</td>
<td>74499</td>
<td>2</td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td>500</td>
<td>149742</td>
<td>1</td>
</tr>
</tbody>
</table>
Experimental results for \([M, 1]\)-transformation
Notice the scalability of the algorithm by comparing the results that have the same parameter \(M\). Notice, also, that the computation time increases, resulting in a smaller speedup. The efficiency, however, increases. As usual, there is a trade-off between speedup and efficiency.
For consumption of \(L\) input values, the theoretical complexity analysis gives
\[
\sigma(D_{N/M}, L-1) = (2L-1)\alpha + M(L-1)\beta
\]
Given this formula and the experimental results, we obtain 13 equations from which \(\alpha\) and \(\beta\) can be deduced. We find
\[
\alpha = 12.33 \mu s \\
\beta = 2.88 \mu s
\]
with an accuracy of more than 99%. As a result, the ratio \(\frac{2\alpha}{\beta}\) equals 8.6 which comes close to the estimated communication overhead of \(\frac{2\alpha}{\beta} \approx 7\), considering the fact that a
receiving process may not always want to accept a communication immediately. The sequential execution time, \( LN/\beta \), is 14.4 sec. and 144 sec. for problem size \( N=50 \) and \( N=500 \), respectively. As an example of the trade-off between speedup and efficiency, for problem size \( N=500 \) we have: \( M=10 \) gives a speedup of 27.1 and an efficiency of 54\%, and \( M=100 \) gives a speedup of 4.6 and an efficiency of 92\%.
### 4.2 Experimental results for the \([K, K]\)-transformation
For the \([K, K]\)-transformation the same experiments have been carried out as for the \([M, 1]\)-transformation. The results are summarized in the following table (\( L = 100,000 \))
<table>
<thead>
<tr>
<th>( N = 50 )</th>
<th>( N = 500 )</th>
</tr>
</thead>
<tbody>
<tr>
<td>( K )</td>
<td>( et )</td>
</tr>
<tr>
<td>1</td>
<td>2883</td>
</tr>
<tr>
<td>2</td>
<td>2559</td>
</tr>
<tr>
<td>5</td>
<td>2938</td>
</tr>
<tr>
<td>10</td>
<td>4012</td>
</tr>
<tr>
<td>25</td>
<td>7663</td>
</tr>
<tr>
<td>50</td>
<td>13136</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Experimental results for \([K, K]\)-transformation
For the consumption of \( L \) input values, the theoretical complexity analysis gives
\[
\sigma(d_{N/K}, \frac{L}{K}-1) = (2 \frac{L}{K}-1)(\alpha_0 + K\alpha_1) + K^2(\frac{L}{K}-1)\beta
\]
We have 13 equations for parameters \( \alpha_0 \), \( \alpha_1 \), and \( \beta \) and obtain
\[
\begin{align*}
\alpha_0 & = 5.77 \mu s \\
\alpha_1 & = 7.42 \mu s \\
\beta & = 2.45 \mu s
\end{align*}
\]
with an accuracy of more than 99\%. Given \( t_K(L) \), the time for producing \( L \) outputs, we infer that for large \( L \) the execution time is minimized for \( K = \sqrt{\frac{2\alpha_0}{\beta}} \). In this case, we find \( K=2.2 \). The experimental results indeed show that the execution time for \( K=2 \) is less than the execution time for \( K=1 \).
### 5 Concluding Remarks
In this paper we have presented two techniques for designing parallel programs of a parameterized grain size. Such a program offers the attractive possibility of tuning it to the
characteristics of the machine on which it is executed. This fact is the more advantageous since it often is a priori not clear what the grain size of a program should be in order to obtain a good performance.
Both techniques started from a fine grained solution. In the \([M, 1]\)-transformation we compose \(M\) cells of the fine grained solution resulting in a larger cell. In the \([K, K]\)-solution we not only compose \(K\) cells of the fine grained program, but also compose larger messages by combining \(K\) communications into a single packet. In both techniques we are able to control the communication overhead of an implementation by setting the parameter to an appropriate value. In fact, both techniques are instances of a more general technique, the \([M, K]\)-transformation, in which \(M\) cells are composed and in which \(K\) communications are composed into a single packet. It can be shown that given a fine grained program (of a certain regular structure) it is always possible to apply an \([M, K]\)-transformation, provided that \(K\) is a divisor of \(M\). Designing an application now boils down to two steps, viz. designing a fine grained program and applying an \([M, K]\)-transformation [9]. By this approach we can benefit from the experience gained in the design of fine grained programs [10, 5, 4].
It is possible to implement our programs in VLSI [7]. In VLSI, chip area is one of the main design restrictions. We have seen that applying an \([M, 1]\)-transformation can reduce the total number of variables of a program and thereby reduce the chip area needed. Experiments with the DICY system at the Philips Research Laboratories have indeed demonstrated this property of the transformation.
We have carried out a number of experiments on a 51 T800-transputer network. For both the \([M, 1]\)-transformation and the \([K, K]\)-transformation the experimental results are conform to the theoretical complexity analysis. In the experiments, each process is allocated to a separate processor. The computation will be more efficient if a number of processes share a processor, e.g. by a cyclic allocation scheme. In that case, however, the theoretical results presented in this paper do not apply anymore.
**In this series appeared:**
<table>
<thead>
<tr>
<th>Volume</th>
<th>Authors</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>89/1</td>
<td>E.Zs. Lepoeter-Molnar</td>
<td>Reconstruction of a 3-D surface from its normal vectors.</td>
</tr>
<tr>
<td>89/2</td>
<td>R.H. Mak</td>
<td>A systolic design for dynamic programming.</td>
</tr>
<tr>
<td></td>
<td>P. Struik</td>
<td></td>
</tr>
<tr>
<td>89/3</td>
<td>H.M.M. Ten Eikelder C. Hemerik</td>
<td>Some category theoretical properties related to a model for a polymorphic lambda-calculus.</td>
</tr>
<tr>
<td>89/4</td>
<td>J. Zwiers W.P. de Roever</td>
<td>Compositionality and modularity in process specification and design: A trace-state based approach.</td>
</tr>
<tr>
<td>89/5</td>
<td>Wei Chen T. Verhoeff J.T. Udding</td>
<td>Networks of Communicating Processes and their (De-)Composition.</td>
</tr>
<tr>
<td>89/6</td>
<td>T. Verhoef</td>
<td>Characterizations of Delay-Insensitive Communication Protocols.</td>
</tr>
<tr>
<td>89/7</td>
<td>P. Struik</td>
<td>A systematic design of a parallel program for Dirichlet convolution.</td>
</tr>
<tr>
<td>89/9</td>
<td>K.M. van Hee P.M.P. Rambags</td>
<td>Discrete event systems: Dynamic versus static topology.</td>
</tr>
<tr>
<td>89/10</td>
<td>S. Ramesh</td>
<td>A new efficient implementation of CSP with output guards.</td>
</tr>
<tr>
<td>89/11</td>
<td>S. Ramesh</td>
<td>Algebraic specification and implementation of infinite processes.</td>
</tr>
<tr>
<td>89/12</td>
<td>A.T.M. Aerts K.M. van Hee</td>
<td>A concise formal framework for data modeling.</td>
</tr>
<tr>
<td>89/14</td>
<td>H.C. Haesen</td>
<td>ELDA, data manipulatie taal.</td>
</tr>
<tr>
<td>89/15</td>
<td>J.S.C.P. van der Woude</td>
<td>Optimal segmentations.</td>
</tr>
<tr>
<td>89/16</td>
<td>A.T.M. Aerts K.M. van Hee</td>
<td>Towards a framework for comparing data models.</td>
</tr>
<tr>
<td>89/17</td>
<td>M.J. van Diepen K.M. van Hee</td>
<td>A formal semantics for Z and the link between Z and the relational algebra.</td>
</tr>
</tbody>
</table>
Formal methods and tools for the development of distributed and real time systems, p. 17.
Dynamic process creation in high-level Petri nets, pp. 19.
Foundations of Compositional Program Refinement - safety properties -, p. 38.
Decomposition of delay-insensitive circuits, p. 25.
On the delay-sensitivity of gate networks, p. 23.
A logic for one-pass, one-attributed grammars, p. 14.
Receptive Process Theory, p. 16.
Combining the functional and the relational model, p. 15.
A formal semantics for Z and the link between Z and the relational algebra, p. 30. (Revised version of CSNotes 89/17).
A proof system for process creation, p. 84.
A proof theory for a sequential version of POOL, p. 110.
Proving termination of Parallel Programs, p. 7.
A proof system for the language POOL, p. 70.
Compositionality in the temporal logic of concurrent systems, p. 17.
A fully abstract model for concurrent logic languages, p. p. 23.
On the asynchronous nature of communication in logic languages: a fully abstract model based on sequences, p. 29.
<table>
<thead>
<tr>
<th>Session</th>
<th>Authors</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>91/02</td>
<td>R.P. Nederpelt, H.C.M. de Swart</td>
<td>Implication. A survey of the different logical analyses "if..., then...", p. 26.</td>
</tr>
<tr>
<td>91/03</td>
<td>J.P. Katoen, L.A.M. Schoenmakers</td>
<td>Parallel Programs for the Recognition of P-invariant Segments, p. 16.</td>
</tr>
<tr>
<td>91/05</td>
<td>D. de Reus</td>
<td>An Implementation Model for GOOD, p. 18.</td>
</tr>
<tr>
<td>91/06</td>
<td>K.M. van Hee</td>
<td>SPECIFICATIEMETHODEN, een overzicht, p. 20.</td>
</tr>
<tr>
<td>91/07</td>
<td>E. Poll</td>
<td>CPO-models for second order lambda calculus with recursive types and subtyping, p. 49.</td>
</tr>
<tr>
<td>91/12</td>
<td>E. van der Sluis</td>
<td>A parallel local search algorithm for the travelling salesman problem, p. 12.</td>
</tr>
<tr>
<td>91/14</td>
<td>P. Lemmens</td>
<td>The PDB Hypermedia Package. Why and how it was built, p. 63.</td>
</tr>
</tbody>
</table>
An example of proving attribute grammars correct: the representation of arithmetical expressions by DAGs, p. 25.
Transforming Functional Database Schemes to Relational Representations, p. 21.
Transformational Query Solving, p. 35.
Some categorical properties for a model for second order lambda calculus with subtyping, p. 21.
Assertional Data Reification Proofs: Survey and Perspective, p. 18.
Z and high level Petri nets, p. 16.
Formal semantics for BRM with examples, p. 25.
A compositional proof system for real-time systems based on explicit clock temporal logic: soundness and completeness, p. 52.
The GOOD based hypertext reference model, p. 12.
Embedding as a tool for language comparison: On the CSP hierarchy, p. 17.
A compositional proof system for dynamic process creation, p. 24.
Correctness of Acceptor Schemes for Regular Languages, p. 31.
An Algebra for Process Creation, p. 29.
<table>
<thead>
<tr>
<th></th>
<th>Authors</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>91/31</td>
<td>H. ten Eikelder</td>
<td>Some algorithms to decide the equivalence of recursive types, p. 26.</td>
</tr>
<tr>
<td>91/33</td>
<td>W. v.d. Aalst</td>
<td>The modelling and analysis of queueing systems with QNM-ExSpect, p. 23.</td>
</tr>
<tr>
<td>91/34</td>
<td>J. Coenen</td>
<td>Specifying fault tolerant programs in deontic logic, p. 15.</td>
</tr>
<tr>
<td>92/01</td>
<td>J. Coenen, J. Zwiers, W.-P. de Roever</td>
<td>A note on compositional refinement, p. 27.</td>
</tr>
<tr>
<td>92/02</td>
<td>J. Coenen, J. Hooman</td>
<td>A compositional semantics for fault tolerant real-time systems, p. 18.</td>
</tr>
<tr>
<td>92/03</td>
<td>J.C.M. Baeten, J.A. Bergstra</td>
<td>Real space process algebra, p. 42.</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://pure.tue.nl/ws/files/1736111/9211272.pdf", "len_cl100k_base": 10818, "olmocr-version": "0.1.50", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 50833, "total-output-tokens": 13238, "length": "2e13", "weborganizer": {"__label__adult": 0.0003740787506103515, "__label__art_design": 0.0005860328674316406, "__label__crime_law": 0.0004549026489257813, "__label__education_jobs": 0.0021800994873046875, "__label__entertainment": 0.0001270771026611328, "__label__fashion_beauty": 0.00020825862884521484, "__label__finance_business": 0.0005006790161132812, "__label__food_dining": 0.0005407333374023438, "__label__games": 0.0008001327514648438, "__label__hardware": 0.0027484893798828125, "__label__health": 0.001251220703125, "__label__history": 0.0005345344543457031, "__label__home_hobbies": 0.0002186298370361328, "__label__industrial": 0.0010938644409179688, "__label__literature": 0.0003943443298339844, "__label__politics": 0.0004074573516845703, "__label__religion": 0.0008258819580078125, "__label__science_tech": 0.44189453125, "__label__social_life": 0.0001270771026611328, "__label__software": 0.0078887939453125, "__label__software_dev": 0.53515625, "__label__sports_fitness": 0.00039505958557128906, "__label__transportation": 0.0009908676147460938, "__label__travel": 0.0002536773681640625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42352, 0.03383]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42352, 0.33465]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42352, 0.8242]], "google_gemma-3-12b-it_contains_pii": [[0, 2055, false], [2055, 2266, null], [2266, 2881, null], [2881, 4863, null], [4863, 7825, null], [7825, 9763, null], [9763, 12052, null], [12052, 15269, null], [15269, 17871, null], [17871, 20419, null], [20419, 21828, null], [21828, 24938, null], [24938, 27370, null], [27370, 29594, null], [29594, 32518, null], [32518, 33433, null], [33433, 36111, null], [36111, 37217, null], [37217, 40116, null], [40116, 41204, null], [41204, 42352, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2055, true], [2055, 2266, null], [2266, 2881, null], [2881, 4863, null], [4863, 7825, null], [7825, 9763, null], [9763, 12052, null], [12052, 15269, null], [15269, 17871, null], [17871, 20419, null], [20419, 21828, null], [21828, 24938, null], [24938, 27370, null], [27370, 29594, null], [29594, 32518, null], [32518, 33433, null], [33433, 36111, null], [36111, 37217, null], [37217, 40116, null], [40116, 41204, null], [41204, 42352, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42352, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42352, null]], "pdf_page_numbers": [[0, 2055, 1], [2055, 2266, 2], [2266, 2881, 3], [2881, 4863, 4], [4863, 7825, 5], [7825, 9763, 6], [9763, 12052, 7], [12052, 15269, 8], [15269, 17871, 9], [17871, 20419, 10], [20419, 21828, 11], [21828, 24938, 12], [24938, 27370, 13], [27370, 29594, 14], [29594, 32518, 15], [32518, 33433, 16], [33433, 36111, 17], [36111, 37217, 18], [37217, 40116, 19], [40116, 41204, 20], [41204, 42352, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42352, 0.17692]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
74ef9aba2dad54c3fd53c6ee62abb22a9bd8480f
|
Register allocation: what does Chaitin’s NP-completeness proof really prove?
Florent Bouchez, Alain Darte, Fabrice Rastello
To cite this version:
HAL Id: hal-02102286
https://hal-lara.archives-ouvertes.fr/hal-02102286
Submitted on 17 Apr 2019
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Register Allocation: What does Chaitin’s NP-completeness Proof Really Prove?
Florent Bouchez
Alain Darte
Fabrice Rastello
March 2006
Research Report N° 2006-13
Register Allocation: What does Chaitin’s NP-completeness Proof Really Prove?
Florent Bouchez, Alain Darte, and Fabrice Rastello
March 2006
Abstract
Register allocation is one of the most studied problem in compilation. It is considered as an NP-complete problem since Chaitin, in 1981, showed that assigning temporary variables to \( k \) machine registers amounts to color, with \( k \) colors, the interference graph associated to variables and that this graph can be arbitrary, thereby proving the NP-completeness of the problem. However, this original proof does not really show where the complexity comes from. Recently, the re-discovery that interference graphs of SSA programs can be colored in polynomial time raised the question: Can we exploit SSA to perform register allocation in polynomial time, without contradicting Chaitin’s NP-completeness result? To address such a question, we revisit Chaitin’s proof to better identity the interactions between spilling (load/store insertion), coalescing/splitting (moves between registers), critical edges (a property of the control-flow graph), and coloring (assignment to registers). In particular, we show when it is easy to decide if temporary variables can be assigned to \( k \) registers or if some spilling is necessary. The real complexity comes from critical edges, spilling, and coalescing, which are addressed in our other reports.
Keywords: Register allocation, SSA form, chordal graph, NP-completeness, critical edge.
RÉsumé
L’allocation de registres est l’un des problèmes les plus étudiés en compilation. On le considère en général NP-complet depuis que Chaitin, en 1981, a montré qu’affecter des variables temporaires à \( k \) registres physiques revient à colorier avec \( k \) couleurs le graphe d’interférences associé aux variables et que ce graphe peut être quelconque. En revanche, cette démonstration ne révèle pas vraiment d’où vient la complexité. Récemment, la re-découverte que les graphes d’interférence des programmes SSA peuvent être coloriés en temps polynomial a conduit à la question : peut-on exploiter la forme SSA pour faire de l’allocation de registres en temps polynomial sans contredire la preuve de Chaitin ? Pour répondre à ce genre de questions, nous revisitions la démonstration de Chaitin pour mieux identifier les interactions entre le “spilling” (insertion de store/load), le “coalescing”/“splitting” (moves entre registres), la présence d’arcs critiques (une propriété du graphe de flot de contrôle) et le coloriage proprement dit (affectation aux registres). En particulier, nous montrons quand il est facile de décider si des variables temporaires peuvent être affectées à \( k \) registres ou si du “spilling” est nécessaire. La vraie complexité du problème d’allocation de registres provient de la présence d’arcs critiques, du “spilling” et du “coalescing”, problèmes que nous considérons dans nos autres rapports.
Mots-clés: Allocation de registres, forme SSA, graphe triangulé, NP-complétude, arc critique.
Register Allocation: What does Chaitin’s NP-completeness Proof Really Prove?
Florent Bouchez, Alain Darte, and Fabrice Rastello
13th March 2006
Abstract
Register allocation is one of the most studied problem in compilation. It is considered as an NP-complete problem since Chaitin, in 1981, showed that assigning temporary variables to \( k \) machine registers amounts to color, with \( k \) colors, the interference graph associated to variables and that this graph can be arbitrary, thereby proving the NP-completeness of the problem. However, this original proof does not really show where the complexity comes from. Recently, the re-discovery that interference graphs of SSA programs can be colored in polynomial time raised the question: Can we exploit SSA to perform register allocation in polynomial time, without contradicting Chaitin’s NP-completeness result? To address such a question, we revisit Chaitin’s proof to better identity the interactions between spilling (load/store insertion), coalescing/splitting (moves between registers), critical edges (a property of the control-flow graph), and coloring (assignment to registers). In particular, we show when it is easy to decide if temporary variables can be assigned to \( k \) registers or if some spilling is necessary. The real complexity comes from critical edges, spilling, and coalescing, which are addressed in our other reports.
1 Introduction
Register allocation is one of the most studied problem in compilation. Its goal is to find a way to map the temporary variables used in a program into physical memory locations (either main memory or machine registers). Accessing a register is much faster than accessing memory, therefore one tries to use registers as much as possible. Of course, this is not always possible, thus some variables must be transfer (“spilled”) to and from memory. This has a cost, the cost of load and store operations, that should be avoided as much as possible.
Classical approaches are based on fast graph coloring algorithms (sometimes combined with techniques dedicated to basic blocks). A widely-used algorithm is iterated register coalescing proposed by Appel and George [12], a modified version of previous developments by Chaitin [6, 5], and Briggs et al. [3]. In these heuristics, spilling, coalescing (removing register-to-register moves), and coloring (assigning a variable to a register) are done in the same framework. Priorities among these transformations are done implicitly with cost functions. Splitting (adding register-to-register moves) can also be integrated in this framework.
Such techniques are well-established and used in any optimizing compiler. However, there are at least four reasons to revisit these approaches.
1. Today’s processors are now much faster than in the past, especially faster than when Chaitin developed his first heuristic (in 1981). Some algorithms not considered in the past, because they were too time-consuming, can be good candidates today.
2. For some critical applications, especially in embedded computing, industrial compilers are ready to accept longer compilation times if the final code gets improved.
3. The increasing cost of a memory access compared to a register access suggests that it is maybe better now to focus on heuristics that give more importance to spilling cost minimization, possibly at the price of additional register-to-register moves, in other words, heuristics that consider the trade-off spilling/coalescing as unbalanced.
4. There are many pitfalls and folk theorems, concerning the complexity of the register allocation problem, that need to be clarified.
This last point is particularly interesting to note. In 1981, Chaitin [6] showed that allocating variables of a program to \( k \) registers amounts to color with \( k \) colors the corresponding interference graph (two variables interfere if they are simultaneously live). As he was able to produce a code corresponding to an arbitrary interference graph and because graph coloring is NP-complete [11, Problem GT4], heuristics have been used for everything: spilling, coalescing, splitting, coloring, etc. Except in a few papers where authors are more careful, the previous argument (register allocation is graph coloring, therefore it is NP-complete) is one of the first sentences of any paper on register allocation. This way of presenting Chaitin’s proof can make the reader (researcher or student) believe more than what this proof actually shows. In particular, it is in the common belief that, when no instruction scheduling is allowed, deciding if some spilling is necessary to allocate variables to \( k \) registers is NP-complete. This is not what Chaitin proves. We will even show that this particular problem is not NP-complete except for a few particular cases (we will make clear which one), which is maybe a folk theorem too. Actually, going from register allocation to graph coloring is just a way of modeling the problem, but it is not an equivalence. In particular, this model does not take into account the fact that a variable can be moved from a register to another one (splitting), of course at some cost, but only the cost of a move instruction (which is often better than a spill).
Until very recently, only a few authors tried to address the complexity of register allocation in more details. Maybe the most interesting complexity results are those of Liberatore et al. [16, 9], who analyze the reasons why optimal spilling is hard for local register allocation (i.e., register allocation for basic blocks). In brief, for basic blocks, the coloring phase is of course easy (the interference graph is an interval graph) but deciding which variable to spill and where is difficult (when stores and loads have nonzero costs). We completed this study for various models of spill cost in [2].
Today, most compilers go through an intermediate code representation, the (strict) SSA form (static single assignment) [7], which makes many code optimizations simpler. In such a code, each variable is defined textually only once and is alive only along the dominance tree associated to the control-fbw graph. Some so-called \( \phi \) functions are used to transfer values along the control fbw not covered by the dominance tree. The consequence is that the interference graph of such a code is, again, not arbitrary: it is a chordal graph, therefore easy to color. Furthermore, it can be colored with \( k \) colors if and only Maxlive \( \leq k \) where Maxlive is the maximal number of variables simultaneously live. What does this property imply? One can imagine to decompose the register allocation problem into two phases. The first phase (also
called allocation in [16]) decides what values are spilled and where, so as to get to a code where Maxlive ≤ k. A second phase of coloring (called register assignment in [16]) maps variables to registers, possibly removing (i.e., coalescing) or introducing (i.e., splitting) move instructions (also called shuffle code in [17]). Considering that loads and stores are more expensive than moves, such an approach is worth exploring. This is the approach advocated by Appel and George [1] and, more recently, in [4, 2, 14].
The fact that interference graphs of strict SSA programs are chordal is well-known (if one makes the connection between graph theory and SSA form). Indeed, a theorem of Walter (1972), Gavril (1974), and Buneman (1974) (see [13, Theorem 4.8]) shows that an interference graph is chordal if and only if it is the interference graph of a family of subtrees (here the live ranges of variables) of a tree (here the dominance tree). Furthermore, maximal cliques correspond to program points. We re-discovered this property in 2002 when teaching to students that register allocation is indeed in general NP-complete but certainly not just because graph coloring is NP-complete. Independently, Brisk et al. [4], Perreira and Palsberg [18], and Hack et al. [14] made the same observation. A direct proof of the chordality property for strict SSA programs can be given, see for example [2, 14].
Recent work has been done on how to go out of SSA [15, 21, 20] and remove ϕ functions, which are not machine code. How to avoid permutations of colors at ϕ points is also addressed in [14]. These work combined with the idea of spilling before coloring so that Maxlive ≤ k has led Perreira and Palsberg [19] to wonder where the NP-completeness of Chaitin’s proof (apparently) disappeared: “Can we do polynomial-time register allocation by first transforming the program to SSA form, then doing linear-time register allocation for the SSA form, and finally doing SSA elimination while maintaining the mapping from temporaries to registers?” (all this when Maxlive ≤ k of course, otherwise some spilling needs to be done). They show that the answer is no, the problem is NP-complete.
The NP-completeness proof of Perreira and Palsberg is interesting, but it does not completely answer the question. It shows that if we choose the splitting points a priori (in particular as ϕ points), then it is NP-complete to choose the right colors. However, there is no reason to fix these particular split points. We show in this paper that, when we can choose the split points, when we are free to add program blocks so as to remove critical edges (as this is often done), when Maxlive ≤ k, then it is in general easy to decide if and how we can assign variables to registers without spilling. More generally, the goal of this paper is to discuss the implications of Chaitin’s proof (and what it does not imply) concerning the interactions between spilling, splitting, coalescing, critical edges, and coloring.
In Section 2, we first reproduce Chaitin’s proof and analyze it more carefully. The proof shows that when the control-fbw graph has critical edges, which we are not allowed to remove with additional blocks, then it is NP-complete to decide whether k registers are enough, even if splitting variables is allowed. In Section 3, we address the same question as Perreira and Palsberg in [19]: we show that Chaitin’s proof can easily be extended to show that, when the graph has no critical edge but if splitting points are fixed (at entry and exit of basic blocks), the problem remains NP-complete. In Section 4, we show, again with a slight variation of Chaitin’s proof, that even if we can split variables wherever we want, the problem remains NP-complete, but only when there are machine instructions that can create two new variables at a time. However, in this case, it is more likely that the architecture can also perform register swap and then k registers are enough if and only if Maxlive ≤ k. Finally, we show that it is also easy to decide if k registers are enough when only one variable can be created at a given
time (as in traditional assembly code representation). Therefore, this study shows that the NP-completeness of register allocation is not due to the coloring phase (as a misinterpretation of Chaitin’s proof may suggest), but is due to the presence of critical edges or not, and to the optimization of spilling costs and coalescing costs.
2 Direct consequences of Chaitin’s proof
Let us look at Chaitin’s NP-completeness proof again. The proof is by reduction from graph coloring [11, Problem GT4]: Given an undirected graph \( G = (V, E) \) and an integer \( k \), can we color the graph with \( k \) colors, i.e., can we define, for each vertex \( v \in V \), a color \( c(v) \) in \( \{1, \ldots, k\} \) such that \( c(v) \neq c(u) \) for each edge \( (u, v) \in E \)? The problem is NP-complete if \( G \) is arbitrary, even for a fixed \( k \geq 3 \).
For the reduction, Chaitin creates a program with \( |V|+1 \) variables, one for each vertex \( u \in V \) and an additional variable \( x \), and the following structure:
- For each \((u, v) \in E\), there is a block \( B_{u,v} \) that defines \( u, v \), and \( x \).
- For each \( u \in V \), there is a block \( B_u \) that reads \( u \) and \( x \), and returns a new value.
- Each block \( B_{u,v} \) is a direct predecessor in the control-flow graph of the blocks \( B_u \) and \( B_v \).
- An entry block switches to all blocks \( B_{u,v} \).
Figure 1 shows the program associated to a cycle of length 4, with edges \((a, b), (a, c), (b, d), \) and \((c, d)\). This is also the example used in [19].

**Figure 1:** The program associated to a cycle of length 4.
It is clear that the interference graph associated to such a program is the graph \( G \) plus a vertex for variable \( x \) with an edge \((u, x)\) for each \( u \in V \) (thus this new vertex must use an extra color). If one interprets a register as a color then \( G \) is \( k \)-colorable if and only if each variable
can be assigned to a unique register for a total of at most \( k + 1 \) registers. This is what Chaitin proved, nothing less, nothing more: for such programs, deciding if one can assign the variables, this way, to \( k \geq 4 \) registers is thus NP-complete.
Chaitin’s proof, at least in its original interpretation, does not address the possibility of splitting the live range of a variable (set of program points where the variable is live\(^1\)). Each vertex of the interference graph represents the complete live range as an atomic object, in other words, it is assumed that one variable must always reside in the same register. The fact that the register allocation problem is modeled through the interference graph loses information on the program itself and the exact location of interferences (this is a well-known fact, which led to many different heuristics).
This raises the question: What if we allow to split live ranges? Consider Figure 1 again and a particular variable, for example \( a \). In block \( B_a \), variable \( a \) is needed for the instruction “return \( a + x \)”, and this value can come from blocks \( B_{a,b} \) and \( B_{a,c} \). Therefore, even if we split the live range of \( a \) in block \( B_a \) before it is used, some register must contain the value of \( a \) both at the exit of blocks \( B_{a,b} \) and \( B_{a,c} \). The same is true for all other variables. In other words, if we consider the possible copies live at exit of blocks of type \( B_{u,v} \) and at entry of blocks of type \( B_v \), we get the same interference graph \( G \) for the copies. Therefore, the problem remains NP-complete even if we allow live range splitting.
Splitting live ranges does not help here because, in the general case, the control-fbw edges from \( B_{u,v} \) to \( B_v \) are critical edges, i.e., they go from a block with more than one successor to a block with more than one predecessor. This forces the live range of a copy to span more than one edge, leading to the well-known notion of web. All copies of a given variable \( a \) are part of the same web and must be assigned the same color. In general, defining precisely what is colored is important as the subtle title of Cytron and Ferrante’s paper “What’s in a name?” pointed out\(^8\).
To conclude this section, we can interpret Chaitin’s original proof as follows. It shows that it is NP-complete to decide if the variables of an arbitrary program can be assigned to \( k \) registers, even if live range splitting is allowed, but only when the program has critical edges that we are not allowed to remove (i.e., we cannot change the structure of the control fbw graph and add new blocks). In the following section, we consider the case of programs with no critical edges. The case of programs with some critical edges with a particular structure will be addressed in another report.
### 3 SSA-like programs and fixed splitting points
In\(^{19}\), Ferreira and Palsberg pointed out that the construction of Chaitin (as done in Figure 1) is not enough to prove anything about register allocation through SSA. Indeed, to assign variables to registers for programs built as in Section 2, one just have to add extra blocks (where out-of-SSA code is traditionally inserted) and to perform some register-to-register moves in these blocks. Any such program can now be allocated with only 3 registers (see Figure 2 for a possible allocation of the program of Figure 1). Indeed, as there are no critical edges anymore,
\(^1\)Actually, Chaitin’s definition of interference is slightly different: Two variables interfere only if one is live at the definition of the other one. However, the two definitions coincide for programs where any control-fbw path from the beginning of the program to a given use of a variable goes through a definition of this variable. Such programs are called strict. This is the case for the programs we manipulate in our NP-completeness proofs.
we can color the two variables of each basic block of type $B_{u,v}$ independently and `repair`, when needed, the coloring to match the colors at each join, i.e., each basic block of type $B_u$. This is done by introducing an adequate re-mapping of registers (here a single move) in the new block along the edge from $B_{u,v}$ to $B_u$.
When there are no critical edges, one can indeed go through SSA (or any representation of live ranges as subtrees of a tree), i.e., consider that all definitions of a given variable belong to different live ranges, and to color them with $k$ colors, if possible, in linear time (because the corresponding interference graph is chordal) in a greedy fashion.
At this stage, it is of course easy to decide if $k$ registers are enough. This is possible if and only if Maxlive, the maximal number of values live at any program point, is less than $k$. Indeed, Maxlive is obviously a lower bound for the minimal number of registers needed, as all variables live at a given point interfere (at least for strict programs). Furthermore, this lower bound can be achieved by coloring because of a double property of such live ranges: a) Maxlive is equal to the size of a maximal clique in the interference graph (in general, it is only a lower bound); b) the size of a maximal clique and the chromatic number of the graph are equal (as the graph is chordal). Furthermore, if $k$ registers are not enough, additional splitting will not help as splitting does not change Maxlive.
If $k$ colors are enough, it is still possible that colors do not match at join points where live ranges were split. Some `shuffle` of registers is needed in the block along the edge where colors do not match. The fact that the edge is not critical guarantees that the shuffle will not propagate along other control flow paths. A shuffle is a permutation of the registers. If some register is
available at this program point, i.e., if Maxlive < k, then any remapping can be performed as a sequence of register-to-register moves, possibly using the free register as temporary storage. Otherwise, one additional register is needed unless one can perform register swap (arithmetic operations are also possible but maybe only for integer registers).
This view of coloring through the insertion of permutations is the base of any approach that optimizes spilling first. Some spilling is done (optimally or not) so as to reduce the register pressure (Maxlive) to at most k. In [1], this approach is even used in the most extreme form: live ranges are split at each program point in order to address the problem of optimal spilling. After the first spilling phase, there is a potential permutation between any two program points. Then, live ranges are merged back, as most as possible, thanks to coalescing.
In other words, it seems that going through SSA (for example) makes easy the problem of deciding if k registers are enough. The only possible remaining case is if we do not allow any register swap. If colors do not match at a joint point where Maxlive = k, then the permutation cannot be performed. This is the question addressed by Ferreira and Palsberg in [19]: Can we easily choose an adequate coloring of the SSA representation so that no permutation (different than identity) is needed? The answer is no, the problem is NP-complete.
To show this result, Ferreira and Palsberg use a reduction from the problem of coloring circular-arc graphs [10]. Basically, the idea is to start from a circular-arc graph, to choose a particular split point of the arcs to get an interval graph, to represent this interval graph as the interference graph of some basic block, to add a back edge to form a loop, and to make sure that Maxlive = k on the back edge. In this case, coloring the basic block so that no permutation is needed on the back edge is equivalent to coloring the original circular-arc graph. Actually, this is the same proof technique used in [10] to reduce the coloring of circular-arc graphs from a permutation problem.
This proof shows that if the split points are chosen a priori, then it is difficult to choose the right coloring of the SSA representation (and thus decide if k registers are enough) even for a simple loop and a single split point. However, for a fixed k, this specific problem is polynomial as it is the case for the k-coloring problem of circular-arc graphs. We now show that, with a simple variation of Chaitin’s proof, a similar result can be proved even for a fixed k, but for an arbitrary program.
Consider the same program structure as Chaitin does, but after critical edges have been removed, thus a program structure such as in Figure 2. Given an arbitrary graph $G = (V, E)$, the program has three variables $u, x_u, y_u$ for each vertex $u \in V$ and a variable $x_{u,v}$ for each edge $(u, v) \in E$. It has the following structure:
- For each $(u, v) \in E$, there is a block $B_{u,v}$ that defines $u, v, \text{ and } x_{u,v}$.
- For each $u \in V$, there is a block $B_u$ that reads $u, y_u, \text{ and } x_u$, and returns a new value.
- For each block $B_{u,v}$, there is a path to the blocks $B_u$ and $B_v$. Along the path from $B_{u,v}$ to $B_u$, there is a block that reads $v$ and $x_{u,v}$ to define $y_u$, and then defines $x_u$.
- An entry block switches to all blocks $B_{u,v}$.
The interference graph restricted to variables $u$ (those that correspond to vertices of $G$) is still exactly $G$. Figure 3 shows the program associated to a cycle of length 4, with edges $(a, b), (a, c), (b, d), \text{ and } (c, d)$. It has no critical edge.
Assume that permutations can be placed only along the edges, or equivalently on entry or exit of the intermediate blocks that are between blocks of type $B_{u,v}$ and type $B_{u}$. We claim that the program can be assigned to 3 registers if and only if $G$ is 3-colorable. Indeed, it is easy to see that on each control-flow edge, exactly 3 variables are live, therefore if only 3 registers are used, no permutation different than identity can be performed. As a consequence, the live range of any variable $u \in V$ cannot be split, each variable is therefore assigned to a unique color. Using the same color for the corresponding vertex in $G$ gives a 3-coloring of the $G$. Conversely, if $G$ is 3-colorable, assign to each variable $u$ the same color as the vertex $u$. It remains to color the variables $x_{a,v}$, $x_{u}$, and $y_{u}$. This is easy: in block $B_{u,v}$, only two colors are used so far, the color for $u$ and the color for $v$, so $x_{u,v}$ can be assigned the remaining color. Finally assigned $x_{a}$ to a color different than $u$, and $y_{u}$ to the remaining color. This gives a valid register assignment of the program.
Figure 3: The program associated to a cycle of length 4.
To get a similar proof for any fixed $k > 3$, just add $k - 3$ variables in the switch block and make their live ranges traverse all other blocks. What we just proved, with this slight variation of Chaitin’s proof, is that if split points are fixed (as this is traditionally the case when going out of SSA), then it is NP-complete to decide if $k$ registers are sufficient, even for a fixed $k \geq 3$ and even if the program has no critical edge.
4 When split points can be anywhere
Does the study of Section 3 completely answer the question? Not quite. Indeed, who said that split points are fixed? Why can’t we shuffle registers at any program point? Consider Figure 3 again. The register pressure is 3 on any control-flow edge, but it is not 3 everywhere. In particular, between the definitions of each \( y_u \) and each \( x_u \), the register pressure drops to 2. At this point, some register-to-register moves could be inserted to permute two colors.
Actually, if we allow to split wherever we want then, for such a program, 3 registers are always enough. Indeed, for each block \( B_{u,v} \), color \( u \), \( v \), and \( x_{u,v} \) with 3 different colors, arbitrarily. For each block \( B_u \), do the same for \( u \), \( x_u \), and \( y_u \). In the block between \( B_{u,v} \) and \( B_u \), give to \( x_u \) the same color it has in \( B_u \) and give to \( y_u \) a color different than the color given to \( u \) in \( B_{u,v} \). Now, between the definitions of \( y_u \) and \( x_{u,v} \), only two registers contain a live value: the register that contains \( u \) defined in \( B_{u,v} \) and the register that contains \( y_u \). These two values can be moved to the registers where there are supposed to be in \( B_u \), with one move, two moves, or three moves in case of a swap, using the available register in which \( x_u \) is going to be defined just after this shuffle.
So, is it really NP-complete to decide if \( k \) registers are enough when splitting can be done anywhere? The problem with the previous construction is that there is no way to not leave a program point with a low register pressure with simple statements while keeping NP-completeness. But, if we are considering the register allocation problem for an architecture with instructions that can define more than one value, it is easy to modify the proof. In a block where \( y_u \) and \( x_u \) are defined, use a parallel statement that uses \( v \) and \( x_{u,v} \) and defines \( y_u \) and \( x_u \) simultaneously, for example something like \( (x_u, y_u) = (b + x_{u,v}, b - x_{u,v}) \). Now, Maxlive = 3 everywhere in the program and, even if splitting is allowed anywhere, the program can be mapped to 3 registers if and only if \( G \) is 3-colorable. Therefore, it is NP-complete to decide if \( k \) registers are enough if two variables can be created simultaneously by a machine instruction, even if there is no critical edge and if we can split wherever we want. Notice the similarity with circular-arc graphs: as noticed in [10], the problem of coloring circular-arc graphs remains NP-complete even if at most 2 circular arcs can start at any point (but not if at most 1 can start, as we show below).
However, if such instructions exist, it is more likely that a register swap is also provided in the architecture, in which case we are back to the easy case where any permutation can be done and \( k \) registers are enough if and only if Maxlive = \( k \). It remains to consider one case: what if only one variable can be created at a given time as it is in traditional sequential assembly code representation? We claim this is polynomial to decide if \( k \) registers are enough, in the case of a strict program and if we are allowed to introduce blocks to remove critical edges. This can be done as follows.
Consider the program after edge splitting and compute Maxlive, the maximal number of values live at any program point. If Maxlive < \( k \), it is always possible to assign variables to \( k \) registers by splitting live ranges as we already discussed because adequate permutations can always be performed. If Maxlive > \( k \), this is not possible \(^2\), more spilling has to be done. The remaining case is thus when Maxlive = \( k \).
If Maxlive = \( k \), restrict to the control-flw graph defined by program points where exactly \( k \) variables are live. We claim that, in each connected component of this graph, if \( k \) registers are enough, there is a unique solution, up to a permutation of colors. Indeed, for each connected
\(^2\)This is true for a strict program. For a non-strict program, one needs to consider another definition of Maxlive. We do not address non-strict programs in this report.
component, start from a particular program point and a particular coloring of the \( k \) variables live at this point. Propagate this coloring in a greedy fashion, backwards or forwards along the control flow. In this process, there is no ambiguity because the number of live variables remains equal to \( k \): At any program point, since one variable (and only one) is created, exactly one must become dead, and the new variable must be assigned the same color as the dead one. Therefore, going backwards or forwards defines a unique solution (up to the initial permutation of colors). In other words, if there is a solution, we can define it, in each connected component, by propagation. If, during this traversal, we reach a program point already assigned and if the colors do not match, this proves that \( k \) registers are not enough.
Finally, if the propagation of colors on each connected component is possible, then \( k \) registers are enough for the whole program. Indeed, we can color the rest in a greedy (but not unique) fashion and, when we reach a point already assigned, we can resolve a possible register mismatch because at most \( k - 1 \) variables are live at this point.
To conclude, to decide if \( k \) registers are enough, one just need to propagate colors along the control flow. We first propagate along program points where \( \text{Maxlive} = k \). If we reach a program point already colored and the colors do not match, more spilling needs to be done. Otherwise, we start a second phase of propagation, along all remaining program points. If we reach a program point already colored and the colors do not match, we resolve the problem with a permutation of at most \( k - 1 \) registers.
5 Conclusion
In this report, we tried to make clearer where the complexity of register allocation comes from. Our goal was to recall what exactly Chaitin’s original proof proves and to extend this result. The main question addressed by Chaitin is of the following type: Can we decide if \( k \) registers are enough for a given program or if some spilling is necessary?
The original proof of Chaitin [6] proves that this problem is NP-complete if each variable can be assigned to only one register (i.e., no live range splitting). We showed that Chaitin’s construction also proves the NP-completeness of the problem if live range splitting is allowed but if we are not allowed to remove critical edges (i.e., no edge splitting).
Recently, Ferreira and Palsberg [19] proves that, if \( k \) is arbitrary and the program is a loop, then the problem remains NP-complete if live range splitting is allowed but only on a block on the back edge and if register swaps are not available. This is a particular form of register allocation through SSA. We showed that Chaitin’s proof can be extended to show a bit more. The problem remains NP-complete for a fixed \( k \geq 3 \), even if the program has no critical edge and if we can split live ranges along any control-flow edge (but not inside basic blocks). This again is if register swaps are not available.
These results do not address the general case where we are allowed to split wherever we want, including inside basic blocks. We show that the problem remains NP-complete but only if some instructions can define two variables simultaneously. For a strict program and/or if we consider that two variables interfere if and only if they are both live at some program point, we can answer the remaining cases. First \( k \) must be at least \( \text{Maxlive} \), the maximal number of variables live at any program point. If \( \text{Maxlive} < k \) or if register swaps are available (which is likely to be the case if some instructions can define two variables simultaneously) then \( k \) registers are enough. If register swaps are not available and if only one variable can be defined
at a given program point, then a simple polynomial-time greedy approach can be used to decide if \( k \) registers are enough.
This study shows that the NP-completeness of register allocation is not due to the coloring phase (as a misinterpretation of Chaitin’s proof may suggest); deciding if \( k \) registers are enough or if spilling is necessary is not as hard as one might think. The NP-completeness of register allocation is due to the presence of critical edges or not, and to the optimization of spilling costs (which variables should be spilled and where so as to reduce Maxlive with a minimal cost?) and coalescing costs (which live ranges should be fused so as to minimize register-to-register moves while keeping the graph \( k \)-colorable?).
References
|
{"Source-Url": "https://hal-lara.archives-ouvertes.fr/hal-02102286/file/RR2006-13.pdf", "len_cl100k_base": 8533, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 43981, "total-output-tokens": 10737, "length": "2e13", "weborganizer": {"__label__adult": 0.0003905296325683594, "__label__art_design": 0.00033545494079589844, "__label__crime_law": 0.00045990943908691406, "__label__education_jobs": 0.0006041526794433594, "__label__entertainment": 6.479024887084961e-05, "__label__fashion_beauty": 0.00019276142120361328, "__label__finance_business": 0.00023305416107177737, "__label__food_dining": 0.0004336833953857422, "__label__games": 0.0007710456848144531, "__label__hardware": 0.0019550323486328125, "__label__health": 0.0007328987121582031, "__label__history": 0.00031948089599609375, "__label__home_hobbies": 0.00011199712753295898, "__label__industrial": 0.0005617141723632812, "__label__literature": 0.0002827644348144531, "__label__politics": 0.0003809928894042969, "__label__religion": 0.0006036758422851562, "__label__science_tech": 0.05279541015625, "__label__social_life": 7.43865966796875e-05, "__label__software": 0.005413055419921875, "__label__software_dev": 0.93212890625, "__label__sports_fitness": 0.0003466606140136719, "__label__transportation": 0.0007195472717285156, "__label__travel": 0.0002157688140869141}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41677, 0.03364]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41677, 0.35933]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41677, 0.87292]], "google_gemma-3-12b-it_contains_pii": [[0, 1022, false], [1022, 1185, null], [1185, 4208, null], [4208, 6961, null], [6961, 10937, null], [10937, 15066, null], [15066, 17052, null], [17052, 21025, null], [21025, 22925, null], [22925, 26634, null], [26634, 28287, null], [28287, 32594, null], [32594, 36463, null], [36463, 39090, null], [39090, 41677, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1022, true], [1022, 1185, null], [1185, 4208, null], [4208, 6961, null], [6961, 10937, null], [10937, 15066, null], [15066, 17052, null], [17052, 21025, null], [21025, 22925, null], [22925, 26634, null], [26634, 28287, null], [28287, 32594, null], [32594, 36463, null], [36463, 39090, null], [39090, 41677, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41677, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41677, null]], "pdf_page_numbers": [[0, 1022, 1], [1022, 1185, 2], [1185, 4208, 3], [4208, 6961, 4], [6961, 10937, 5], [10937, 15066, 6], [15066, 17052, 7], [17052, 21025, 8], [21025, 22925, 9], [22925, 26634, 10], [26634, 28287, 11], [28287, 32594, 12], [32594, 36463, 13], [36463, 39090, 14], [39090, 41677, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41677, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
d1d6f57837b498cced5ce821553e576b7b8bfbc9
|
Types for Quantum Computing
Peter Selinger
Dalhousie University
Halifax, Canada
Why Quantum Programming Languages?
• For certain problems, quantum algorithms have an exponential speedup over best known classical algorithms.
• Most research in quantum computing has focused on algorithms and complexity theory.
• Quantum algorithms are traditionally described in terms of hardware: quantum circuits or quantum Turing machines.
• Want compositionality. Also, how do quantum features interact with other language features such as structured data, recursion, i/o, higher-order.
Part I: Quantum Computation
Linear Algebra Review
- Scalars \( \lambda \in \mathbb{C} \), column vectors \( u \in \mathbb{C}^n \), matrices \( A \in \mathbb{C}^{n \times m} \).
- Adjoint \( A^* = (a_{ji})_{ij} \), trace \( \text{tr} A = \sum_i a_{ii} \), norm \( \|A\|^2 = \sum_{ij} |a_{ij}|^2 \).
- Unitary matrix \( S \in \mathbb{C}^{n \times n} \) if \( S^* S = I \).
Change of basis: \( B = SAS^* \Rightarrow \text{tr} B = \text{tr} A, \|B\| = \|A\| \).
- Hermitian matrix \( A \in \mathbb{C}^{n \times n} \): if \( A = A^* \).
Hermitian positive: \( u^* A u \geq 0 \) for all \( u \in \mathbb{C}^n \).
Diagonalization: \( A = SDS^* \), \( S \) unitary, \( D \) real diagonal.
- Tensor product \( A \otimes B \), e.g. \( \begin{pmatrix} 0 & 1 \\ -1 & 0 \end{pmatrix} \otimes B = \begin{pmatrix} 0 & B \\ -B & 0 \end{pmatrix} \).
The QRAM abstract machine [Knill96]
- General-purpose classical computer controls a special quantum hardware device
- Quantum device provides a bank of individually addressable qubits.
- Left-to-right: instructions.
- Right-to-left: results.
Quantum computation: States
- state of one qubit: $\alpha|0\rangle + \beta|1\rangle$ (superposition of $|0\rangle$ and $|1\rangle$).
- state of two qubits: $\alpha|00\rangle + \beta|01\rangle + \gamma|10\rangle + \delta|11\rangle$.
- independent: $(a|0\rangle + b|1\rangle) \otimes (c|0\rangle + d|1\rangle) = ac|00\rangle + ad|01\rangle + bc|10\rangle + bd|11\rangle$.
- otherwise entangled.
Lexicographic convention
Identify the basis states $|00\rangle$, $|01\rangle$, $|10\rangle$, $|11\rangle$ with the standard basis vectors
\[
\begin{pmatrix}
1 \\
0 \\
0 \\
0
\end{pmatrix},
\begin{pmatrix}
0 \\
1 \\
0 \\
0
\end{pmatrix},
\begin{pmatrix}
0 \\
0 \\
1 \\
0
\end{pmatrix},
\begin{pmatrix}
0 \\
0 \\
0 \\
1
\end{pmatrix},
\]
in the lexicographic order.
Note: we use column vectors for states.
\[
\begin{pmatrix}
\alpha \\
\beta \\
\gamma \\
\delta
\end{pmatrix} = \alpha |00\rangle + \beta |01\rangle + \gamma |10\rangle + \delta |11\rangle.
\]
Quantum computation: Operations
- unitary transformation
- measurement
Some standard unitary gates
Unary:
\[ N = \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix}, \quad N_c = \begin{pmatrix} I & 0 \\ 0 & N \end{pmatrix}, \]
\[ H = \frac{1}{\sqrt{2}} \begin{pmatrix} 1 & 1 \\ 1 & -1 \end{pmatrix}, \quad H_c = \begin{pmatrix} I & 0 \\ 0 & H \end{pmatrix}, \]
\[ V = \begin{pmatrix} 1 & 0 \\ 0 & i \end{pmatrix}, \quad V_c = \begin{pmatrix} I & 0 \\ 0 & V \end{pmatrix}, \]
\[ W = \begin{pmatrix} 1 & 0 \\ 0 & \sqrt{i} \end{pmatrix}, \quad W_c = \begin{pmatrix} I & 0 \\ 0 & W \end{pmatrix}, \]
Binary:
\[ X = \begin{pmatrix} 1 & 0 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & 1 \end{pmatrix}. \]
Measurement
\[ \alpha |0\rangle + \beta |1\rangle \]
\[ |\alpha|^2 \quad 0 \quad 1 \quad |\beta|^2 \]
\[ \alpha |0\rangle \quad \beta |1\rangle \]
Two Measurements
\[ \alpha |00\rangle + \beta |01\rangle + \gamma |10\rangle + \delta |11\rangle \]
Note: Normalization convention.
Pure vs. mixed states
A mixed state is a (classical) probability distribution on quantum states.
Ad hoc notation:
\[
\frac{1}{2} \left\{ \begin{pmatrix} \alpha \\ \beta \end{pmatrix} \right\} + \frac{1}{2} \left\{ \begin{pmatrix} \alpha' \\ \beta' \end{pmatrix} \right\}
\]
Note: A mixed state is a description of our knowledge of a state. An actual closed quantum system is always in a (possibly unknown) pure state.
Density matrices (von Neumann)
Represent the pure state \( v = \begin{pmatrix} \alpha \\ \beta \end{pmatrix} \in \mathbb{C}^2 \) by the matrix
\[
vv^* = \begin{pmatrix} \alpha \bar{\alpha} & \alpha \bar{\beta} \\ \beta \bar{\alpha} & \beta \bar{\beta} \end{pmatrix} \in \mathbb{C}^{2\times2}.
\]
Represent the mixed state \( \lambda_1 \{v_1\} + \ldots + \lambda_n \{v_n\} \) by
\[
\lambda_1 v_1 v_1^* + \ldots + \lambda_n v_n v_n^*.
\]
This representation is not one-to-one, e.g.
\[
\frac{1}{2} \left\{ \begin{pmatrix} 1 \\ 0 \end{pmatrix} \right\} + \frac{1}{2} \left\{ \begin{pmatrix} 0 \\ 1 \end{pmatrix} \right\} = \frac{1}{2} \begin{pmatrix} 1 & 0 \\ 0 & 0 \end{pmatrix} + \frac{1}{2} \begin{pmatrix} 0 & 0 \\ 0 & 1 \end{pmatrix} = \begin{pmatrix} .5 & 0 \\ 0 & .5 \end{pmatrix}
\]
\[
\frac{1}{2} \left\{ \frac{1}{\sqrt{2}} \begin{pmatrix} 1 \\ 1 \end{pmatrix} \right\} + \frac{1}{2} \left\{ \frac{1}{\sqrt{2}} \begin{pmatrix} 1 \\ -1 \end{pmatrix} \right\} = \frac{1}{2} \begin{pmatrix} .5 & .5 \\ .5 & -.5 \end{pmatrix} + \frac{1}{2} \begin{pmatrix} .5 & -.5 \\ -.5 & .5 \end{pmatrix} = \begin{pmatrix} .5 & 0 \\ 0 & .5 \end{pmatrix}
\]
But these two mixed states are indistinguishable.
Quantum operations on density matrices
Unitary:
\[ \rho \mapsto U \rho U^* \]
Measurement:
\[
\begin{pmatrix}
\alpha \\
\beta \\
\end{pmatrix}
\begin{pmatrix}
0 & 1 \\
|\alpha|^2 & |\beta|^2 \\
\end{pmatrix}
\begin{pmatrix}
\alpha \\
0 \\
\end{pmatrix}
\begin{pmatrix}
\bar{\alpha} \\
\beta \\
\end{pmatrix}
\begin{pmatrix}
0 & 1 \\
\alpha \bar{\alpha} & \beta \bar{\beta} \\
\end{pmatrix}
\begin{pmatrix}
0 & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & b \\
c & d \\
\end{pmatrix}
\begin{pmatrix}
a \bar{\alpha} & \beta \bar{\beta} \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & b \\
c & d \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\]
\[ \begin{pmatrix}
\alpha \\
\beta \\
\end{pmatrix}
\begin{pmatrix}
\alpha \bar{\alpha} & \alpha \bar{\beta} \\
\beta \bar{\alpha} & \beta \bar{\beta} \\
\end{pmatrix}
\begin{pmatrix}
\alpha \bar{\alpha} & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
\alpha \bar{\alpha} & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
\alpha \bar{\alpha} & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\begin{pmatrix}
a & 0 \\
0 & 0 \\
\end{pmatrix}
\]
14
A complete partial order of density matrices
Let $D_n = \{ A \in \mathbb{C}^{n \times n} \mid A$ is positive hermitian and $\text{tr} A \leq 1 \}$.
**Definition.** We write $A \sqsubseteq B$ if $B - A$ is positive.
**Theorem.** The density matrices form a *complete partial order* under $\sqsubseteq$.
- $A \sqsubseteq A$
- $A \sqsubseteq B$ and $B \sqsubseteq A \Rightarrow A = B$
- $A \sqsubseteq B$ and $B \sqsubseteq C \Rightarrow A \sqsubseteq C$
- every increasing sequence $A_1 \sqsubseteq A_2 \sqsubseteq \ldots$ has a least upper bound
Part II: The Flow Chart Language
First: the classical case. A simple classical flow chart
```
input b, c : bit
b, c : bit
branch b
0 1
b, c : bit
b := c
b, c : bit
c := 0
b, c : bit
b, c : bit
output b, c : bit
```
Classical flow chart, with boolean variables expanded
input $b, c : \textbf{bit}$
00 01 10 11
(* branch $b$ *)
(* $b := c$ *)
(* $c := 0$ *)
(* merge *)
output $b, c : \textbf{bit}$
00 01 10 11
18
Classical flow chart, with boolean variables expanded
input \( b, c : \text{bit} \)
\[
\begin{array}{cccc}
00 & 01 & 10 & 11 \\
\text{A} & \text{B} & \text{C} & \text{D} \\
\end{array}
\]
(output \( b, c : \text{bit} \))
\[
\begin{array}{cccc}
00 & 01 & 10 & 11 \\
\text{A + C} & \text{B} & \text{D} & 0 \\
\end{array}
\]
(* branch \( b \) *)
(* \( b := c \) *)
(* \( c := 0 \) *)
(* merge *)
A simple classical flow chart
```
input b, c : bit
branch b
0
b, c : bit
b := c
b, c : bit
c := 0
b, c : bit
output b, c : bit
```
A simple classical flow chart
input $b, c : \text{bit}$
$b, c : \text{bit} = (A, B, C, D)$
branch $b$
1
$b, c : \text{bit} = (0, 0, C, D)$
$b := c$
$b, c : \text{bit} = (A, B, 0, 0)$
$c := 0$
$b, c : \text{bit} = (C, 0, 0, D)$
$b, c : \text{bit} = (C, 0, D, 0)$
output $b, c : \text{bit}$
$b, c : \text{bit} = (A + C, B, D, 0)$
Summary of classical flow chart components
Allocate bit:
\[ \Gamma = A \]
\[ \text{new bit } b := 0 \]
\[ b : \text{bit}, \Gamma = (A, 0) \]
Discard bit:
\[ b : \text{bit}, \Gamma = (A, B) \]
\[ \text{discard } b \]
\[ \Gamma = A + B \]
Assignment:
\[ b : \text{bit}, \Gamma = (A, B) \]
\[ b := 0 \]
\[ b : \text{bit}, \Gamma = (A + B, 0) \]
\[ b := 1 \]
\[ b : \text{bit}, \Gamma = (0, A + B) \]
Branching:
\[ b : \text{bit}, \Gamma = (A, B) \]
\[ \text{branch } b \]
\[ b : \text{bit}, \Gamma = (A, 0) \]
\[ b : \text{bit}, \Gamma = (0, B) \]
Merge:
\[ \Gamma = A \]
\[ \Gamma = B \]
\[ \Gamma = A + B \]
\[ \Gamma = 0 \]
Initial:
\[ b_1, \ldots, b_n : \text{bit} = A_0, \ldots, A_{2^n-1} \]
\[ \text{permute } \phi \]
\[ b_{\phi(1)}, \ldots, b_{\phi(n)} : \text{bit} = A_{2^\phi(0)}, \ldots, A_{2^\phi(2^n-1)} \]
The quantum case: A simple quantum flow chart
```
input p, q : qbit
measure p
p : qbit 0
q *= N
p : qbit
p : qbit 1
p *= N
p : qbit
output p, q : qbit
```
A simple quantum flow chart
\[ \text{input } p, q : \text{qbit} \]
\[ p, q : \text{qbit} = \begin{pmatrix} A & B \\ C & D \end{pmatrix} \]
measure p
\[ p, q : \text{qbit} = \begin{pmatrix} A & 0 \\ 0 & 0 \end{pmatrix} \]
\[ p, q : \text{qbit} = \begin{pmatrix} 0 & 0 \\ 0 & D \end{pmatrix} \]
\[ q *\equiv N \]
\[ p *\equiv N \]
\[ p, q : \text{qbit} = \begin{pmatrix} \text{NAN}\star & 0 \\ 0 & 0 \end{pmatrix} \]
\[ p, q : \text{qbit} = \begin{pmatrix} D & 0 \\ 0 & 0 \end{pmatrix} \]
\[ p, q : \text{qbit} = \begin{pmatrix} \text{NAN}\star + D & 0 \\ 0 & 0 \end{pmatrix} \]
output p, q : qbit
Summary of quantum flow chart components
Allocate qbit:
\[
\begin{align*}
\Gamma &= A \\
\text{new qbit } q := 0 \\
q : \text{qbit}, \Gamma &= \begin{pmatrix} A & 0 \\ 0 & 0 \end{pmatrix}
\end{align*}
\]
Discard qbit:
\[
\begin{align*}
q : \text{qbit}, \Gamma &= \begin{pmatrix} A & B \\ C & D \end{pmatrix} \\
discard q \\
\Gamma &= A + D
\end{align*}
\]
Unitary transformation:
\[
\begin{align*}
\tilde{q} : \text{qbit}, \Gamma &= A \\
\tilde{q} &= S \\
\tilde{q} : \text{qbit}, \Gamma &= (S \otimes I)A(S \otimes I)^*
\end{align*}
\]
Measurement:
\[
\begin{align*}
q : \text{qbit}, \Gamma &= \begin{pmatrix} A & 0 \\ 0 & 0 \end{pmatrix} \\
\text{measure } q \\
q : \text{qbit}, \Gamma &= \begin{pmatrix} 0 & 0 \\ 0 & D \end{pmatrix}
\end{align*}
\]
Merge:
\[
\begin{align*}
\Gamma &= A \\
\Gamma &= B \\
\Gamma &= A + B
\end{align*}
\]
Initial:
\[
\begin{align*}
\Gamma &= A \\
\Gamma &= B \\
\Gamma &= A + B \\
\Gamma &= 0
\end{align*}
\]
Permutation:
\[
\begin{align*}
q_1, \ldots, q_n : \text{qbit} &= (a_{ij})_{ij} \\
\text{permute } \phi \\
q_{\phi(1)}, \ldots, q_{\phi(n)} : \text{qbit} &= (a_{2\phi(i),2\phi(j)})_{ij}
\end{align*}
\]
Part III: Quantum Lambda Calculus
With Benoît Valiron.
A quantum lambda calculus [Selinger, Valiron04]
- Quantum data is subject to *linearity constraints*. Need to avoid terms that lead to runtime errors such as
\[
\text{let } q = \text{new}_\text{qbit}() \text{ in } (\lambda x. H(x, x)) q.
\]
- Bits are always duplicable, qubits are never duplicable. What about functions?
- Consider
\[
\begin{align*}
q: \text{qbit} & \vdash \lambda p.p : \text{qbit} \rightarrow \text{qbit} \\
q: \text{qbit} & \vdash \lambda p.q : \text{qbit} \rightarrow \text{qbit}
\end{align*}
\]
Both closures have type \text{qbit} \rightarrow \text{qbit}, but only the first one is duplicable.
- Solution: type system based on linear logic.
Linear type system [Selinger, Valiron04]
Types: \( A, B ::= \text{qbit} \mid !A \mid A \rightarrow B \mid 1 \mid A \otimes B \mid A \oplus B. \)
Convention \( \text{bit} := 1 \oplus 1. \)
Subtyping: \( !A <: A. \)
Main typing rules:
\[
\frac{\Delta, x:A \triangleright M : B}{\Delta \triangleright \lambda x.M : A \rightarrow B}
\]
\[
\frac{!\Delta, x:A \triangleright M : B}{!\Delta \triangleright \lambda x.M : !(A \rightarrow B)}
\]
Complete typing rules:
\[
\frac{A \triangleleft: B}{\Delta, x:A \triangleright x : B} \quad (ax_1)
\]
\[
\frac{\Delta \triangleright c : B}{\Delta \triangleright c : B} \quad (ax_2)
\]
\[
\frac{\Delta \triangleright M : !^m A \quad \Delta \triangleright \text{inj}_1(M) : !^m (A \oplus B)}{\Delta \triangleright \text{inj}_1(M) : !^m (A \oplus B)} \quad (\oplus.I_1)
\]
\[
\frac{\Delta \triangleright N : !^m B \quad \Delta \triangleright \text{inj}_r(N) : !^m (A \oplus B)}{\Delta \triangleright \text{inj}_r(N) : !^m (A \oplus B)} \quad (\oplus.I_2)
\]
\[
\frac{\Delta \triangleright \text{match } P \text{ with } (x \mapsto M \mid y \mapsto N) : C}{\Gamma_1, \Gamma_2, !\Delta \triangleright \text{match } P \text{ with } (x \mapsto M \mid y \mapsto N) : C \quad (\oplus.E)}
\]
\[
\frac{\Gamma_1, !\Delta \triangleright M : A \rightarrow B \quad \Gamma_2, !\Delta \triangleright N : A}{\Gamma_1, \Gamma_2, !\Delta \triangleright MN : B \quad (\text{app})}
\]
\[
\begin{align*}
\text{If } & \text{ FV}(M) \cap |\Gamma| = \emptyset: \\
\frac{\Gamma, !\Delta, x:A \triangleright M : B}{\Gamma, !\Delta, x:A \triangleright M : B} & \quad (\lambda_1) \\
\frac{\Delta \triangleright \lambda x.\bar{M} : A \rightarrow B}{\Gamma, !\Delta \triangleright \lambda x.\bar{M} : !^{n+1}(A \rightarrow B)} & \quad (\lambda_2) \\
\end{align*}
\]
\[
\frac{\Delta \triangleright M_1 : !^n A_1 \quad \Delta \triangleright M_2 : !^n A_2}{\Delta \triangleright \langle M_1, M_2 \rangle : !^n (A_1 \otimes A_2)} \quad (\otimes.I)
\]
\[
\frac{\Delta \triangleright \langle M_1, M_2 \rangle : !^n (A_1 \otimes A_2)}{\Delta \triangleright \star : !^m 1} \quad (1)
\]
\[
\frac{\Delta \triangleright M : !^n (A_1 \otimes A_2) \quad \Delta \triangleright x_1 : !^n A_1, x_2 : !^n A_2 \triangleright N : A}{\Delta \triangleright \text{let } \langle x_1, x_2 \rangle = M \text{ in } N : A \quad (\otimes.E)}
\]
\[
\frac{\Delta \triangleright f : !(A \rightarrow B), x : A \triangleright M : B \quad \Delta, \Gamma, f : !(A \rightarrow B) \triangleright N : C}{\Delta, \Gamma \triangleright \text{let rec } f x = M \text{ in } N : C \quad (\text{rec})}
\]
Properties of the type system
All the rules of intuitionistic linear logic are valid, except for the general promotion rule:
$$
\frac{!\Delta \vdash M : A}{!\Delta \vdash M : !A}.
$$
We do have the promotion rule for \textit{values}:
$$
\frac{!\Delta \vdash V : A}{!\Delta \vdash V : !A}.
$$
\textbf{Type inference:} first do “intuitionistic” type inference, then find a “linear decoration”.
Completeness
Quantum lambda calculus (with list types and recursion) is complete for quantum computation. Every algorithm can be expressed \textit{in principle}.
Part IV: Quipper
Quipper developers: Richard Eisenberg, Alexander S. Green, Peter LeFanu Lumsdaine, Neil J. Ross, Peter Selinger, Benoît Valiron.
Design goals
Quantum lambda calculus is too low-level. Algorithms in the quantum literature are described in terms of meta-operations:
- Start with a classical function;
- turn it into a circuit;
- make it reversible;
- apply a transformation (e.g. amplitude amplification);
- etc.
Quipper: extend quantum lambda calculus with the ability to build and manipulate quantum circuits as first-class objects.
Quipper’s initial implementation
Implemented as a deeply embedded EDSL in Haskell.
Reasons:
- Haskell provides very good support for higher-order, polymorphic, and overloaded functions.
- Both Haskell and Quipper are strongly typed, functional programming languages, and as such, are a relatively good fit for each other.
Trade-offs:
- Haskell lacks two features that would be useful to Quipper: linear types and dependent types. We must live with checking certain properties at run-time that could be checked by the type-checker in a dedicated language.
Quipper contains a powerful circuit description language
- In our experience, 99 percent of the quantum programmer’s task is “constructing the circuit”, and 1 percent is “running the circuit”.
- Quipper separates the description of quantum operations from what to do with them. E.g.: a given quantum function could be:
- executed right away;
- stored for later execution; or
- stored to be transformed or analyzed.
- Many tasks in algorithm construction require manipulations at the circuit level, rather than the gate level. For example:
- reversing;
- iteration (e.g. Trotterization; amplitude amplification);
- construction of classical oracles and ancilla management;
- whole-circuit optimization
The two run-times
As a circuit description language, Quipper shares many features with *hardware description languages*. In particular, it has *three distinct phases of execution*:
1. **Compile time.**
Subject to: *compile time parameters*
Error detection: most programming errors detected.
2. **Circuit generation time ("synthesizer").**
Subject to: *circuit parameters*
Error detection: ideally none (or some run-time errors).
3. **Circuit execution time.**
Subject to: *circuit inputs*
Error detection: decoherence errors, physical errors.
The two run-times, continued
The distinction between *parameters* and *inputs* requires special support in the type system. **Circuit inputs are not known at circuit generation time!**
In Quipper, this is done by having 3 basic types instead of the usual 2:
- **Bool**: a boolean *parameter*, known at circuit generation time;
- **Bit**: a boolean *input*, i.e., a boolean wire in a circuit;
- **Qubit**: a qubit *input*, i.e., a qubit wire in a circuit.
Moreover, circuit generation and execution may be interleaved ("*dynamic lifting*").
The Quipper idiom
The basic idiom for writing a circuit in Quipper is:
```haskell
example :: (Qubit, Qubit, Qubit) -> Circ (Qubit, Qubit, Qubit)
example (a, b, c) = do
<<gate1>>
<<gate2>>
<<gate3>>
return (a, b, c)
```
Note: in Quipper, as in Quantum Lambda Calculus, quantum operations are viewed as functions. However, the `Circ` monad is used to assemble a data structure.
A first example
The code on the left is a small, but complete, Quipper program. When it is compiled and run, it outputs the circuit shown on the right.
```haskell
import Quipper
example1 (q, a, b, c) = do
hadamard a
qnot_at c 'controlled' [a, b]
hadamard q 'controlled' [c]
qnot_at c 'controlled' [a, b]
hadamard a
return (q, a, b, c)
```
Scoped ancillas
Let us modify the previous example so that the qubit $c$ is a local ancilla. This is done with the `with_ancilla` operator. This operator is followed by a nested “do” block. Note that Quipper uses indentation to figure out the end of a “do” block.
```quipper
import Quipper
def example2 (q, a, b) = do
hadamard a
with_ancilla $ \c -> do
qnot_at c 'controlled' [a, b]
hadamard q 'controlled' [c]
qnot_at c 'controlled' [a, b]
hadamard a
return (q, a, b)
```
---

Blockwise controls
Any circuit previously defined can be used as a subroutine. Also, the `with_controls` operator can be used to specify that an entire block of gates should be controlled:
```haskell
example3 (q, a, b, c, d, e) = do
example1 (q, a, b, c)
with_controls (d .==. 0 .&&. e .==. 1) $ do
example1 (q, a, b, c)
example1 (q, a, b, c)
example1 (q, a, b, c)
example1 (q, a, b, c)
```
![Diagram showing quantum circuit with blockwise controls]
Recursion
Let us consider an implementation of a classical “and” gate. It inputs two qubits, and returns a new ancilla qubit initialized to the “and” of the two input qubits:
```haskell
and_gate :: (Qubit, Qubit) -> Circ (Qubit)
and_gate (a, b) = do
c <- qinit False
qnot_at c 'controlled' [a, b]
return c
```

Recursion, continued
We now program a function that computes the “and” of a list of qubits. Note that the length of the list is a parameter, but the qubits themselves are inputs.
\[
\text{and\_list} :: [\text{Qubit}] \rightarrow \text{Circ Qubit}
\]
\[
\text{and\_list} \; [] \; = \; \text{do}
\]
\[
\text{c} \; \leftarrow \; \text{qinit} \; \text{True}
\]
\[
\text{return} \; \text{c}
\]
\[
\text{and\_list} \; [q] \; = \; \text{do}
\]
\[
\text{return} \; q
\]
\[
\text{and\_list} \; (q:t) \; = \; \text{do}
\]
\[
d \; \leftarrow \; \text{and\_list} \; t
\]
\[
e \; \leftarrow \; \text{and\_gate} \; (d, \; q)
\]
\[
\text{return} \; e
\]
Generic classical-to-reversible operator with ancilla uncomputation
Quipper provides a general operator \texttt{classical\_to\_reversible}, which turns any classical circuit into a reversible circuit by uncomputing all the “garbage” ancillas. When applying this to the function from the previous slide, we get:
\begin{verbatim}
and_rev :: ([Qubit], Qubit) -> Circ ([Qubit], Qubit)
and_rev = classical_to_reversible and_list
\end{verbatim}
Automatic oracle generation from classical code
Quipper can generate circuits from ordinary classical functional programs, via *Template Haskell* and a preprocessor.
```haskell
build_circuit
v_function :: BoolParam -> BoolParam -> Boollist -> Boollist -> Node -> (Bool,Node)
v_function c_hi c_lo f g a =
let aa = snd a in
let cbc_hi = newBool c_hi 'bool_xor' level_parity aa in
let cbc_lo = newBool c_lo in
if (not (is_root aa) && cbc_hi && not (cbc_lo 'bool_xor' (last aa)))
then (False, parent a)
else
let res = child f g a cbc_lo in
(is_zero aa || cbc_hi, res)
```
Part V: Issues for type system design
Inadequacy of host language
- Haskell has no *linear types*. Therefore, errors like
\[(a,b) \leftarrow \text{controlled_not} (c,c)\]
can only be caught at runtime.
- Haskell has no *dependent types*. Variable size circuits can be represented as
\[
\text{circuit} :: [\text{Qubit}] \rightarrow \text{Circ} [\text{Qubit}]
\]
However, when *reversing* such a circuit, the type system cannot know the number of inputs of the reversed circuit. That is because the length of the list is a *parameter* but here treated as an *input*. Dependent types would solve this problem easily.
Some issues for type system design
- Reversibility tracking (not all circuits are reversible).
- Support for imperative syntax. Writing gates in purely functional style is okay:
\[(a,b) \leftarrow \text{gate} (a,b).\]
However, for higher-order combinators, this turns very ugly:
\[(a,b) \leftarrow (\text{while } \langle\langle \text{condition} \rangle \rangle \text{ do } \langle\langle \text{body} \rangle \rangle \rightarrow \\
\langle\langle \text{return} (a,b) \rangle \rangle)(a,b)\]
Some issues for type system design, continued
• Weak linearity. Consider the classical Toffoli gate
```
a -----
|
b ----
|
c
```
Linearity requires that \( a \neq c \) and \( b \neq c \).
On the other hand, it can be perfectly reasonable (and desirable) to allow \( a = b \).
Moreover, \( a \) and \( b \) are immutable.
In classical circuit synthesis, to ensure well-formed circuits, one should keep track of all of these properties.
Some issues for type system design, continued
- Automatic garbage management. A classical boolean function such as
\[
\text{let } c = \text{and } a \ b
\]
will be synthesized to a circuit such as this:
\[
\begin{array}{c}
a \\
\downarrow \\
b \\
\downarrow \\
0 \oplus \quad c
\end{array}
\]
Note that \( a \) and \( b \) are outputs of the circuit, but not of the function. They are “garbage”, and must potentially be uncomputed later. We need a type system to automatically track such garbage.
The end.
|
{"Source-Url": "http://cs.ioc.ee/types15/slides/selinger-slides.pdf", "len_cl100k_base": 8369, "olmocr-version": "0.1.50", "pdf-total-pages": 52, "total-fallback-pages": 0, "total-input-tokens": 90864, "total-output-tokens": 11006, "length": "2e13", "weborganizer": {"__label__adult": 0.0004246234893798828, "__label__art_design": 0.0004315376281738281, "__label__crime_law": 0.00036072731018066406, "__label__education_jobs": 0.0006747245788574219, "__label__entertainment": 8.910894393920898e-05, "__label__fashion_beauty": 0.00017917156219482422, "__label__finance_business": 0.00023806095123291016, "__label__food_dining": 0.0005364418029785156, "__label__games": 0.0005259513854980469, "__label__hardware": 0.0024242401123046875, "__label__health": 0.0008101463317871094, "__label__history": 0.00029397010803222656, "__label__home_hobbies": 0.00018787384033203125, "__label__industrial": 0.0008301734924316406, "__label__literature": 0.00025081634521484375, "__label__politics": 0.0003638267517089844, "__label__religion": 0.0007467269897460938, "__label__science_tech": 0.07177734375, "__label__social_life": 0.00011771917343139648, "__label__software": 0.004619598388671875, "__label__software_dev": 0.91259765625, "__label__sports_fitness": 0.0004472732543945313, "__label__transportation": 0.0006189346313476562, "__label__travel": 0.00025010108947753906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 23968, 0.03232]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 23968, 0.48524]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 23968, 0.52858]], "google_gemma-3-12b-it_contains_pii": [[0, 82, false], [82, 580, null], [580, 608, null], [608, 1424, null], [1424, 1667, null], [1667, 2064, null], [2064, 2630, null], [2630, 2703, null], [2703, 3342, null], [3342, 3492, null], [3492, 3626, null], [3626, 4048, null], [4048, 5250, null], [5250, 6578, null], [6578, 7127, null], [7127, 7160, null], [7160, 7344, null], [7344, 7550, null], [7550, 7951, null], [7951, 8090, null], [8090, 8430, null], [8430, 9252, null], [9252, 9412, null], [9412, 10019, null], [10019, 11171, null], [11171, 11227, null], [11227, 11918, null], [11918, 12135, null], [12135, 12359, null], [12359, 14488, null], [14488, 14886, null], [14886, 15049, null], [15049, 15196, null], [15196, 15603, null], [15603, 16164, null], [16164, 16882, null], [16882, 17459, null], [17459, 18003, null], [18003, 18390, null], [18390, 18744, null], [18744, 19288, null], [19288, 19761, null], [19761, 20146, null], [20146, 20796, null], [20796, 21237, null], [21237, 21835, null], [21835, 21873, null], [21873, 22473, null], [22473, 22969, null], [22969, 23431, null], [23431, 23960, null], [23960, 23968, null]], "google_gemma-3-12b-it_is_public_document": [[0, 82, true], [82, 580, null], [580, 608, null], [608, 1424, null], [1424, 1667, null], [1667, 2064, null], [2064, 2630, null], [2630, 2703, null], [2703, 3342, null], [3342, 3492, null], [3492, 3626, null], [3626, 4048, null], [4048, 5250, null], [5250, 6578, null], [6578, 7127, null], [7127, 7160, null], [7160, 7344, null], [7344, 7550, null], [7550, 7951, null], [7951, 8090, null], [8090, 8430, null], [8430, 9252, null], [9252, 9412, null], [9412, 10019, null], [10019, 11171, null], [11171, 11227, null], [11227, 11918, null], [11918, 12135, null], [12135, 12359, null], [12359, 14488, null], [14488, 14886, null], [14886, 15049, null], [15049, 15196, null], [15196, 15603, null], [15603, 16164, null], [16164, 16882, null], [16882, 17459, null], [17459, 18003, null], [18003, 18390, null], [18390, 18744, null], [18744, 19288, null], [19288, 19761, null], [19761, 20146, null], [20146, 20796, null], [20796, 21237, null], [21237, 21835, null], [21835, 21873, null], [21873, 22473, null], [22473, 22969, null], [22969, 23431, null], [23431, 23960, null], [23960, 23968, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 23968, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 23968, null]], "pdf_page_numbers": [[0, 82, 1], [82, 580, 2], [580, 608, 3], [608, 1424, 4], [1424, 1667, 5], [1667, 2064, 6], [2064, 2630, 7], [2630, 2703, 8], [2703, 3342, 9], [3342, 3492, 10], [3492, 3626, 11], [3626, 4048, 12], [4048, 5250, 13], [5250, 6578, 14], [6578, 7127, 15], [7127, 7160, 16], [7160, 7344, 17], [7344, 7550, 18], [7550, 7951, 19], [7951, 8090, 20], [8090, 8430, 21], [8430, 9252, 22], [9252, 9412, 23], [9412, 10019, 24], [10019, 11171, 25], [11171, 11227, 26], [11227, 11918, 27], [11918, 12135, 28], [12135, 12359, 29], [12359, 14488, 30], [14488, 14886, 31], [14886, 15049, 32], [15049, 15196, 33], [15196, 15603, 34], [15603, 16164, 35], [16164, 16882, 36], [16882, 17459, 37], [17459, 18003, 38], [18003, 18390, 39], [18390, 18744, 40], [18744, 19288, 41], [19288, 19761, 42], [19761, 20146, 43], [20146, 20796, 44], [20796, 21237, 45], [21237, 21835, 46], [21835, 21873, 47], [21873, 22473, 48], [22473, 22969, 49], [22969, 23431, 50], [23431, 23960, 51], [23960, 23968, 52]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 23968, 0.00297]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
c7fe5e6ec4146dd46799606d401d19386f8c3e93
|
Object Linking in Repositories
David Eichmann, ed.
West Virginia University Research Corporation
6/1/92
Cooperative Agreement NCC 9-16
Research Activity No. SE.43
NASA Johnson Space Center
Information Systems Directorate
Information Technology Division
Research Institute for Computing and Information Systems
University of Houston-Clear Lake
TECHNICAL REPORT
The University of Houston-Clear Lake established the Research Institute for Computing and Information Systems (RICIS) in 1986 to encourage the NASA Johnson Space Center (JSC) and local industry to actively support research in the computing and information sciences. As part of this endeavor, UHCL proposed a partnership with JSC to jointly define and manage an integrated program of research in advanced data processing technology needed for JSC's main missions, including administrative, engineering and science responsibilities. JSC agreed and entered into a continuing cooperative agreement with UHCL beginning in May 1986, to jointly plan and execute such research through RICIS. Additionally, under Cooperative Agreement NCC 9-16, computing and educational facilities are shared by the two institutions to conduct the research.
The UHCL/RICIS mission is to conduct, coordinate, and disseminate research and professional level education in computing and information systems to serve the needs of the government, industry, community and academia. RICIS combines resources of UHCL and its gateway affiliates to research and develop materials, prototypes and publications on topics of mutual interest to its sponsors and researchers. Within UHCL, the mission is being implemented through interdisciplinary involvement of faculty and students from each of the four schools: Business and Public Administration, Education, Human Sciences and Humanities, and Natural and Applied Sciences. RICIS also collaborates with industry in a companion program. This program is focused on serving the research and advanced development needs of industry.
Moreover, UHCL established relationships with other universities and research organizations, having common research interests, to provide additional sources of expertise to conduct needed research. For example, UHCL has entered into a special partnership with Texas A&M University to help oversee RICIS research and education programs, while other research organizations are involved via the "gateway" concept.
A major role of RICIS then is to find the best match of sponsors, researchers and research objectives to advance knowledge in the computing and information sciences. RICIS, working jointly with its sponsors, advises on research needs, recommends principals for conducting the research, provides technical and administrative support to coordinate the research and integrates technical results into the goals of UHCL, NASA/JSC and industry.
Object Linking in Repositories
RICIS Preface
This research was conducted under auspices of the Research Institute for Computing and Information Systems by David Eichmann, Jon Beck, John Atkins, and Bill Bailey of West Virginia University. Dr. E. T. Dickerson served as RICIS research coordinator.
Funding was provided by the Information Technology Division, Information Systems Directorate, NASA/JSC through Cooperative Agreement NCC 9-16 between NASA Johnson Space Center and the University of Houston-Clear Lake. The NASA technical monitor for this activity was Ernest M. Fridge, III of the Information Technology Division, Information Systems Directorate, NASA/JSC.
The views and conclusions contained in this report are those of the authors and should not be interpreted as representative of the official policies, either express or implied, of UHCL, RICIS, NASA or the United States Government.
Object Linking in Repositories
David Eichmann (ed.)
June 1, 1992
Introduction
This final report consists of three sections: the original interim report, an addendum describing the prototype, and a paper describing a new program slicing technique for increasing the substructure and flexibility of repository artifacts without requiring the separation of complex deposits.
1. Introduction
This interim report explores some of the architectural ramifications of extending the Eichmann/Atkins lattice-based classification scheme [1] to encompass the assets of the full life-cycle of software development. In particular, we wish to consider a model which provides explicit links between objects in addition to the edges connecting classification vertices in the standard lattice.
The model we consider here uses object-oriented terminology [3, 4]. Thus the lattice is viewed as a data structure which contains class objects which exhibit inheritance.
This report contains a description of the types of objects in the repository, followed by a discussion of how they interrelate. We discuss features of the object-oriented model which support these objects and their links, and consider behaviors which an implementation of the model should exhibit. Finally, we indicate some thoughts on implementing a prototype of this repository architecture.
2. A Bestiary of Objects
The repository is designed to contain the full set of assets created during the software life-cycle. Therefore, there are many types of objects we wish the repository to contain. Listed below are some obvious candidates for inclusion in the repository. This is an open list, indicative but not exhaustive. Extensibility of the system, a strength of faceted classification, is a necessity.
* This work is supported in part by NASA subcontract 089, cooperative agreement NCC-9-16, project no. RICIS SE.43.
Our discussion uses a simplified waterfall life-cycle model solely for the purposes of illustration. Our choice of models for this report was made on the basis of reaching the most general audience, rather than upon the suitability of any particular modeling technique. The arguments presented below apply equally well to any such technique.
2.1 Requirements
A repository containing the assets of a full life-cycle of some software development project will contain one or more requirements documents or requests for proposal which delineate the need which the software met. These documents will be written in human text (possibly with diagrams and figures) but will refer to functionality provided by code.
2.2 Specifications
Based on the requirements, there will be specifications documents, also written in human text. These documents describe the architecture of a software system which will provide the functionality demanded in the requirements. Code is written based upon the architecture which the specifications provide.
2.3 Code
Code is the central category type for the repository. While all the other objects are necessary to a fully functioning repository, code is the repository’s focus, and the main attraction for users.
In the prototype stage we concentrate on the Ada language, but extensible support for other languages is essential. Given a grammar or specification for a language, the repository structure must be able to accommodate code in that language.
2.4 Validation and Acceptance Documents, Test Data
After the software has been coded, the development team bears the burden of proving that it meets the requirements and follows the specifications. There can be textual descriptions of how the requirements are satisfied. There can also be files of test input data or script files which demonstrate test cases. There may be files of output data captured to show compliance with the
specifications. There may be caveats listing limitations or implementation dependencies. All of these refer back to the requirements, specifications, and actual code of the software system.
2.5 Versions
All of the above assets may exist in the repository in multiple versions. Version 2.0 of a word processor is very similar to, but distinct from, version 2.1, and it is valid for both versions to exist in the repository. This means that all assets of that word processor package, from requirements to acceptance report, may exist in multiple versions. There could also be a Differences document relating one version to the next, which belongs to two versions.
3. Object Granularity
The repository will contain not just code, but code at a number of different levels of granularity. For example, a repository object might be a word processor, available for retrieval as a complete word processing module. But embedded within that package are many other code objects. There might be a queue package for input buffering, which in turn contains a linked list package. The search–and–replace module is an object, but from it can be generated two separate submodules by the technique of program slicing [2, 7], the search submodule and the replace submodule. Each of these is a repository object in its own right, separately retrievable via a query on its own classification.
Similarly, a specifications document for the word processor will exist. But within that document are one or more sections detailing the specification for the search–and–replace module.
A file of test data may be input which exercises the entire package, or it may be input for testing only a very small functional piece of the system. For example, a file containing misspelled words for ensuring that the spell checker functions correctly may have nothing to do with testing the printer output module of a word processing package. However, the file of misspelled words properly resides in the repository as a member of the comprehensive test suite.
Every large object in the repository may contain or be composed of smaller objects also in the repository in their own right. Conversely each small object may be not only a valid repository object but also a constituent of a larger asset.
The issue here is one of complex structure; we use a canonical notion of a document to illustrate the concepts. Consider the general concept of a document with a fixed structuring scheme (sections, subsections, paragraphs, and sentences) as shown in figure 1. Any given document
contains an arbitrary number of sections, which in turn contain an arbitrary number of subsections, and so on.
Every large object in the repository may contain or be composed of smaller objects also in the repository in their own right. Conversely each small object may be not only a valid repository object but also a constituent of a larger asset.
The model includes the definition of the limits of granularity. In the prototype presented here, a Document, the coarsest level, contains successively finer objects, down to paragraphs, the finest level. The document class definition limits the number of granularity levels. For code, a recursively defined class, there is no fixed number of granularity levels. Every bona fide block in the code, no matter how deeply nested, is a repository object at its own level of granularity. Thus the reference given in section 2.1 for the language's specification to allow parsing code into its block structure.
We do not imagine, however, that each lowest-level object will be replicated in every coarser object of which it is a constituent part. A paragraph will not be replicated in every subsection, section, and document which contains it. Rather, the larger-grained objects will contain references to the finer-grained ones, references which are transparent to the user. In object-oriented terminology, the larger-grained objects are composite. More exactly, the references from coarse- to fine-grained objects are shared independent composite references. The reference from a word processing system to one of its constituent string packages is a shared reference because the string package may be contained in more than one parent object. The reference is also independent because the existence of the string package does not depend on the existence of the word processing system. We might decide that the word processing system is of no further use in the repository and delete it, but retain the string package on its own merit.
4. Object Links
As outlined above, there are many objects which will reside in the repository. It is obvious that there are many relationships among them. A spell checker code module is related across granularity levels up to the word processing package which contains it and down to the buffer package it contains. It is related across life-cycle phases, back to the specifications section which discusses spell checking functionality and forward to the verification test of the spell checker module. It is related across versions of the software back to its predecessor and forward to its successor.
A person browsing in a conventional library has only one dimension by which to follow links to find related books. From a book of interest, the browser can search left or right along the shelf to try to find related works. But our repository has the ability to provide many dimensions of links to related objects. The basic lattice structure provides two mechanisms for browsing for related objects, relaxation of facet values in queries and use of closeness metrics which produce queries containing conceptually similar or related terms.
In addition to these, the data structure of the objects in the lattice should allow the inclusion of explicit links along all the dimensions given above. These links connect related objects and must be available to the browser as a means to identify objects related along the axes of granularity, life-cycle phase, and version. All repository object links are bidirectional and reflexive. They may be one-to-one, one-to-many, or many-to-many.
The combination of a rich linking structure within a lattice framework produces the potential for an extremely powerful interface mechanism. Traditional relational query systems can only retrieve data blindly, with no notion of their location in the database. Most current object-oriented systems provide only navigational access to data, with limited querying ability. Our model provides full query access to any node in the lattice through the facet-tuple mechanism. But our model also provides full navigational access via the object structure with its cross links. With
this combination of declarative queries and procedural navigation, it is thus possible for the user to browse through the entire repository finding and pinpointing the exact object of interest.
Object-oriented database systems support our link concepts through object identity. A reflexive relationship implies that the parties (i.e., objects) to the relationship store the identity (or identities) of the objects to which they relate. This is very similar, but not exactly equivalent, to the concept of pointers in more traditional programming languages.
4.1 Phase Links
Phase links are those which join one object in the lattice to another object which is related by virtue of being the “same” object at a different phase of the life cycle. This type of link joins, for example, a requirement to its embodiment as a specification, and then similarly on to its implementation in code.
There must be a link not only between the word processor’s specification document and the word processing code, but also between the section of the specification which treats of the search-and-replace function and the code module which implements that functionality.
Figure 2 illustrates the duality of reference between the various artifacts in the life cycle. A requirements document has as its specification some design document (a one-to-one relationship); that same design document in turn was specified by the requirements document. A given design document may specify aspects of multiple programs (illustrating a one-to-many relationship).
4.2 Granularity Links
Granularity links are those which join objects across granularity levels. This type of link joins, for example, a section in a document is linked to the paragraphs it contains, and also to the chapter which contains it. Similarly, in source code, a search program slice has links to the search-and-replace module from which it was derived via slicing.
The transition from our conceptual model of a document as illustrated in figure 1 to the object model of a document as illustrated in figure 3 exemplifies the representation of complex structure in object-oriented systems.
Hence, a document is a title and an ordered collection of sections. A section is a title and an ordered collection of subsections, and so on. Object identity implies that the document does not actually contain all of its nested components, but rather it contains references to them (effectively pointers to the other objects).
4.3 Version Links
If versions are added to the repository, a new dimension is added. In this dimension there are links from an object forward to a later version or backward to a previous version of the same object concept. These links are orthogonal to the phase links between objects in the same project. It is possible, however, that the version relationship is not as simple as lineal descendancy. Rather, the versions of an object may form a directed acyclic graph, as shown by the bold lines in figure 4, designating the derivation of version 2 from version 1, and the derivation of version 3 from both version 1 and version 2. Any number of new versions may be derived from one or more existing versions. In other words, versioning can exhibit all the characteristics of temporal inheritance.

Figure 4. A Sample Multiple-Version Document
The set of versions for some document artifact in the life cycle is just a labeled association, with the version number acting as label for a specific instance of a document object. This leads to the distinction between a conceptual document and a document version. A conceptual document contains the named associations comprising the various versions, each of which are documents in their own right, as shown in figure 4.
Note that any given object can be referenced by any number of other objects, so that it is quite reasonable for a given section to appear unchanged in multiple versions of a document. This is accomplished by storing the identity of the section in each of the documents' respective ordered sequence of sections.
5. The Model
The above sections describe an architecture for a lattice-based faceted repository of life-cycle assets. Many of the features of this architecture are couched in object-oriented terms. We use these terms because the object-oriented paradigm provides semantics closer to the abstract concept we are trying to model than any other yet developed. Use of object-oriented terminology and concepts, therefore, leads us directly into the use of an object-oriented data model for designing the data structures of the lattice.
The conceptual structure of the repository is a lattice, demanding an object-oriented model which explicitly includes multiple inheritance. As depicted schematically in figure 5 and textually in figure 6, the fundamental superclass of the lattice is the LatticeNode class. The two subclasses of LatticeNode are FacetNode and TupleNode, corresponding to the node types in the Facet and Tuple sublattices as explained in [1].

Figure 5. The Class Hierarchy
The Tuple sublattice contains the references to the items actually stored in the repository. An instance of TupleNode contains the attribute set of RepositoryElement to accomplish this. In our simplified example, a RepositoryElement is a class with only two subclasses, Document and Code. In a full repository implementation there would be other subclasses for storing test data and make scripts, for instance.
LatticeNode
set of LatticeNode — parents
set of LatticeNode — children
FacetNode : subclass of LatticeNode
set of FacetValue
TupleNode : subclass of LatticeNode
set of FacetNode
set of RepositoryElement
RepositoryElement
ObjectTitle
ObjectVersion
ObjectAuthor
ObjectDate
...other attributes
Document : subclass of RepositoryElement
...other attributes
set of SectionObject — constituent items
set of FigureObject — constituent items
Section
SectionHeader
SectionNumber
set of Document — parents
set of Subsection — constituent items
Subsection
SubsectionHeader
SubsectionNumber
set of Section — parents
set of Paragraph — constituent items
Paragraph
ParaNumber: Integer
set of Subsection — parents
ParaText: String
Code : subclass of RepositoryElement
CodeLanguage
...other attributes
set of CodeElement — constituent items
CodeElement
set of Code — parents
set of Declarations
set of Statements
Figure 6. The Class Definitions
The RepositoryElement class defines attributes of general interest such as Title, Author, Version, Date. These attributes constitute general metadata about repository object which would be displayed to the user. The subclasses Document and Code have further attributes which are specific to their types. For example, a Document instance might contain a Drawing, whereas a piece of Code would have a ProgrammingLanguage.
As explained in Section 3, a Document in the repository is not atomic but is composed of instances of the classes Section, Subsection, etc. Each of these classes is an object defined with its own appropriate attributes. Similarly a Code instance contains CodeElement instances.
The encapsulation feature of the object-oriented paradigm makes this model easily extensible. For example, if in the future we added to the repository a sound processing program which required a digitized audio score as an initialization file, the requisite class definition of that object could be added to the schema with no disruption of the current existing definitions.
6. Future Work
We have identified the major objects which will reside in the repository and we have proposed an object-oriented data model for our lattice. With this model it is possible to capture the abstract concept of a static lattice repository which exhibits inheritance among its objects and many complex linkages between them. This model also provides for the encapsulation of the functions which allow navigation between and display of the objects in the repository.
We now intend to examine a number of commercial and experimental object-oriented database management systems to determine the feasibility of implementing this model. The result of this examination should be a prototype of ASV4, the full life-cycle reuse repository. We anticipate that this prototyping phase will generate considerable feedback for refining and fine-tuning the object-oriented data model.
Particular areas that warrant further examination include:
- the role of methods (mechanisms that implement behavior) in the presentation of and navigation through the repository and its contents;
- the ties between an object-oriented model of the repository and a hypermedia representation of the repository; and
- the assistance an object-oriented model of the repository can provide in quality assessment [5, 6].
References
Object Links in the Repository
Addendum
Jon Beck, John Atkins & Bill Bailey
1 – Introduction
In a previous report [Object Links white paper, 27 Sep], hereafter referred to as the "Interim Report", we described a software repository model, based on the object-oriented data model, which was capable of encompassing all of the assets of the full life-cycle of a software development effort. This report contains a description of our efforts to implement this repository architecture using a commercially available object-oriented database management system. We describe some of the features of this implementation and point to some of the next steps to be taken to produce a working prototype of the repository.
The goal of the present effort was to develop the *structure* of the repository, while the next major step, not yet developed, will be to implement the *behavior* of the repository. We are thus here concerned with the static data in the repository, and the relationships among the data. Thanks to the built-in semantics of object-oriented design, we have developed an architecture which allows us to store repository assets in a structure which reflects the static relationships among the various objects of the software development life-cycle.
2 – Conceptual Schema
We described the schema on which our implementation is based in the Interim Report. The object-oriented architecture described in the present report has some differences from the original one in the Interim Report, and so we present here a brief description of the architecture which we actually implemented.
Fundamentally, the architecture is designed to embody the semantics of a lattice-based faceted
repository of life-cycle assets. We assume that any commercial object-oriented data management system will have a built-in distinguished class called "Object" which serves as the parent class of all user-defined classes and objects in the system.
We defined two subclasses of Object, called LatticeNode and RepositoryElement. These two are the parent classes of two completely distinct categories of objects which we have defined. The first category comprises the objects which make up the structure of the lattice itself. All of these objects are descendants of LatticeNode. The second category consists of the assets which the lattice itself actually contains. Each of these assets is an instance of RepositoryElement. As an analogy, the lattice objects (LatticeNodes) are like the wood out of which a set of pigeonholes is built, and the repository elements are like the contents of the pigeonholes.
As explained in [Eichmann & Atkins, SEKE Lattice paper], the very high power of a faceted classification scheme is due in part to the very large number of potential classifications. In fact, however, this can pose a problem for any physical system in that the number of potential classifications, and therefore the number of lattice nodes, in a real-world software repository can easily exceed the number of atoms in the universe. Clearly, then, the lattice must be represented as a sparse data structure; the only nodes which exist are those which are actually populated with one or more repository assets.
In addition, we have used the notions of domain analysis to further reduce the potential search space of the repository. From an operational point of view, a domain can be thought of as defined by a set of facets. All assets which have an exact, specific set of facets in common form a domain. For example, the Generic ADT domain might have Language, Unit Type, and Type of Interest as facets, while the Data Manager domain might consist of the facets Language, Unit Type, Data Model, and Query Language. In the full lattice model, a user may query the repository using any arbitrary set of facets, for example Language and Unit Type, without regard to specific domains. In our prototype, however, we restrict queries to Named Domains, and require a query to have a value for all and only those facets in the domain being queried. This restriction shrinks the search
space dramatically, while not reducing the power of the model at all. Any set of facets may be named as a domain, and thus queried, if the assets at hand indicate its usefulness.
The result of populating only Named Domains with assets results in (or rather, allows) a two-tiered or two-dimensional split in the lattice. At the "top level" is a lattice consisting only of FacetNodes, nodes whose facets are empty of values (and, therefore, of assets). This lattice forms the structure of Named Domains. Each FacetNode is also the top, distinguished node of a second-level lattice, a lattice of ValueNodes. Every ValueNode contains exactly the facets of its parent FacetNode, with its own unique set of values for each of these facets. A given FacetNode only exists in the repository if it is populated with a set of RepositoryElements. The RepositoryElements thus form the sparse data structure which actually contains the repository's assets.
3 – Implementation
For our implementation of the object schema of the repository, we used Servio Corporation's GemStone database system. The code which created the classes and their access methods was written in OPAL, the object-oriented programming language of the GemStone system. We carried out the programming effort within Topaz, which is Servio's OPAL Programming Environment.
As noted in the Interim Report, a central design tenet of the repository schema must be extensibility. There is no way of predicting in advance what kinds of objects will ultimately reside in the repository, and no theoretical limit to their number or physical manifestation. Thus it is impossible to create pro forma the definitions of classes to contain all possible future repository object. Fortunately, the object schema presented here does not require these definitions in advance; new definitions can be added at any time without disturbing the executing environment of the existing repository.
Notwithstanding an inability to predict all of the needed classes for an arbitrary repository, some classes will almost certainly be needed. We have thus provided as examples two subclasses
One note on the physical layout of the OPAL code with which the class structure is defined is that the instance variables in the classes are initially defined without constraints. Then, in a second source file, the constraints on the instance variables are defined. This is done because the class-composition hierarchy contains several circular references. For example, a ValueNode contains RepositoryElements, but the parentNode instance variable of a RepositoryElement is a ValueNode. In GemStone, constraints can only be placed on instance variables of classes which already exist.
4 – Future Work
As mentioned above, we have developed the static structure of the repository. With this structure we are able to store all the assets of the full life-cycle of software development, regardless of the physical form an asset may take. What is now needed is to develop the behavior of each class of asset, as well as of the lattice structure itself, for inclusion into the class definitions.
Most of this behavior is concerned with the interface of the repository with the user. For example, a query is allowed only within the context of a Named Domain. The effect of this is to require that a query must specify a set of values for each of a set of facets which forms a domain. Determining which domain is being queried, and verifying the values of each facet, before actually handing the query on to the GemStone system, is a set of behavioral methods in the user interface.
Similarly, in the lattice model it is possible to navigate the lattice using any of the object links described in the Interim Report. This navigational behavior will also be included in the user interface.
5 – The OPAL Code
! [. . . . . .] CLAS S . OPL
! Jon Beck
13 May 1992
The object schema for the repository, implemented in GemStone OPAL code.
These are the class and subclass definitions, without constraints.
Constraints, being circular references, are in another file.
run
Object subclass: 'LatticeNode'
instVarNames: #('parents' 'children'
'facets'
'domainName')
inDictionary: UserGlobals
isModifiable: True.
%
run
Set subclass: 'LatticeNodeSet'
instVarNames: #()
classVars: #('subclasses')
poolDictionaries: #[]
inDictionary: UserGlobals
constraints: LatticeNode
instancesInvariant: false
isModifiable: True.
%
run
LatticeNode subclass: 'FacetNode'
instVarNames: #('sublatticeDescendants')
inDictionary: UserGlobals
isModifiable: True.
LatticeNode subclass: 'ValueNode'
instVarNames: #('relatedLinks'
'values'
'repositoryElements'
'metaData')
inDictionary: UserGlobals
isModifiable: True.
Object subclass: 'RepositoryElement'
instVarNames: #('parentNode'
'title'
'version'
'author'
'language'
'creationDate'
'inclusionDate'
'metaData'
'data'
'containedIn'
'contains'
'previousPhase'
'nextPhase'
'previousVersion'
'nextVersion'
'relatedLinks')
inDictionary: UserGlobals
isModifiable: True.
run
Set subclass: 'RepositoryElementSet'
instVarNames: #()
classVars: #('subclasses')
poolDictionaries: #[]
inDictionary: UserGlobals
constraints: RepositoryElement
instancesInvariant: false
isModifiable: true.
run
RepositoryElement subclass: 'Document'
instVarNames: #()
inDictionary: UserGlobals
isModifiable: True.
RepositoryElement subclass: 'Code'
instVarNames: #()
inDictionary: UserGlobals
isModifiable: True.
Object subclass: 'DocumentElement'
instVarNames: #()
inDictionary: UserGlobals
isModifiable: True.
run
DocumentElement subclass: 'TextElement'
instVarNames: #('sectionType'
'sectionTitle'
'text')
inDictionary: UserGlobals
isModifiable: True.
DocumentElement subclass: 'GraphicElement'
instVarNames: #('graphicType' 'graphicDetails' 'graphicTitle' 'graphic')
inDictionary: UserGlobals
isModifiable: True.
Object subclass: 'CodeElement'
instVarNames: #('numberOfLines' 'numberOfStatements' 'body')
inDictionary: UserGlobals
isModifiable: True.
! Now the constraints for the variables which will be used for access.
! Only those variables generally used for queries need be constrained.
run
LatticeNode instVar: 'parents' constrainTo: LatticeNodeSet.
LatticeNode instVar: 'children' constrainTo: LatticeNodeSet.
LatticeNode instVar: 'facets' constrainTo: LatticeNodeSet.
LatticeNode instVar: 'domainName' constrainTo: String.
%
run
FacetNode instVar: 'sublatticeDescendants' constrainTo: LatticeNodeSet.
%
run
ValueNode instVar: 'relatedLinks' constrainTo: LatticeNodeSet.
ValueNode instVar: 'values' constrainTo: String.
ValueNode instVar: 'repositoryElements' constrainTo: RepositoryElementSet.
ValueNode instVar: 'metaData' constrainTo: String.
%
run
RepositoryElement instVar: 'parentNode' constrainTo: ValueNode.
RepositoryElement instVar: 'title' constrainTo: String.
RepositoryElement instVar: 'version' constrainTo: String.
RepositoryElement instVar: 'author' constrainTo: String.
RepositoryElement instVar: 'language' constrainTo: String.
RepositoryElement instVar: 'creationDate' constrainTo: DateTime.
RepositoryElement instVar: 'inclusionDate' constrainTo: DateTime.
RepositoryElement instVar: 'metaData' constrainTo: String.
RepositoryElement instVar: 'containedIn' constrainTo: RepositoryElement.
RepositoryElement instVar: 'contains' constrainTo: RepositoryElement.
RepositoryElement instVar: 'previousPhase' constrainTo: RepositoryElement.
RepositoryElement instVar: 'nextPhase' constrainTo: RepositoryElement.
RepositoryElement instVar: 'previousVersion' constrainTo: RepositoryElement.
RepositoryElement instVar: 'nextVersion' constrainTo: RepositoryElement.
RepositoryElement instVar: 'relatedLinks' constrainTo: RepositoryElement.
%
run
TextElement instVar: 'sectionType' constrainTo: String.
TextElement instVar: 'sectionTitle' constrainTo: String.
TextElement instVar: 'text' constrainTo: String.
%
run
GraphicElement instVar: 'graphicType' constrainTo: String.
GraphicElement instVar: 'graphicDetails' constrainTo: String.
GraphicElement instVar: 'graphicTitle' constrainTo: String.
%
run
CodeElement instVar: 'numberOfLines' constrainTo: SmallInteger.
CodeElement instVar: 'numberOfStatements' constrainTo: SmallInteger.
CodeElement instVar: 'body' constrainTo: String.
%
! [ ...OO]METHOD.OPL
! Jon Beck
! 13 May 1992
!
! The methods for the classes.
run
LatticeNode compileAccessingMethodsFor:
#(#parents #children #facets #domainName).
%
run
FacetNode compileAccessingMethodsFor:
#(#sublatticeDescendants).
ValueNode compileAccessingMethodsFor:
#(#relatedLinks #values #repositoryElements #metaData).
RepositoryElement compileAccessingMethodsFor:
#(#parentNode #title #version #author #language #creationDate #inclusionDate
#metaData #data #containedIn #contains #previousPhase #nextPhase
#previousVersion #nextVersion #relatedLinks).
%
run
TextElement compileAccessingMethodsFor:
#(#sectionType #sectionTitle #text).
GraphicElement compileAccessingMethodsFor:
#(#graphicType #graphicDetails #graphicTitle #graphic).
CodeElement compileAccessingMethodsFor:
#(#numberOfLines #numberOfStatements #body).
%
Balancing Generality and Specificity in Component-Based Reuse*†
David Eichmann and Jon Beck
Software Reuse Repository Lab
Dept. of Statistics and Computer Science
West Virginia University
Send correspondence to:
David Eichmann
SoRReL
Dept. of Statistics and Computer Science
West Virginia University
Morgantown, WV 26506
Email: eichmann@cs.wvu.wvnet.edu
* Submitted to The International Journal of Software Engineering and Knowledge Engineering.
† This work was supported in part by NASA as part of the Repository Based Software Engineering project, cooperative agreement NCC-9-16, project no. RICIS SE.43, subcontract no. 089 and in part by a grant from MountainNet Inc.
Abstract
For a component industry to be successful, we must move beyond the current techniques of black box reuse and genericity to a more flexible framework supporting customization of components as well as instantiation and composition of components. Customization of components strikes a balance between creating dozens of variations of a base component and requiring the overhead of unnecessary features of an “everything but the kitchen sink” component. We argue that design and instantiation of reusable components have competing criteria – design-for-reuse strives for generality, design-with-reuse strives for specificity – and that providing mechanisms for each can be complementary rather than antagonistic. In particular, we demonstrate how program slicing techniques can be applied to customization of reusable components.
1 – Introduction
The impediments to a successful reuse infrastructure in the software engineering community have typically been separated into social and technological issues [26]. Furthermore, the social issues (e.g., comprehension, trust, and investiture) often are characterized as being the more critical, as there is a perception that all of the technical issues (e.g., environments, repositories, and linguistic support) have been solved [27]. We do not agree with this assessment (see [8] for our arguments regarding repositories and environments), and furthermore believe that appropriate application of technology can alleviate certain of the social issues just mentioned.
This paper addresses two reuse impediments – component comprehension by a reuser [14] and the fitness of a component for a given application – and how technical support, in this case language features and program slicing, alleviate these impediments. These two impediments drive the consumer side of reuse repository design, for without comprehensibility users will not select artifacts from the repository, and without adequate conformance to requirements users will not incorporate artifacts into systems even if they do select them. These two impediments also drive the design process for reusable components, since components perceived as ill-suited for reusers’ application domains (and hence not incorporated into the resulting systems) have not met the requirements of a design-for-reuse effort.
We begin in section 2 by characterizing the inherent conflict between the design goals for design-for-reuse and design-with-reuse. We then review mechanisms that support particular structural and behavioral aspects of component design in section 3. The mechanisms described support flexibility in the design of a component. We consider mechanisms in section 4 to constrain an implementation, supporting specificity in the instantiation of a component, and show in section 5 how to employ program slicing as one such mechanism. Section 6 demonstrates the application of our technique to a moderate-sized example.
Design-for-reuse focuses on the potential reusability of the artifacts of a design process. Design-with-reuse, on the other hand, focuses on employing existing artifacts wherever possible in the design process. The intent of the two approaches, and hence the various criteria that each of them employ, is then quite distinct. In particular, design for reuse strives for generality, even to the point of additional cost to the current project, and design with reuse strives to reduce cost to the current project, even to the point of adapting non-critical project requirements to achieve conformance with existing artifacts.
Garnett and Mariani proposed the following attributes for reusable software [10]:
- environmental independence – no dependence on the original development environment;
- high cohesion – implementing a single operation or a set of related operations;
- loose coupling – minimal links to other components;
- adaptability – easy customization to a variety of situations;
- understandability;
- reliability; and
- portability.
These attributes clearly reflect goals that should apply to all products of a design-for-reuse effort, and some of these attributes (particularly understandability and reliability) apply to all software development efforts. Not so clear is whether these attributes reflect the goals of design-with-reuse efforts.
We contend that there is an inherent conflict between design-for-reuse and design-with-reuse that centers upon adaptability. Design-for-reuse strives to create artifacts that are as generally applicable as possible, in the worst case creating “everything-but-the-kitchen-sink” artifacts, loading a component with features in an effort to ensure applicability in all situations. Design-with-reuse strives to identify that artifact which most specifically matches a given requirement. Anything less
requires additional effort, both in comprehension and coding. Anything more carries with it the penalty of excess resource consumption and increased comprehension effort.
The specificity that we seek in design-with-reuse takes two forms — the first is that of avoiding additional functionality in a simple component; the second is that of avoiding additional functionality in an abstraction, implemented as a package/module. Specificity becomes increasingly critical when considering scale. The additional storage consumed and increased comprehension effort posed by a simple abstract data type quickly become the multi-megabyte “hello world” applications of today’s user interface management systems, and threaten intractability in the domain of megaprogramming [4, 19].
3 – Language Mechanisms Supporting Design–For–Reuse
Designing a software component for reuse involves a number of issues, including analysis of the intended target domain [21, 22], the coverage that this component should provide for the domain [22], and the nature and level of parameterization of the component [7, 28, 29]. A number of developments in programming language design directly bear upon these issues. We focus here upon those we see as most beneficial.
3.1 – Procedural and Modular Abstraction
The obvious advantages that functions and procedures provide in comprehension and reuse of portions of a program (even if the reuse is only at a different location in the same program) are so well recognized, that no contemporary language proposal is taken seriously without them. The package (or module) concept, with separate specification and implementation of a collection of data and procedural definitions, has arguably reached the same level of acceptance. Sommerville’s list of classes of reusable components (functions, procedures, declaration packages, objects, abstract data types, and subsystems) [25] indicates the depth of this acceptance — virtually every class listed is directly implementable using one of the two mechanisms (objects being the only non-obvious fit).
3.2 – Parameterization and Genericity
The utility of a function or procedure is severely limited without the ability to provide information customizing the effect of a specific invocation. Parameters comprise the explicit contract between a function and its invocations, and are generally accepted as far preferable to the implicit contract provided by shared global state. Genericity, or more formally, parametric polymorphism [6], involves the parameterization of program units (both functions/procedures and packages/modules) with types, variables, and operations (functions, procedures, tasks, and exceptions). Parameters effectively support families of invocations. Genericity extends this support to families of instantiations, each with its own family of invocations, providing increased adaptability and portability [28].
3.3 – Inheritance
Inheritance involves the creation of generalization/specialization structures, a tree in the case of single inheritance, a lattice in the case of multiple inheritance. These generalizations/specializations may be structural (in the case of subtypes [6]) or behavioral (in the case of classes [11]). Whatever the structuring mechanism, inheritance supports the creation of variations of a base component, each with its own interface [15], as well as instances of those variations. Inheritance thus is a very useful mechanism for the creation of certain classes of software artifacts. Note, however, that using inheritance as a reuse-enabling mechanism is not without its own hazards, most notably scalability and the violation of information hiding [23, 24].
4 – Language Mechanisms Supporting Design-With-Reuse
The previous section primarily addressed the creation of program structure. Our primary interest in this section involves not the creation of new reusable components, but rather their natural involvement in the development process. This corresponds to the responsibilities of Basili’s project organization [3].
4.1 – Procedural and Modular Abstraction
Much of today’s reuse takes place at the level of procedures and packages, either as source or object code. The linguistic and environmental mechanisms for this, including source and object libraries and separate compilation, provide little over what a simple text editor with cut and paste commands provides. The onus of comprehension and adaptation is placed upon the reuser, particularly if the reuser is interested in increasing the specificity of the component (which may even be proscribed by the social infrastructure, i.e. management). The consequence of design-with-reuse in this context is thus monolithic reuse, an all or nothing acceptance of an entire component.
4.2 – Genericity
Genericity readily supports the creation of specializations of the generic artifact through instantiation. However, genericity as defined in languages such as Ada provides little beyond complete instantiation of a generic component into a completely concrete instance. Further, partial instantiation does little in terms of additional flexibility, as every successive partial instantiation makes the resulting generic more concrete. Hence genericity provides the same form of monolithic reuse as that described in the previous section, with the option of customizing the instances.
4.3 – Inheritance
Inheritance performs as readily in support of a reuser as in support of a developer of components. The reuser can both instantiate new instances of the component and derive new component classes from the original. This second issue is a particularly beneficial one, as it allows for the development of unanticipated refinements to the program model without requiring adaptation of existing code. However, inheritance exhibits the same specificity limitations as abstraction and genericity, supporting only monolithic reuse, in the case of instantiation, or incremental monolithic reuse, in the case of class refinement.
Program Slicing
The mechanisms discussed in sections 3 and 4 add structure and/or complexity to a program. Parameterization and genericity increase the interface complexity of a program unit. Packages and inheritance increase either the number of program units or the structural complexity of those units. Hence, current languages do not have explicit mechanisms that address the conflicting goals of design-for-reuse and design-with-reuse. We therefore propose a new mechanism for reconciling the two approaches (by increasing component structural specificity) which works in conjunction with the facilities provided in Ada—a new form of program slicing. We use Ada for our examples, as it is a language whose built-in features facilitate the types of transformations which we invoke. However, the concepts we present are not confined to any particular language.
In his thesis [30], Weiser introduced the concept of program slicing. In this form of slicing, called static slicing, a slice of a program is an executable subset of the source statements which make up program. A slice is specified by a variable and a statement number, and consists of all statements which contribute to the value of that variable at the end of execution of that statement, together with any statements needed to form a properly executing wrapper around the slice proper.
Dynamic slicing, [1, 2, 17] is a second form of slicing which is determined at runtime and is dependent on input data. A dynamic slice is the trace of all statements executed during a program run using a particular input data set, refined by specifying only those executed statements which reference a specified set of variables. Dynamic slicing was specifically designed as an aid in debugging, and is used to help in the search for offending statements in finding a program error.
By definition, static slicing is a pre-compilation operation, while dynamic slicing is a run-time analysis. Our interface slicing belongs in the category of static slicing, as it is a data-independent pre-compilation code transformation. Since our interest here is only with static slices, henceforth we will use slicing to mean static slicing, and we will not again discuss dynamic slicing.
procedure wc (theFile : in string; nl, nw, nc : out natural := 0) is
inword : boolean := FALSE;
theCharacter : character;
file : file_type;
begin
open(file, IN_FILE, theFile);
while not end_of_file(file) loop
get(file, theCharacter);
nc := nc + 1;
if theCharacter = LF then
nl := nl + 1;
end if;
if theCharacter = ' '
or theCharacter = LF
or theCharacter = HT then
inWord = FALSE;
else if not inWord then
inWord = TRUE;
nw := nw + 1;
end if;
end loop;
close(file);
end wc;
Figure 1: wc, a procedure to count text
5.1 – Previous Work in Slicing
In his thesis [30] and subsequent work [31, 32, 33], Weiser used slicing to address various issues primarily concerned with program semantics and parallelism. Gallagher and Lyle more recently employed a variation of slicing in limiting the scope of testing required during program maintenance [20].
Program slicing has been proposed for such uses as debugging and program comprehension [32], parallelization [5], merging [12, 18], maintenance, and repository module generation [9].
As an example of program slicing, we present the following example, adapted from Gallagher & Lyle [9]. The procedure wc, presented in Figure 1, computes the count of lines, words, and characters in a file.* Figure 2 gives the results of slicing wc on the variable nc at the last line of the procedure. Since the variables nl, nw, and inword do not contribute to the value of nc, they do not appear in the slice. Also, the statements on lines 10 through 20 of the original procedure do not
* This procedure is not entirely correct, since the Ada get procedure skips over line terminators, unlike the C getchar function. We adapted wc in this way to clarify its actions and retain the flavor of the original function.
1 procedure wc (theFile : in string; nc : out natural := 0) is
2 theCharacter : character;
3 file : file_type;
4 begin
5 open(file, IN_FILE, theFile);
6 while not end_of_file(file) loop
7 get(file, theCharacter);
8 nc := nc + 1;
9 end loop;
10 close(file);
11 end wc;
Figure 2: wc sliced on nc
appear in the slice. While this slice follows the spirit of a classic slice, and will serve to illustrate classic slicing, it also differs in several important ways, as described below.
5.2 – Interface Slicing
We propose a new form of slicing, interface slicing, which is performed not on a program but on a component. Similar to previous work in static slicing, our interface slice consists of a compilable subset of the statements of the original program. The interface slice is defined such that the behavior of the statements and the values of the variables in the slice is identical to their behavior and values in the original program.
However, while previous slicing efforts have attempted to isolate the behavior of a set of variables, even across procedural boundaries, our slice seeks rather to isolate portions of a component which export the behavior we desire. In the following discussion, we assume for simplicity that a package implements a single ADT, and we use package and ADT interchangeably.
Unlike standard slicing techniques which are usually applied to an entire program, interface slicing is done on a fragment of a program – a component – since our goal is to employ the necessary and sufficient semantics of a component for use in the target system. Interface slicing is at the level of procedures, functions, and task types. If a procedure is invoked at all, the entire procedure must be included, as we have no way of knowing a priori what portion of the procedure will be needed. * However, if an ADT is incorporated into a system, not necessarily all of its operations are
invoked. The interface slicing process determines which operations are to be included, and which can be eliminated. Because interface slicing treats procedures atomically, the complex program dependence graph analysis of standard slicing [13] is not necessary. A single pass of the call graph of an ADT's operations is sufficient to determine the slice. We use "operation" as a general term to encompass procedures, functions, and exceptions, and include tasks with procedures in that a task is another way of encapsulating a subprogram unit.
We will illustrate the concept of interface slicing first by examining a simple example, a toggle ADT. First consider package `toggle1`, in Figure 3. This package exports the public operations `on`, `off`, `set`, and `reset`. `On` and `off` are examination operations which query the state of the toggle, while `set` and `reset` are operations which modify the state of the toggle. Now suppose that we wish to have a toggle in a program which we are writing, but we have a need for only three of the four operations, namely `on`, `set`, and `reset`. In standard Ada, we have two choices. We can include the package as is, and have the wasted space of the `off` operation included in our program. This is the kitchen sink syndrome. Alternatively, we can edit the source code manually (assuming we have access to it) and remove the `off` operation, thereby saving space, but requiring a large amount of code comprehension and introducing the danger of bugs due to hidden linkages and dependencies. In both these cases, we see the generality of design-for-reuse competing with the desired specificity of design-with-reuse.
Instead, we propose the invocation of an interface slicing tool to which we give the `toggle1` package together with the list of operations we wish to include in our program. The tool then automatically slices the entire package based on the call graph of its operations, generating a slice containing only those operations (and local variables) needed for our desired operations. The slice of `toggle1` which contains only the three operations is shown in Figure 4.
* In other words, an interface slice is orthogonal to a standard static slice. The use of one technique neither requires nor inhibits the use of the other. We are not discussing the technique of standard static slicing here, other than to contrast it with our interface slice, and so we do not assume that an interprocedural slicer is operating at the same time as our interface slicer.
package toggle1 is
function on return boolean;
function off return boolean;
procedure set;
procedure reset;
end toggle1;
package body toggle1 is
theValue : boolean := FALSE;
function on return boolean is
begin
return theValue = TRUE;
end on;
function off return boolean is
begin
return theValue = FALSE;
end off;
procedure set is
begin
theValue := TRUE;
end set;
procedure reset is
begin
theValue := FALSE;
end reset;
end toggle1;
Figure 3: A toggle package
As another example, consider the package toggle2, which in addition to the operations of toggle1 includes the operation swap. This package is shown in Figure 5. Suppose we wish to write a program which needs a toggle ADT and the operations on and swap. The interface slicing tool finds that the operation on has no dependencies, but the operation swap needs on, set, and reset, and so the desired slice of toggle2 which is produced for our program is contains the four operations, on, set, reset, and swap, and does not contain off. This slice is shown in Figure 6.
One of the differences between interface slices and standard slices is the way that interface slices are defined. While a standard slice is defined by a slicing criterion consisting of a program, a statement and a set of variables, an interface slice is defined by a package and a set of operations.
package toggle1 is
function on return boolean;
procedure set;
procedure reset;
end toggle1;
package body toggle1 is
theValue : boolean := FALSE;
function on return boolean is
begin
return theValue = TRUE;
end on;
procedure set is
begin
theValue := TRUE;
end set;
procedure reset is
begin
theValue := FALSE;
end reset;
end toggle1;
Figure 4: The toggle package sliced by on, set and reset
in its interface. The package is an example of design-for-reuse and implements a full ADT, complete with every operation needed to legally set and query all possible states of the ADT. The interface slicer is an aid to design-with-reuse and prunes the full ADT down to the minimal set of operations necessary to the task at hand. The interface slicer does not add functionality to the ADT, as the ADT contains full functionality to start with. Rather, the slicer eliminates unneeded functionality, resulting in a smaller, less complex source file for both compiler and reuser to deal with, and smaller object files following compilation.
6 – An Extended Example
The examples above illustrate the general concept of interface slicing, but leave out some important details. To fill in some of these details, we will next examine a pair of generic packages in the public domain. These packages were explicitly written to be used as building blocks for Ada
package toggle2 is
function on return boolean;
function off return boolean;
procedure set;
procedure reset;
procedure swap;
end toggle2;
package body toggle2 is
theValue : boolean := FALSE;
function on return boolean is
begin
return theValue = TRUE;
end on;
function off return boolean is
begin
return theValue = FALSE;
end off;
procedure set is
begin
theValue := TRUE;
end set;
procedure reset is
begin
theValue := FALSE;
end reset;
procedure swap is
begin
if on then
reset;
else
set;
end if;
end swap;
end toggle2;
Figure 5: Version 2 of the toggle package
programs. The first is a generic package which provides the ADT set. The package is instantiated
by supplying it with two parameters, the first being the type of element which the set is to contain,
and the second a comparison function to determine the equality of two members of this type. The
package provides all the operations necessary to create, manipulate, query, and destroy sets. The
full interface specification of the set is given in Appendix A.
package toggle2 is
function on return boolean;
procedure swap;
end toggle2;
package body toggle2 is
theValue : boolean := FALSE;
function on return boolean is
begin
return theValue = TRUE;
end on;
procedure set is
begin
theValue := TRUE;
end set;
procedure reset is
begin
theValue := FALSE;
end reset;
procedure swap is
begin
if on then
reset;
else
set;
end if;
end swap;
end toggle2;
Figure 6: Version 2 of toggle sliced by on and swap
This set package happens to use a list as the underlying representation upon which it builds the set ADT, and so requires the second generic package which supplies the list ADT. This happens to be a singly-linked list implementation which exports all the operations necessary to create, manipulate, query, and destroy lists. This package also requires two generic parameters, the same ones which set requires. The specification for the list package is given in Appendix B.
In the particular list and set packages we used for our example, there were no private operations. Private operations are not available to be used in an interface slicing criterion; only the exported operations in the interface can be in the slicing criterion. In general, however, private operations are treated identically to exported ones during the slicing process. The slicer, being a
privileged pre-compilation code transformer, does not respect privacy.
6.1 – A Single Level of Slicing
Now suppose we wish to use the set package in a program we are writing, but we have a need for only a few of the set operations, specifically, in this example, create, insert, and equal. We would like to include all the code necessary to accomplish these operations, but would like to have only the necessary code, and no more.
In order to slice the set package, we must examine the call graph of operations in the set package for the transitive closure of the three desired operations. Figure 7 shows the complete call graph of the set package, and figure 8, shows the transitive closure of create, insert, and equal (nodes s2, s4 and s8, respectively). Figure 8 shows the slice corresponding to these three operations. Out of the total of 14 operations exported by the original package, the slice based on create, insert, and equal contains only 8 operations, with a considerable reduction in total size of code, although the complexity of the call graph remains the same.
Notice that in this example, the sliced set package needs the same number and type of generic parameters as did the original package. This will not always be the case, however. In Figure 1, the
* The call graph node labels correspond to the comments associated with each operation for the package specifications appearing in the appendices.
original wc procedure needed 4 parameters, but the slice based on nc shown in Figure 2 needed only 2 parameters. In general, out of all the local variables in a component, including both variables bound to parameters and those declared within the component’s scope, a slice will include a subset of these local variables.
6.2 - A Second Level of Slicing
While the 8 operations represent an improvement over the original 14, we can go further, and examine not only the set package, but also the list package as well. If we examine the transitive closure of the three desired operations in the call graph of all the operations of both the set and list packages, we can accomplish a much more dramatic improvement in the size and complexity of the resulting slice. Figure 9 shows the full call graph of the set and list packages. In standard Ada usage, all of this would be included in a program were the generic set and list packages instantiated in a program. Figure 10 shows the call graph which is exactly the transitive closure of the set operations create, insert, and equal, as would be produced by interface slicing. The size and complexity of this call graph are obviously much less than that of the full graph. Table 1 gives some statistics on the relative sizes of the packages and their call graphs.
None of the examples above involved overloaded names. Interface slicing in the presence of overloading is somewhat more complicated. Assuming that the resolution can be accomplished...
completely at compile time, there are two options. The first is a simple, naive approach in which all versions of an overloaded operation are included. The second is to perform the type checking for parameters and return value (if any) to determine which of the overloaded versions are actually called. For example, assume that list's operation *attach* is a quadruply overloaded procedure which can be called with two elements, an element and a list, a list and an element, or two lists. Resolution of the overloading may, in a particular situation, allow three of the four procedures to be sliced away, resulting in improved reduction of size and complexity.
If the overloading cannot be resolved at compile time, but must wait until runtime, we have no option but to include the code for all possible operations which may be called. A static slice can only blindly assume worst-case in the presence of run-time binding of overloaded procedure.
names. Although our example extends to only two levels, the slicing can extend to as many levels as exist in the compilation dependency graph of the packages included in the program.
7 – Conclusion: Balancing Genercity and Specificity
We have discussed two main reuse-oriented paradigms in software engineering, namely design-for-reuse and design-with-reuse, and how the goals of these two paradigms have in the past been viewed as being antagonistic, with the former striving for generality and the latter striving for specificity. We have shown that with the proper language mechanisms and development techniques, the goals are in fact complementary. The specific mechanism we use by way of example is a new form of static program slicing which we call interface slicing. Using interface slicing, a complete and generic component can be adapted to the specific needs of the program at hand, increasing comprehension and reducing complexity, without sacrificing the generality of the base component. Thus a developer designing a component for reuse can be completely unfettered of all size constraints and strive for total generality, knowing that a reuser of the components can effortlessly have all unneeded functionality sliced away in a pre-compilation step.
The artifacts produced by an interface slicer should not be considered as new components, any more than instantiations of a generic are viewed as new components. Rather, we want to emphasize the retention of the derivation specification, avoiding additional maintenance problems through the life-cycle of what would then be custom components. We should keep the desired interface specification, and alter that when we need to change the way in which we bind through the interface to the base component. Just as we don’t associate any cost per se with the instantiation of a generic, we should not associate a cost with specialization through interface slicing, since it can be completely handled by the development environment.
Our approach addresses indirectly a critical social aspect of reuse, the trust that reusers place in the components extracted from the repository [16]. Deriving a family of interface slices from a
base component implies that if the base component is correct (or at least certified), then all of the slices must necessarily be correct (or at least certified) also.
References
Appendix A – The Package Specification for Set
Note: the comments in the right margin refer to the node labels in the call graphs of Figures 7, 8, 9, and 10.
1 generic
type elemType is private;
with function equal(e1, e2: elemType) return boolean is "=";
package setPkg is
type set is private;
type iterator is private;
noMore: exception; -- s1
function create return set; -- s2
procedure delete(s: in out set; e: in elemType); -- s3
procedure insert(s: in out set; e: in elemType); -- s4
function intersection(s1, s2: set) return set; -- s5
function union(s1, s2: set) return set; -- s6
function copy(s: set) return set; -- s7
function equal(s1, s2: set) return boolean; -- s8
function isEmpty(s: set) return boolean; -- s9
function isMember(s: set; e: elemType) return boolean; -- s10
function size(s: set) return natural; -- s11
function makeIterator(s: set) return iterator; -- s12
procedure next(iter: in out iterator; e: out elemType); -- s13
function more(iter: iterator) return boolean; -- s14
end setPkg;
Appendix B – The Package Specification for List
Note: the comments in the right margin refer to the node labels in the call graphs of Figures 9 and 10.
1 generic
2 type elemType is private;
3 with function equal(e1, e2: elemType) return boolean is "=";
4 package listPkg is
5
type list is private;
6 type iterator is private;
7
8 circularList: exception; -- 11
9 emptyList: exception; -- 12
10 itemNotPresent: exception; -- 13
11 noMore: exception; -- 14
12
13 procedure attach(l1: in out list; l2 in list); -- 15
14
15 function copy(l: list) return list; -- 16
16 function create return list; -- 17
17
18 procedure deleteHead(l: in out list); -- 18
19
20 procedure deleteItem(l: in out list; e: in itemType); -- 19
21
22 procedure deleteItems(l: in out list; e: in itemType); -- 110
23
24 function equal(l1, l2: list) return boolean; -- 111
25
26 function firstValue(l: list) return itemType; -- 112
27
28 function isInList(l: list; e: itemType) return boolean; -- 113
29
30 function isEmpty(l: list) return boolean; -- 114
31
32 function lastValue(l: list) return itemType; -- 115
33
34 function length(l: list) return integer; -- 116
35
36 function makeIterator(l: list) return iterator; -- 117
37
38 function more(l: iterator) return boolean; -- 118
39
40 procedure next(iter: in out iterator; e: itemType); -- 119
41
42 procedure replaceHead(l: in out list; e: itemType); -- 120
43
44 procedure replaceTail(l: in out list; newTail: in list); -- 121
45
46 function tail(l: list) return list; -- 122
47
48 function last(l: list) return list; -- 123
49
50 end listPkg;
|
{"Source-Url": "https://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19920023934.pdf", "len_cl100k_base": 14431, "olmocr-version": "0.1.49", "pdf-total-pages": 66, "total-fallback-pages": 0, "total-input-tokens": 125565, "total-output-tokens": 19307, "length": "2e13", "weborganizer": {"__label__adult": 0.0002627372741699219, "__label__art_design": 0.0003616809844970703, "__label__crime_law": 0.00024962425231933594, "__label__education_jobs": 0.0009016990661621094, "__label__entertainment": 4.380941390991211e-05, "__label__fashion_beauty": 0.00011593103408813477, "__label__finance_business": 0.00016570091247558594, "__label__food_dining": 0.00021755695343017575, "__label__games": 0.000370025634765625, "__label__hardware": 0.00054168701171875, "__label__health": 0.0002605915069580078, "__label__history": 0.00019872188568115232, "__label__home_hobbies": 7.849931716918945e-05, "__label__industrial": 0.00023555755615234375, "__label__literature": 0.00018537044525146484, "__label__politics": 0.00019800662994384768, "__label__religion": 0.0003204345703125, "__label__science_tech": 0.006153106689453125, "__label__social_life": 7.134675979614258e-05, "__label__software": 0.004791259765625, "__label__software_dev": 0.9833984375, "__label__sports_fitness": 0.0001971721649169922, "__label__transportation": 0.0003783702850341797, "__label__travel": 0.00015473365783691406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 76630, 0.05176]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 76630, 0.42431]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 76630, 0.88177]], "google_gemma-3-12b-it_contains_pii": [[0, 366, false], [366, 2859, null], [2859, 2890, null], [2890, 2890, null], [2890, 3762, null], [3762, 3762, null], [3762, 3829, null], [3829, 3829, null], [3829, 4137, null], [4137, 4137, null], [4137, 4137, null], [4137, 4137, null], [4137, 5641, null], [5641, 7558, null], [7558, 9585, null], [9585, 10104, null], [10104, 12086, null], [12086, 14248, null], [14248, 16162, null], [16162, 16713, null], [16713, 18314, null], [18314, 19749, null], [19749, 20747, null], [20747, 22706, null], [22706, 24062, null], [24062, 24062, null], [24062, 24062, null], [24062, 24062, null], [24062, 25749, null], [25749, 28130, null], [28130, 30253, null], [30253, 32131, null], [32131, 33192, null], [33192, 34060, null], [34060, 35512, null], [35512, 37165, null], [37165, 37443, null], [37443, 37443, null], [37443, 37443, null], [37443, 37443, null], [37443, 38120, null], [38120, 38956, null], [38956, 41056, null], [41056, 42917, null], [42917, 44985, null], [44985, 46960, null], [46960, 48919, null], [48919, 51151, null], [51151, 52977, null], [52977, 54895, null], [54895, 57415, null], [57415, 58808, null], [58808, 60198, null], [60198, 61337, null], [61337, 62739, null], [62739, 64163, null], [64163, 65660, null], [65660, 66608, null], [66608, 68801, null], [68801, 68968, null], [68968, 70782, null], [70782, 72755, null], [72755, 74038, null], [74038, 75057, null], [75057, 76630, null], [76630, 76630, null]], "google_gemma-3-12b-it_is_public_document": [[0, 366, true], [366, 2859, null], [2859, 2890, null], [2890, 2890, null], [2890, 3762, null], [3762, 3762, null], [3762, 3829, null], [3829, 3829, null], [3829, 4137, null], [4137, 4137, null], [4137, 4137, null], [4137, 4137, null], [4137, 5641, null], [5641, 7558, null], [7558, 9585, null], [9585, 10104, null], [10104, 12086, null], [12086, 14248, null], [14248, 16162, null], [16162, 16713, null], [16713, 18314, null], [18314, 19749, null], [19749, 20747, null], [20747, 22706, null], [22706, 24062, null], [24062, 24062, null], [24062, 24062, null], [24062, 24062, null], [24062, 25749, null], [25749, 28130, null], [28130, 30253, null], [30253, 32131, null], [32131, 33192, null], [33192, 34060, null], [34060, 35512, null], [35512, 37165, null], [37165, 37443, null], [37443, 37443, null], [37443, 37443, null], [37443, 37443, null], [37443, 38120, null], [38120, 38956, null], [38956, 41056, null], [41056, 42917, null], [42917, 44985, null], [44985, 46960, null], [46960, 48919, null], [48919, 51151, null], [51151, 52977, null], [52977, 54895, null], [54895, 57415, null], [57415, 58808, null], [58808, 60198, null], [60198, 61337, null], [61337, 62739, null], [62739, 64163, null], [64163, 65660, null], [65660, 66608, null], [66608, 68801, null], [68801, 68968, null], [68968, 70782, null], [70782, 72755, null], [72755, 74038, null], [74038, 75057, null], [75057, 76630, null], [76630, 76630, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 76630, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 76630, null]], "pdf_page_numbers": [[0, 366, 1], [366, 2859, 2], [2859, 2890, 3], [2890, 2890, 4], [2890, 3762, 5], [3762, 3762, 6], [3762, 3829, 7], [3829, 3829, 8], [3829, 4137, 9], [4137, 4137, 10], [4137, 4137, 11], [4137, 4137, 12], [4137, 5641, 13], [5641, 7558, 14], [7558, 9585, 15], [9585, 10104, 16], [10104, 12086, 17], [12086, 14248, 18], [14248, 16162, 19], [16162, 16713, 20], [16713, 18314, 21], [18314, 19749, 22], [19749, 20747, 23], [20747, 22706, 24], [22706, 24062, 25], [24062, 24062, 26], [24062, 24062, 27], [24062, 24062, 28], [24062, 25749, 29], [25749, 28130, 30], [28130, 30253, 31], [30253, 32131, 32], [32131, 33192, 33], [33192, 34060, 34], [34060, 35512, 35], [35512, 37165, 36], [37165, 37443, 37], [37443, 37443, 38], [37443, 37443, 39], [37443, 37443, 40], [37443, 38120, 41], [38120, 38956, 42], [38956, 41056, 43], [41056, 42917, 44], [42917, 44985, 45], [44985, 46960, 46], [46960, 48919, 47], [48919, 51151, 48], [51151, 52977, 49], [52977, 54895, 50], [54895, 57415, 51], [57415, 58808, 52], [58808, 60198, 53], [60198, 61337, 54], [61337, 62739, 55], [62739, 64163, 56], [64163, 65660, 57], [65660, 66608, 58], [66608, 68801, 59], [68801, 68968, 60], [68968, 70782, 61], [70782, 72755, 62], [72755, 74038, 63], [74038, 75057, 64], [75057, 76630, 65], [76630, 76630, 66]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 76630, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
4e798c4df26928b72211105310cf87b5ac592361
|
Guidelines for Sustainable Open Source Communities in the Public Sector
Disclaimer
The information and views set out in this publication are those of the author(s) and do not necessarily reflect the official opinion of the Commission. The Commission does not guarantee the accuracy of the data included in this study. Neither the Commission nor any person acting on the Commission’s behalf may be held responsible for the use which may be made of the information contained therein.
© European Union, 2020
The reuse policy of the European Commission is implemented by the Commission Decision 2011/833/EU of 12 December 2011 on the reuse of Commission documents (OJ L 330, 14.oun12.2011, p. 39). Except otherwise noted, the reuse of this document is authorised under the Creative Commons Attribution 4.0 International (CC BY 4.0) licence (https://creativecommons.org/licenses/by/4.0/). This means that reuse is allowed provided appropriate credit is given and any changes are indicated. For any use or reproduction of photos or other material that is not owned by the EU, permission must be sought directly from the copyright holders.
Picture on cover page: pixabay.com
AUTHORS:
Vivien DEVENYI Wavestone
Debora DI GIACOMO Wavestone
Chloé DUSSUTOUR Wavestone
Barbora KUDZMANAITE Wavestone
Maha SHAIKH King’s College London
REVIEWERS:
Natalia ARISTIMUÑO PÉREZ European Commission
Monika SOWINSKA European Commission
Georges LOBO European Commission
This work was carried out for the ISA² programme under Specific Contract No 272,
Framework Contract DI/07626 by: WAVESTONE
Acknowledgments
The OSOR team is grateful for the generous feedback received from the community throughout the development of these Guidelines. We would like to especially thank Nephtis Brandsma (Groningen Municipality), Miguel Arana Catania (formerly CONSUL), Leonardo Favario (Developers Italia), Philippe Bareille and Pierre Levy (City of Paris), Fritjof Knier (Integreat), Timo Aarnio (OSKARI), Bastien Guerry (DINUM), Janis Tupulis (LATA), the Foundation for Public Code team, Mike Linksvayer (GitHub), Tiago Mendonça (Portuguese Administrative Modernisation Agency), Jani Kylmäaho (NLS) for their time and contributions.
Contents
1. Setting the foundation for sustainable open source engagements ........................ 10
1.1 Assess your needs & capabilities ................................................................. 10
1.2 Embed your community within the public administration – make it ‘official’ ... 13
1.3 Secure project and community funding ....................................................... 14
2. Joining an existing community ........................................................................ 19
2.1 Understand the community behind the software .......................................... 19
2.2 Facilitate sustainable collaboration .............................................................. 22
2.3 Contribute to the solution in the long run .................................................... 23
3. Building your own public sector OSS community .......................................... 26
3.1 Operating within your public administration ................................................ 26
3.2 Focus on the software .................................................................................... 28
3.3 Organise the community ................................................................................ 30
3.4 Keep the community active ........................................................................... 35
3.5 Grow your community ................................................................................... 37
4. Long-term sustainability .................................................................................... 40
5. Methodological Note ......................................................................................... 42
List of figures
Figure 1 Case studies on the sustainability of open source communities. ............... 6
Figure 2 How to assess your software needs? ......................................................... 11
Figure 3 Key elements to consider when assessing Total Cost of Ownership. ....... 15
Figure 4 Understanding existing communities....................................................... 20
Figure 5 High Level Organisation of OSS communities......................................... 32
Figure 6 Community roles & responsibilities....................................................... 33
Introduction
Open source software (OSS) can be highly beneficial to those who choose to harness it. One of the key strengths of OSS is its adaptability: anyone can reuse or modify it to best suit their needs, and therefore, its use is not restricted to any single domain or user group. Public administrations represent one such user group which stands to gain from the use of OSS when developing and implementing IT solutions for both internal processes and the delivery of digital public services.
Nevertheless, the adoption of OSS across public administrations has historically been a slow and often unsustainable journey. There are many examples of public administrations at the national or local level adopting OSS, only to switch back to a proprietary solution at a later stage. This happens for many reasons, be it due to compatibility issues or a change of heart at the managerial level. However, across public administrations of all sizes, there are many instances of flourishing OSS communities with diverse user bases and a wide array of contributors. The varying levels of success among public administrations in fostering OSS communities raises questions about the factors that determine their sustainability.
Recognising the different experiences of public administrations in adopting and maintaining OSS and building on the belief that the sustainability of open source projects relies heavily on the communities around them, the European Commission’s Open Source Observatory (OSOR) has put together dedicated Guidelines for Sustainable Open Source Communities in the Public Sector. The purpose of the Guidelines is to debunk the myth that working with OSS is challenging, resource intense, and requires domain-specific knowledge. They aim to demonstrate that there are different ways to launch an OSS project and a community around it within a public administration and to guide readers through this process. Whilst many guidelines on OSS community-building exist, such as the Linux\(^1\) or GitHub\(^2\) Open Source Guides, there is a gap to fill when it comes to the sustainable OSS community-building in the public sector.
The Guidelines for Sustainable Open Source Communities in the Public Sector are for civil servants at all administrative levels, project managers, IT developers, and OSS enthusiasts looking to start or participate in an OSS project or for individuals who are simply curious about what such an endeavour might entail.
The Guidelines are based on the assumption that public administrations should not merely reuse OSS (i.e. be consumers) but rather be active members and contributors to the communities that exist around this software.
The Guidelines were put together following research consisting of a literature review, a dedicated survey, and five case studies on the following sustainable OSS communities in the public sector: the Integreat software developed outside the public sector and used by German municipalities; the use of the CONSUL platform by the Groningen municipality in the Netherlands; Lutece
---
\(^1\) Available at: [https://www.linuxfoundation.org/resources/open-source-guides/](https://www.linuxfoundation.org/resources/open-source-guides/)
\(^2\) Available at: [https://opensource.guide/](https://opensource.guide/)
Guidelines for Sustainable Open Source Communities in the Public Sector
software developed by the City of Paris; the Developers Italia community launched by the Italian government; and the geospatial OSKARI software developed in Finland.
**Figure 1** Case studies on the sustainability of open source communities
<table>
<thead>
<tr>
<th>Developer Italia</th>
<th>Integreat</th>
<th>Lutece</th>
<th>Oskari</th>
<th>Voice of Groningen</th>
</tr>
</thead>
<tbody>
<tr>
<td>Launched in 2017 by the Agency for Digital Italy, Developers Italia is a vibrant community made up of citizens, civil servants, public administrations, and enterprises. Community members meet on this online platform and discuss ongoing or future projects, share ideas, and upload source code.</td>
<td>Launched in 2015 by a group of students, Integreat is an open source digital integration platform aiming to reduce information poverty for new arrivals in and within Germany. The Integreat platform is now used by over 60 German municipalities</td>
<td>Lutece, launched in 2001, is an initiative of the City of Paris aiming to supply each Parisian district with a tailored Content Management System tool to manage their own website. It is a portal engine allowing users to create a dynamic website, which can be tailored to users’ needs with additional modules and features.</td>
<td>Oskari is an open source software designed as a framework that can be used to easily build web mapping applications, showcase geospatial data, and analyse such data. Its distributed Spatial Data Infrastructures enable public administrations and other bodies to share their spatial data and work collaboratively.</td>
<td>In 2019, the City of Groningen started a new participatory democracy project following the successful launch of the Voice of Groningen platform, based on the open source software CONSUL. The new project aims to give citizens more decision-making power in relation to their locality.</td>
</tr>
</tbody>
</table>
The research methods used to produce the Guidelines are briefly described in the Methodological Note chapter and the research results are available in an analysis document, *Key Success Factors of Sustainable Open Source Communities* published on the OSOR Knowledge Centre.
There are two general approaches that public administrations can take to engage with OSS. They can either join an existing OSS community or create one from scratch. In both cases, it is crucial for public administrations to address some key questions internally before deciding on how to best engage in or launch a public sector OSS community. Therefore, the Guidelines consist of the following three key chapters:
1. **Setting the foundation for sustainable open source engagements** – detailing the type of questions that should be addressed within public administrations before committing to an OSS engagement and outlining the two main approaches one can take to achieve this goal.
2. **Joining an existing community** – describing the sustainable way to join an existing OSS community and reuse its software if the software meets a public administration’s needs.
3. **Building your own public sector OSS community** – a detailed breakdown of the steps that should be taken and questions that need to be answered to build a sustainable OSS public sector community.
The Guidelines have been designed with a user-centric approach so that readers can easily understand the key aspects of engaging with OSS in public administrations, either by launching a new OSS community or by joining an existing one. For this reason, the Guidelines follow a Q&A structure, posing and answering the most pertinent questions associated with the sustainability of OSS in the public sector.
The Guidelines are part of the European Commission’s work – under the Sharing and Reuse Action[^3] – to promote the sharing and reuse of IT solutions within public administrations.
## Terms and Definitions
<table>
<thead>
<tr>
<th>TERM</th>
<th>DEFINITION</th>
</tr>
</thead>
<tbody>
<tr>
<td>Fork</td>
<td>Creating a “fork” is producing a personal copy of someone else’s project. Forks act as a bridge between the original repository and a personal copy.</td>
</tr>
<tr>
<td>Open source community</td>
<td>A group of individuals who work together to develop, test, or modify open source software products.</td>
</tr>
<tr>
<td>Open source engagement</td>
<td>An organisation’s commitment to engage with open source software either by launching an OSS community from scratch or joining an existing community and contributing to it instead.</td>
</tr>
<tr>
<td>Open source project</td>
<td>A specific project for which the source code is available to everyone to contribute to and reuse, as defined by the open license used for the project.</td>
</tr>
<tr>
<td>Open source software (OSS)</td>
<td>Software for which the original source code is made freely available and may be redistributed and modified.</td>
</tr>
<tr>
<td>Proprietary software</td>
<td>Occasionally referred to as closed source software, proprietary software is software that legally remains the property of the organisation, group, or individual who created it. The organisation that owns the rights to the product usually does not release the source code and may insist that only those who have purchased a special licence key can use it.</td>
</tr>
<tr>
<td>Software as a Service (SaaS)</td>
<td>A software licensing model in which access to the software is provided on subscription basis, with the software being located on external servers rather than on in house servers. Software-as-a-Service is typically accessed through a web browser, with users logging into the system using a username and password. Instead of each user having to install the software on their computer, the user is able to access the program via the internet.</td>
</tr>
</tbody>
</table>
---
5. IGI Global, “What is Open Source Community”. More information: [https://www.igi-global.com/dictionary/collaborative-development-environments/](https://www.igi-global.com/dictionary/collaborative-development-environments/)
7. BBC, “Software concepts”. More information: [https://www.bbc.co.uk/bitesize/guides/z6r86sg/revision/4](https://www.bbc.co.uk/bitesize/guides/z6r86sg/revision/4)
<table>
<thead>
<tr>
<th>TERM</th>
<th>DEFINITION</th>
</tr>
</thead>
<tbody>
<tr>
<td>Total cost of ownership (TCO)</td>
<td>A financial estimate aimed at calculating the short- and long-term costs of any product or service by taking into account the complete costs. For IT, TCO includes hardware and software acquisition, management and support, communications, end-user expenses and the opportunity cost of downtime, training and other productivity losses.</td>
</tr>
<tr>
<td>Vendor lock-in</td>
<td>A situation whereby a customer becomes dependent on a product or service provided by a commercial supplier and cannot move to another vendor without substantial costs and/or inconvenience.</td>
</tr>
</tbody>
</table>
---
10 The LINUX information project, "Vendor Lock-In Definition". More information: [http://www.linfo.org/vendor_lockin.html](http://www.linfo.org/vendor_lockin.html)
1
Setting the foundation for sustainable open source engagements
1. Setting the foundation for sustainable open source engagements
When considering starting an open source engagement, public administrations are faced with two key choices: join an existing community or create a new one. Before deciding, there are several elements to consider. In this chapter, we review the criteria to help guide you through making this choice. We also outline some crucial elements that can help to ensure your engagement’s long-term sustainability such as well-defined funding and internal support.
1.1 Assess your needs & capabilities
Before you engage with a specific OSS community or embark upon building your own, there are several aspects to consider. Firstly, you should carefully evaluate your software needs and identify whether they are unique to the public administration alone or whether there are other potential software partners with similar needs. Secondly, you should assess the IT capabilities of your public administration and, in turn, scan the OSS market to see whether a solution that meets your needs already exists.
What kind of software are we looking for?
Organisations’ software needs must be assessed prior to engaging with any OSS. Your public administration might need various types of software, such as an operating system, word processors, database management, an intranet portal, or a specific application, to cover different business processes. Having a clear understanding of your software needs will make it easier to look for existing solutions on the market.
Another key element to keep in mind is the interoperability of the software. Your new open source engagement cannot inhibit the upgrade path for related legacy IT systems, and it needs to be compatible with the infrastructure already in place within your public administration. That is why the license of the open source software that you develop or decide to reuse has to be compatible with the existing IT infrastructure at your administration. This will increase the sustainability of your OSS venture.
You should assess the most important functional aspects that you are looking for in a solution. This will help you better understand the efforts that would be required to maintain and develop the software. By doing so, you will have a clear idea of the short-, mid-, and long-term goals you wish to achieve, and you will be prepared for the agile needs of the public sector.
Finally, there are some non-functional aspects of the software to consider. You should take into account the security requirements of the planned OSS engagement, as this might potentially restrict the range of software your administration can reuse. It is also beneficial to assess the software’s targeted user base, consider its scalability in the future, and understand the resources that need to be allocated for software maintenance, among other things. Figure 2 below summarises these considerations.

The European Commission, under the ISA2 programme, has developed some tools that can support you in this process. For example, PM² is a project management methodology designed specifically for managing projects in public administrations. Additionally, Interoperability Maturity Assessment of a Public Service (IMAPS) is a self-assessment tool aimed at helping public administrations to assess the interoperability of a new solution under development. Finally, Common Assessment Method on Standards and Specifications (CAMMS) helps public administrations to select appropriate standards and specifications for their solutions.
What are the IT capabilities available at our public administration?
The type of OSS engagement that your public administration will choose is largely dependent on its IT capabilities. If there is a dedicated in-house developer team, then it is very likely that the public administration will be in a good position to host existing OSS or even develop the software from scratch. This is more likely to be the case in large, centralised administrations such as ministries or agencies.
When it comes to smaller public administrations, there might not be an in-house developer team or civil servants with a high level of IT knowledge. In this case, you might consider joining an existing OSS community with vendors offering tailored versions of the software (i.e. vendors who provide Software as a Service).
However, even if your public administration does not have in-house IT support, you could consider developing such capabilities, be it on a small scale over time. This will give the public administration more autonomy over the software development. Alternatively, you could procure civil society organisations or SMEs to develop the open source solution while making sure that you also build the community around it.
Is there an existing open source solution that meets our needs?
Having assessed the software needs of your public administration as well as your IT capabilities, you should then conduct some in-depth research to analyse if any software that matches your needs already exists. This can be done in several ways.
A good place to start is to check whether your central government has published a dedicated catalogue or repository of available solutions for reuse. Alternatively, you can take a look at catalogues or repositories produced by other governments. This way, you can save valuable public resources and reuse software supported by public administrations.
Bear in mind that an open source solution existing on the market does not need to fully meet the requirements of your public administration in order to be considered. If, having assessed the available software, you believe that additional features that suit your needs could be developed as add-ons, then the software could indeed be reused by your public administration.
However, if the core software itself must be modified, it is preferable to work with the OSS community or a vendor that develops the solution in order to add your required features to the core. This is because making local changes to any open source community-driven project brings its own risks. The adapted fork\(^{11}\) that you produce would have to be updated by your public administration alone as the community surrounding the software will continue to work on the original branch, rather than the fork that you developed. Updates and maintenance needs must then be met in-house as any forked project will need to be sustained over time. Working with the OSS community is generally a more sustainable option than forking.
However, if having assessed the software landscape, you fail to identify a suitable solution, it is worthwhile considering launching your own OSS community and developing a new solution. Where possible, this should be done in collaboration with other public administrations. This will help you to mitigate the risk of having a low number of contributions. As mentioned above, the development of such a solution does not necessarily have to be done in-house. Together with other public administrations, you could hire an IT company to develop the open source solution for you. Your responsibility would then be to grow the community around the software within the public administration.
---
11 Please refer to Terms and Definitions section for a definition of this term.
Could other public administrations partner with us for this project?
Public administrations within a country tend to share the same culture and have similar government institutions. Therefore, they are likely to have similar IT needs. Before you procure or develop software, you should check whether other public administrations at the national, regional, or local levels might want to collaborate. It may be helpful to reach out to public administrations of the same type – i.e. another municipality, public institution, or a ministry.
Identifying potential synergies with other public administrations will facilitate the pooling of resources and exchanging lessons learnt and best practices when it comes to working on the software together. You can also look outside your own country for software that could be adapted to your needs. Although pooling resources requires more coordination efforts, the benefits of such collaboration will outweigh the costs in the long run. Working with universities is another great way to pool resources, generate ideas, and gather OSS expertise.
1.2 Embed your community within the public administration – make it ‘official’
Once your team has selected the most suitable way to engage in a public sector OSS project, the next key step is to formalise this engagement within your public administration.
Which key public administration actors do we need to onboard to kick-start the community?
Political support is a strong enabler of sustainable OSS communities in the public sector\footnote{Our research shows that having political support for any type of OSS project is a pre-requisite for a sustainable public sector OSS project. More specifically, 62\% of our survey respondents believe the support of the political level is a ‘very important’ factor in the sustainability of any community.}. One of the reasons why political support is crucial is the hierarchical decision-making structure found in public administrations. Even if you have the IT personnel and mid-level management on board, the initiative might struggle to take off without the approval of the political layer. Open source efforts risk being abandoned if there is no true buy-in from an organisation’s political leadership\footnote{According to our survey respondents.}. Furthermore, the initial period of building a new OSS project and community around it might bring its own challenges. Hence, having political and managerial support might be helpful to keep the momentum going.
OSS community leaders and members play an important role as advocates of their project in the public administration. They should invest resources in demonstrating the benefits of using OSS, which can help them gain in political support within their public administration.
How do we formalise our community within the public administration?
In order to ensure the longevity of a public sector OSS community, it is crucial to formalise the community within the public administration, rather than view it as an ad hoc engagement.
This means giving it status, a clear name, choosing a project manager and a dedicated team, and securing the budget (described in more details below).
This will make it easier to lock in dedicated resources. The time that community contributors spend fostering the community and/or working on the OSS project should be officially recognised as part of their work duties rather than as a voluntary engagement. Official recognition of the community improves its long-term sustainability as the community becomes part of the administration’s strategic planning. This protects the community against any short-term shifts in public administration’s political focus or priorities.
1.3 Secure project and community funding
The final crucial aspect of getting your community off the ground is securing funding. There are several factors to consider when assessing your funding needs and securing resources for it.
What elements should we consider when defining the budget for an OSS project and the community around it?
In order to secure a sufficient budget for the OSS project and the community around it, you should evaluate the ex-ante costs associated with it. This involves considering the Total Cost of Ownership (TCO) in order to help you better understand the project’s long-term costs. Some of the costs to be considered include:
- initial hiring of IT staff;
- exit costs for existing software being used;
- development or implementation of the new software;
- staff training, if any, on working with the new software;
- maintaining the software;
- developing the community;
- managing the community.
In addition to assessing the TCO of your project, you could also develop a business case demonstrating the long-term benefits of your OSS community to help secure managerial and political support for it.
Young public sector OSS communities sometimes underappreciate the importance of dedicating resources to software maintenance and ensuring community vibrancy (community management). A budget should be allocated in order to nurture the community itself (developing the community) by investing in community events, such as hackathons, physical meetups, or online gatherings where members can exchange feedback, lessons learnt, and future ideas.
**Figure 3 Key elements to consider when assessing Total Cost of Ownership**
**How do we secure project and community funding?**
A clearly defined budget is crucial for any public sector initiative. Our research clearly shows the importance of having sufficient funds to develop the core aspects of a community and its associated software. Therefore, public administrations should dedicate a portion of their annual budget to launch their OSS project and to help maintain the associated community. It can be complemented by additional funds from other organisations interested in participating.
For administrations with constrained budgets, there is an option to consider: co-funding. It refers to the involvement of one or more organisations willing to contribute financial support for software development to supplement funding provided by the public administration. This arrangement may also result in public-private partnerships.
---
**The nine main public administrations involved in the use and development of the Finnish OSKARI geospatial software each contribute a yearly fee of € 5 000 for the development of the platform.**
---
14 54% of our survey respondents consider a clearly defined budget as a ‘very important’ or an ‘important’ sustainability factor.
If you decide to engage with OSS by joining an existing community, one way to support it is through *crowdfunding*, which refers to the raising of funds from a wide range of donors, usually through a dedicated platform. Some communities choose this option to fund the development of specific software components or to receive financial support for the growth of the community. If the community of your choice is open to crowdfunding, there is a variety of platforms that it may select for this purpose. Bear in mind that any public sector organisation interested in crowdfunding should first check if it is compliant with existing policy and national legal frameworks.
**Should we consider hiring additional resources?**
Before diving into a new OSS project, you need to assess whether additional resources are required to guarantee its smooth implementation. Whilst contributions to OSS are largely driven by members’ commitment to collaborative open source values, public sector OSS communities need certainty and structure to ensure their longevity.
If there is a need for additional community contributors, it is worthwhile to *invest resources in hiring developers* to implement, maintain and provide support for your software. This will help to maintain the project’s quality and usefulness in the long run. It is also a great opportunity to make skilled IT professionals a part of your public administration, thus providing support and encouragement for new community members and users with less IT knowledge.
Public administration community managers and members might have parallel commitments and hence, might not be available to focus on the OSS full time. Hiring individual developers can help to ensure that the software is regularly maintained. Nevertheless, this is not to say that the project management should be outsourced to these contributors. Public administration community managers should be empowered to dedicate time to the community and its growth, even if they have parallel commitments.
Similarly, rather than hiring full-time developers, it might be worth launching a *public tender calling for developers* to work on certain aspects of the OSS project. This will help to ensure continuous developer commitment to the project, and it is also an effective way to produce initial project output.
**How should we approach private sector contributions?**
OSS communities often benefit from private sector’s financial contributions from the private sector. However, when it comes to private sector involvement, especially from large organisations, the support should not manifest itself in indirect control of the community and its outputs.
---
15 Hiring developers was seen as a ‘very important’ factor by 47% and as an ‘important’ factor by 22% of our survey respondents.
This also holds true for OSS initiatives in the public sector.
The public sector should retain the steering role of the community while private sector contributions should take the form of providing additional support and advice, when necessary. Generally, it is advisable to allow private sector contributions when the community is more mature. Particular attention should be paid to the transparency of the community’s governance model and to ensuring that engagement with the private sector does not compromise this model.
2
Joining an existing community
2. Joining an existing community
After assessing your needs and IT capabilities and evaluating the open source solution market, there are a few elements that you will need to consider if you decide to join an existing open source community. The list below will help to guide you and ensure that, having selected the community you want to engage with, you establish sustainable long-term collaboration.
2.1 Understand the community behind the software
Before joining an existing open source community and reusing its software, there are several questions that you should ask yourself in order to fully understand its nature and how you can best contribute.
What is the setup of the community we are joining?
To find a community that will match your organisation, you need to consider its setup and governance. Identifying the governance model, the community’s communication channels, its manager, and consulting the code of conduct are good elements to start with, as outlined in Figure 4 below.
A clear understanding of the community’s governance model of the community is key to your future contribution. Put simply, the governance of the community should be compatible with the processes in your public administration or at least compatible enough that your public administration can adapt to the processes within the community and ensure its smooth cooperation.
Although each open source community is slightly different, the main types of governance models are as follows:
- **Founder-led**: a type of OSS community where a single person, normally the founder of the community, is in charge of making all the key decisions with regard to the evolution of the project. Such a governance type can often be found in smaller organisations and young OSS communities with only a few contributors. As the project evolves, the single decision-maker can also be replaced by a steering committee.
---
16 Our survey highlighted the importance of having a clear governance structure. Indeed, survey respondents underlined the importance of having a clear leadership structure (74% of respondents) and clearly defined roles and responsibilities (76% of respondents).
17 Taken and adapted from: [Open Source Leadership and Governance Guide](#) and [Red Hat’s Guide to open source project governance models](#).
Guidelines for Sustainable Open Source Communities in the Public Sector
- **Merit-based**: a community where responsibilities are assigned based on merit, i.e. developers’ commitment and contributions to the project. In such communities, decisions can also be driven by voting to ensure member-driven project evolution.
- **Member-driven**: a community without a strict or formal governance model, where contributions are made by individual members and the evolution of the project is driven by consensus-building among community members with varying degrees of influence. Usually, the governance of such projects is implicit, and it might be difficult for new joiners to grasp.
Each governance type comes with its own benefits and drawbacks, and it is not unusual for a community to adapt its governance structure as it evolves.
You will need to identify a future **point of contact** in the community, and assign a point of contact within your own organisation. This will ease your onboarding in the community and allow you to get more information on the project. Similarly, understanding the community’s communication channels will help your team to stay on top of any community updates and easily collaborate with key members.
You should also check the community’s **code of conduct** to see if it is aligned with your own needs and public administration’s values.
**Figure 4 Understanding existing communities**
**GOVERNANCE MODEL**
Have a clear understanding of the existing hierarchy in the community
**COMMUNICATION**
Identify the community’s communication channels
**POINT OF CONTACT**
Identify your future point of contact in the community
**CODE OF CONDUCT**
Make sure the values of your organisation are aligned with the ones of the community
**How mature is the community we are joining?**
The maturity of the community will affect how you collaborate with it. The following criteria that may help you gauge the maturity of a particular community:
- size of its developer community
- size of its user base
Guidelines for Sustainable Open Source Communities in the Public Sector
- number of recent commits to the code
- sustainability and diversity of its funding model
- frequency of update releases
- date of last update.
If the community that you wish to join was only created recently, you will be in a better position to help shape the functioning of the community and to establish yourself as a key player regarding decisions about the core features of the solution. Smaller and newer communities also allow you more flexibility when collaborating with other community members as rules and practices are typically quite new. However, ‘young’ communities might require the mobilisation of more financial and human resources in order to kick-start their growth.
If the community you join is large and mature, you will benefit from extensive existing content. Most probably, the OSS will already be at a mature stage of code development and some contributors may have developed substantial forks and plug-ins that are worth consulting. It might also offer capabilities to host the software you need on their own platform. However, individuals involved in the community will have reduced influence over the direction of the community and the OSS product itself.
To conclude, the choice of open source community depends on your financial and technical resources, as well as the type of software you are looking for. In both cases, you should pay attention to the interoperability of this solution with the software already in use in your organisation.
How can we make the most of the OSS community behind the software?
If you have decided to use an open source solution, it is best to fully exploit its potential. Unlike proprietary solutions, open source solutions benefit from a community of developers around them who fix bugs, develop new features and plugins, and contribute to the code. Below are some tips on how to make the most of the open source community behind your software:
- **Interact with the community** if you have questions about the installation or use of the software.
- **Contribute** to the community by developing code, contributing to or creating documentation, and resolving issues.
- **Have a look at other public organisations** using the same software. Their variation of the software can provide inspiration for your own version.
- Make sure that citizens are aware that the software your organisation is using is open source. Not only is it a guarantee of transparency, it also gives **visibility** to the community and to the OSS solution. This way, your organisation is contributing to the sustainability of the open source community.
In order to make the most of the open source solution, it is important to not only receive from the community, but also to contribute to the sustainability of the solution. Should your organisation develop plugins, write documentation or create additional features around the software, these elements should be published under an open source licence, preferably the same as the solution itself, and shared with the upstream community.
### 2.2 Facilitate sustainable collaboration
There are several steps that you can take to ensure that your public administration will reap the full benefits of collaborating with an OSS community.
**How can we adapt our procurement rules and processes to work with OSS communities?**
Appropriate procurement procedures and rules are a prerequisite to healthy collaboration with OSS communities. Public procurement templates should have clear and permissive clauses on purchasing open source solutions. The templates should also allow civil servants not to only purchase OSS solutions but also engage with the community surrounding the software. Public administrations are encouraged to maintain lists of compatible OSS licenses, and those should also be specified in public procurement templates when purchasing software. Check whether your country has guidelines on public procurement and open source solutions.
The Italian government has dedicated Guidelines on the acquisition and reuse of software for public administrations, which are legally binding.
The Linux foundation has published a guide on open source software for procurement professionals, which addresses the key questions on this topic.
**How to best implement open source software?**
Once your organisation has chosen the open source solution, you need to decide whether you will be running the software in your own premises, relying on the upstream community to host it for you, or modifying the source code altogether and tailoring it to your own needs.
**Relying on an existing software version** is a good way to start your open source project while minimising financial and technical outputs for your public administration. Hence, you might want to choose this option if you have limited IT resources and the existing solution is strongly aligned to your needs.
**Creating add-ons and plug-ins** is useful when you want to add tailored features to the existing software. However, you should follow the open source industry best practices and share your changes with the upstream community. If the changes are important and relevant to the broader community, they can potentially be included in the upcoming software release.
Contributing upstream is an crucial aspect of giving back to the community as code-sharing is one of the key values of OSS.
What are the strengths that we can offer to the community?
When choosing to join a community, you should assess what kind of contribution you are willing to make. The potential resources you can mobilise include:
- financial resources;
- human resources, both in terms of technical human resources such as developers, and supporting human resources such as project managers, community managers and communication specialists;
- technical knowledge and resources, assuming that your organisation has the capacity to create content for the open source solution that could be shared with the community;
- leverage of your public administration's involvement with the community so as to attract other public administrations, thus helping the community to grow.
Contributing to the open source project helps your public administration to gain substantial respect within the open source community, which in turn can expedite your transition from a minor community player to a core decision-maker. Decision-making control is beneficial because it will allow your public administration to direct the trajectory of the open source project in line with your own needs.
2.3 Contribute to the solution in the long run
Joining an OSS community is not a one-off engagement. For a more complete view of your potential contribution, assess your capabilities and resources in the short-, medium-, and long-term. An honest and representative assessment will prevent you from over-committing beyond your capabilities.
Your public administration will have to find ways to contribute, collaborate and give back to the community in the long run. Collaboration is one of the key principles behind the success of OSS.
**How can we promote the solution in other public administrations to help grow the community?**
Growth is crucial to any community’s sustainability\(^{18}\). Therefore, as a public sector community representative, you can help to expand the community’s user base. If you happen to know a public administration like yours that could be interested in the open source solution, share your documentation. You can also plan to **pool your resources** with several other public bodies to promote a solution. This strategy is particularly useful for small public entities which, taken alone, often do not have the financial or technical resources for a long-term involvement in an open source community. This will allow you to build expertise across public administrations that can then train, implement and offer policy suggestions to other public bodies.
**How can we contribute to the visibility of the community?**
Contributing to the visibility of the OSS community is essential to its sustainability\(^{19}\). Without visibility, the open source community is unlikely to attract new members, thus putting the long-term maintenance of the solution at risk. Public organisations using open source solutions should therefore market the community and the software behind it, allowing viewers to access the software’s repository.
Your organisation can also **communicate actively** about the community. We encourage the development of a dedicated online space for the solution that your organisation plans to use. It is worth outlining the software’s open source characteristics and providing a brief explanation text about the solution and the community behind it if the website is addressed to the wider public.
\(^{18}\) 45% of our survey respondents deem a community’s capacity to attract new members as a ‘very important’ or ‘important’ sustainability factor.
\(^{19}\) 64% of our survey respondents highlighted the importance of communication in the sustainability of an open source project.
Building your own public sector OSS community
3. Building your own public sector OSS community
If you have decided to create a new open source community, this section will explore the key issues that you may encounter and how to overcome them. In the first few months, you will likely have to make several important decisions that will impact the sustainability of your community. Such decisions should be made with a long-term perspective, all the while accounting for the future maintenance of your software.
3.1 Operating within your public administration
Given that the OSS community is to be launched within a public administration, the nature and operation of the community will inherently be affected by the public administration's ways of working. Therefore, to ensure that the community is well positioned and recognised within the public administration, it is recommended that you promote the community and inform your colleagues about the benefits of and ways of working with OSS.
How to establish collaboration between an OSS community and the public administration it is attached to?
Building relationships outside your community will help to boost its recognition. Contributions and resources dedicated to your OSS community have to be recognised and valued by the management and employees. This can only happen if other civil servants outside the community understand what working on an open source solution entails.
The benefits of the new OSS community should be demonstrated to your peers, management, and the decision-makers of your organisation as early as possible. This could be done by sharing weekly or monthly reports about the recent developments and code contributions to the software. Another good way to showcase your project’s growth over time is to define some metrics against which you could assess your community.
For inspiration, you can consult the CHA OSS Community Health Metrics.
It is also important that the hierarchy of your public administration understands the collaborative nature of OSS communities. This will help safeguard the horizontal and transparent ways of working in the community. Furthermore, public sector managers should appreciate the fact that software development is a continuous process that might require several iterations, tests and release cycles before the final product is put together. Even then, software updates and new add-ons are regularly released. OSS communities are not static and there is no end-goal per se. As long as the software is used, the open source community behind it will be needed to publish updates and respond to user requests.
To better position your OSS projects within the public administration, you may consider setting up an Open Source Program Office (OSPO). OSPO’s responsibilities will vary depending on the size of your organisation and its OSS engagement scale. Its main mission is, however, to nurture and support the open source approach to software development and engage with developer communities. The European Commission, in its renewed open source software strategy, has established an OSPO and tasked it with facilitating all activities outlined in the strategy.
How can we ensure the community’s growth within our public administration?
As your community will be set up within a public administration, you should work to ensure that its decision-making process does not slow down your community’s growth. Raising awareness of OSS benefits and your community among civil servants and the political hierarchy will encourage openness in your public administration with regard to fostering the growth of an OSS community. You should highlight the fact that OSS helps to prevent vendor lock-in and ensures your administration’s digital sovereignty. You could invite your colleagues to contribute to community forums, participate in any online or physical events and encourage them to meet community members to better understand the nature of OSS communities.
Bearing in mind that public administrations are hierarchical, which stands in contrast to the the horizontal communal nature of OSS projects, launching and growing your community may take patience and determination. The decision-making process within public administrations depends on long-term planning and budget cycles, which in turn depend on the political priorities at the time. Nevertheless, the OSS communities that we have studied all demonstrated flexibility and agility to work with and within public administrations.
Who can become our community’s members?
A public sector open source community should always arise from the needs of the public administration. However, just because the project is created and funded by a public administration, it does not imply that the community cannot evolve beyond the frame of a single public organisation or branch out to other users. In fact, our research shows that an increase in the number of actors involved in the community as active contributors strengthens its sustainability.²⁰
3.2 Focus on the software
The maturity of the community’s software is crucial for the community’s sustainability as it is the foundation on which the community is built. There are several elements that you need to consider when releasing and maintaining the community’s code.
How can we choose the right license?
Choosing the appropriate license allows the software to gain visibility. It is also a guarantee for all actors involved in the project that the source code will benefit the open source community. It is good practice to choose an open source license recognised by the Open Source Initiative (OSI). Furthermore, it is recommended to choose a license commonly used in the programming language or framework ecosystem that your project will build upon. This will ensure continued participation from outsiders and lead to a more sustainable community.
Some tools that can help you in the process of identifying the right license include Joinup Licensing Assistant and Choose A License.
Additionally, open source communities need to check whether the country where the project is taking place has requirements regarding the licensing of open source solutions by the public administrations. For example, in France, public administrations are obligated to publish their source code under an open license listed by the Decree, and in Spain, public administrations should follow the Guidelines on the Publication and Licensing of Assets, that explain how to publish and distribute open source software.
²⁰ According to our survey respondents, the community’s capacity to attract new members and retain current members are key sustainability factors, deemed as ‘very important’ by 46% and 53% of our survey respondents respectively.
Which programming language should we choose?
The choice of the programming language is another key element of an open source project. It depends on the nature of the software, but whenever possible, you should choose a well-known language to allow more developers to contribute to the project and foster its reusability.
How should we approach software releases?
Having an overview of your planned product releases, as is the case with proprietary software, helps to add structure to your project. A project roadmap will be a helpful way for your team to plan the key milestones associated with your software’s development. When it comes to OSS, new software releases often happen in 3- or 6-month cycles.
Additionally, planned software releases should be announced in advance. This will create anticipation, boost your community’s visibility and help the community to prepare for the new release. More specifically, having a clear idea of the next version release will allow community members to anticipate potential new bug fixes, plan training sessions, and to set expectations for their workflow.
How should we ensure code quality?
Prioritising quality over quantity with regard to the development of the source code is a key element of an open source project’s sustainability. To ensure that the source code meets high quality standards, open source communities need to put testability mechanisms in place and foster peer-review processes. Giving more responsibilities to individual members of the community can also motivate them to keep the highest standard of code quality without relying too much on the community's code testing capacities.
Furthermore, to maintain the long-term software quality, you need to carefully evaluate (and not underestimate) the workload required to keep the software updated, fix bugs and respond to users’ queries. In many cases, software maintenance is a full-time job.
What should we do regarding software documentation?
Well-documented software makes it easier to onboard new members and foster software reusability.21
For more information on how to write software documentation, you can consult advice published by the Write the Docs community. Additionally, the Foundation for Public Code outlined suggested requirements for documenting software developed by public administrations.
21 61% of our survey respondents consider that documentation is an important element of the sustainability of the open source project. Some of our interviewees even believe that 50% of developers’ time should be dedicated to documentation.
**Does our software have to meet GDPR requirements?**
When building an open source solution for a public administration, keep in mind the specific requirements that it entails. Lack of compliance with the requirements of the General Data Protection Regulation (GDPR) is an obstacle to the use of some software. Open source communities need to make sure that their software is GDPR-compliant and that information about its compliance is easily accessible to external users. It is also worth checking whether the software that your public administration is developing must meet any national requirements or regulations.
**How do we make the software accessible?**
It is equally important to ensure that your software meets the EU and international standards for accessibility. The European Commission’s Web Accessibility Directive, in force since 22 December 2016, lays down the standards and procedures associated with ensuring the accessibility of European websites and mobile apps of public services.
Additionally, the W3C has put together a detailed guide on Accessibility, including international accessibility principles.
**When to make the source code available?**
It is good practice to make the code publicly available from the project’s inception, starting with the very first line of code. This way, more developers are encouraged to join the community. Waiting too long before publishing the source code not only results in fewer developers being involved but also contradicts one of the core principles of open source – making the source code available.
In addition to publishing software, you should maintain and keep it up to date. Ideally, the public software repository should be the main ‘working’ software repository used by the project team and the community.
The UK Government has put together a dedicated guidance explaining the value and process of making source code open from the start.
**3.3 Organise the community**
Organising OSS communities helps to guarantee their smooth operation. Given the hierarchical nature of the public sector, organising the community becomes especially important in demonstrating a project’s success and sustainability. Clear governance and operational guidance should be agreed upon with the community so it can operate and grow freely.
How should the decision-making structure of the community be set up?
The sustainability of any open source community depends on strong leadership and open management. Community governance, set up transparently, should strike the right balance between openness and the organisational structure of the public administration\textsuperscript{22}.
- **Identifiable public sector manager**: The role of public sector manager(s) is to enable flexible and transparent modes of operation for the community. Any decisions taken by public sector management should be clearly reported back to the community along with justifications for such decisions. Considering the openness of open source communities, public sector manager(s) should consult with community members as frequently as possible to ensure that the community is truly member-driven. This will also help to strengthen members’ motivation to contribute to the community and its project(s)\textsuperscript{23}.
- **Project manager / steering committee**: The project manager or steering committee should demonstrate a strong understanding of OSS and the nature of the community as well as knowledge of public sector operations. This will allow them to act as facilitators between the community and the public administration within which it operates. Additionally, the project management team should include the project’s key developers as they have the most specialised knowledge of the software.
For the sake of long-term sustainability, the community’s management should also take into account potential changes to the roles in the community. You should facilitate the organic growth of the community members’ responsibilities and envisage potential replacements of managers if they are no longer available to steer the community. Resources should also be dedicated to training future community leaders - a strong team behind the community is crucial for its sustainability.
A key part of your community is to have a core team. These are members who make daily contributions to your software, interact with the broader community, and are responsible for making decisions for certain subsets of your community. More often than not, some core team members are also part of the project management team as they tend to have the strongest knowledge of the long-term evolution of the open source software and the community.
Finally, users of your open source solution are another key community group as they share valuable feedback on the new releases. However, this group and the contributors can be viewed as being at the periphery of your community. Unlike the core group, they are more likely to
\textsuperscript{22} Our research shows transparency of the decision-making hierarchy to be a factor strongly influencing OSS contributors’ motivation.
\textsuperscript{23} 43% of our survey respondents view the presence of coordination mechanisms among community members as a very important factor to its sustainability.
switch to other software and be less committed to your project in the long run.
These key community layers are summarised in Figure 5 below.
**Figure 5 High Level Organisation of OSS communities**
What are some key roles & responsibilities that should be fulfilled in the community?
For your community to function smoothly, your core community members should fulfil several different roles. Even though there are many types of open source communities, below are some of the key roles that can be found in most communities, as additionally summarised in Figure 6:
- **Management** – the key person(s) responsible for the community and taking decisions on features, releases, and other activities as well as acting as a bridge between the community and the public administrations’ political hierarchy.
- **Core Technical Committee** – a technical management team that is highly committed and is responsible for verifying and approving proposed changes to the code and making the final decisions regarding the project’s evolution together with the project leader(s).
- **Maintainers** – members of the community responsible for maintaining and managing certain aspects of the project (e.g. security). Community members who have a strong sense of responsibility and direction are best positioned to be community maintainers.
- **Committers** – community members who have demonstrated dedication to the community and are regular contributors can, with time, be recognised as project committers. They can also be responsible for reviewing new code contributions.
- **Contributors** – any members of the community who participate in forums, comment on issues, organise events and are active in any other way.
Additionally, some members of the core team should also be responsible for promoting the community and be in charge of communication, marketing and social media management.
Figure 6 Community roles & responsibilities
| MANAGEMENT | Person(s) responsible for the project, taking key decisions, as well as acting as a bridge between the community and the public administrations’ political hierarchy. |
| CORE TECHNICAL MANAGEMENT | Responsible for verifying and approving proposed changes to the code and shaping the project’s evolution together with the management team. |
| MAINTAINERS | Members of the community who are responsible for maintaining and managing certain aspects of the project. |
| COMMITTERS | Members who have demonstrated dedication to the community and are regular contributors can be recognised as project committers. |
| CONTRIBUTORS | Any members of the community who participate in forums, comment on particular issues, organise events and are active in any other ways. |
| SUPPORT ACTIVITIES | Very active community members can be in charge of support activities such as communication, marketing, social media management, etc. |
The Linux foundation and GitHub Open Source Guides both outline some of the most commonly found roles within OSS communities.
What organisational information should be made available to the community members?
A community operates best when there are clear roles and responsibilities as well as defined means of operation. However, these aspects need to be agreed upon with and driven by the community. Community members are also encouraged to take up roles and responsibilities voluntarily.
The governance structure of the community itself will largely depend on the type of community being set up. A young community may be self-driven, thus allowing contributions to happen spontaneously. However, setting up your community will require strong efforts in the beginning to structure the team, set goals and milestones and build coordination mechanisms.
Clear Community Vision & Mission
A community is more sustainable if it has a common sense of purpose and a shared identity. For this reason, new and mature communities alike should have clear, publicly available Vision
24 Community’s vision states what the community wants to achieve in the future.
and Mission statements, which will help foster a sense of a community working toward achieving a single goal. They will also help potential new community members to understand the community’s purpose, thus encouraging them to join.
**Community Guidelines**
The rules governing the community should be driven from the bottom-up and agreed with community members. Nevertheless, if you wish to have more formal internal control, the coordination mechanism should not undermine the community’s ability to freely evolve, innovate, and develop. A mature community may, over time, become leaner and more informal.
The best way to set out the community’s operational model is by putting forward Community Guidelines.
They should cover the key elements as follows:
- **Code of Conduct** – outlining the operating principles of the community and expectations for how community members should behave.
- **Roles & Responsibilities** – detailing any specific roles & responsibilities that exist within the community and how community members can get involved.
- **Community’s ways of working and key procedures** – outlining the key processes within the community, such as becoming a community member, contributing code, reporting and fixing bugs, and animating the community.
- **Resources** – detailing any supporting resources available to community members, such as online tutorials, documentation, and online forums.
**FAQ for community members and the general public to consult**
You can host a FAQ on your website or on the development platform that you use for your project. This FAQ may also be divided into two parts: one for contributors and the other for the users of your open source solution.
The FAQ can comprise various sections on general questions, definitions, rules, licencing, documentation, and the communication channel.
---
The City of Helsinki (Finland), for instance, uses GitHub to outline best practices for software development for the city. Developers Italia (Italy) hosts a document website of relevant manuals and documents. Tchap, an instant messaging service used by government officials in France, also hosts an online FAQ.
---
Community’s mission states the purpose of the community.
Overall, 41% of our survey respondents believed community guidelines to be very important and 41% an important factor for sustainability.
How inclusive can we afford to be at the start of the project without losing control of the direction?
Your community should be agile and understand that priorities may need to be redefined at times. The outputs of your community will be based on the current needs of the public sector but may, in the future, require changes and new input that will put other projects on hold. Changes may include adding new features and reworking the code at hand to adapt to these new needs. Your community should thus be prepared for agile methods but you should define a short-, mid-, and long-term vision to achieve the set goals.
Additionally, choosing a few key developers to start developing the software will be useful. You can choose a well-respected figure from the open source world to join the project – even if only temporarily to help secure developers’ initial commitment and contribution to the code.
3.4 Keep the community active
An OSS community is driven by the dedication of its members. Thus, ensuring the community’s health and vibrancy is vital to its longevity.
How to best facilitate communication between community members?
Rapid and transparent communication is key for open source communities, and there are various ways to facilitate it. For example, the community may establish a place for both synchronised and unsynchronised conversations, in the form of live chats and a forum respectively. In addition to informal chatting, a central information hub should also be set up. This can be a wiki, a mailing list, Discord, Slack, GitHub, or GitLab. A single point containing all information will ensure that no important information is lost or scattered across the various channels. Public sector open source projects are encouraged to choose OSS for their means of communication in order to boost their credibility within the community.
Public progress reports highlighting weekly or monthly contributions are also very popular with community members as a means of ensuring transparency within the community. These updates might also be shared with the public administrations’ hierarchy to demonstrate the project’s evolution.
How to sustain the motivation of community members?
Motivation of the community members is a key aspect of the community’s long-term growth and sustainability. If community members do not feel motivated, they are more likely to leave.
There are several ways to maintain the motivation of your community’s members: recognising members’ work, transparent decision-making, and organising meetups.
Recognition of members’ work
Community members are more likely to be motivated and proactively participate in the community if they feel that their contributions are visible and recognised. This, for example, can be facilitated by having weekly overviews of the community’s activities that are shared with the entire community.
Similarly, active community contributors can be rewarded by being assigned more formal and official roles with the community. Such roles and duties include management positions, providing translation services, managing documentation, acting as an organisational integrator, reviewing code, and tracking progress. Allocation of these roles will help to ensure that the community’s management is as horizontal as possible within the framework of a public administration.
Another way to recognise members’ contributions to the community is by introducing gamification elements, such as badges or leader boards, to your community. These might be a fun way to give recognition to and motivate community members. However, before introducing these concepts, assess whether they would be welcome. Some community members might view these changes as fostering competition, rather than collaboration, between members.
Transparent decision-making
Transparent and non-hierarchical decision-making is imperative in ensuring that members feel valued and motivated to participate in the community. Any decisions made regarding the community should be clearly logged and transparent. Community members should also, to the extent possible, be involved in planning the next steps and project releases. An organic community is defined by good coordination and the members working together towards the same goal.
Organising meetups
As much as open source communities’ members mostly interact online, physical community meetups are highly beneficial to the community. While physical meetups should not replace online interactions and hangouts of the community, they might help to add some vibrancy to it. If your budget allows for it, your project would benefit from regular meetups as these are useful to maintain a sense of belonging and foster information exchange. Furthermore, as your community grows, it might also be worthwhile to organise location-specific meetups for, say, different municipalities using your software. If physical gatherings are not possible, organised online meetups may bring similar benefits.
72% of our survey respondents deem the ability to get credit for one’s contribution to an open source community as a ‘very important’ or ‘important’ sustainability factor.
You should be aware that it is natural for community members to leave. Departing members should be quickly replaced with new members so your community grows organically. In other words, a community with a strong core of developers and a large body of peripheral developers with a high turnover is a good indication that your community is doing well.
### 3.5 Grow your community
**How do we ensure the visibility of our community?**
As discussed in section 3.3, some community members need to be dedicated to increasing the visibility of your community. One factor that might help your community be more visible to potential contributors and users is having a dedicated website. It should be easy to access and navigate and provide the most important information about your software. You should use the social media to raise awareness about your software, find like-minded community members, and learn about other ongoing projects.
Furthermore, you should list your software in an existing national catalogue and any other independent catalogues.
**Are there other public administrations that could be interested in joining the community?**
Community growth is an important aspect of any community’s sustainability. It is likely that there might be other public administrations with similar needs that could also benefit from your software.
Therefore, your community should dedicate time and resources to raising its visibility across other public administrations. Your software might be particularly useful to small public entities which, taken alone, do not have the financial or technical resources for long-term involvement in an open source community.
How do we attract new contributors?
There are a multitude of ways to attract new contributors to your community. Most communities collaborate with other public administrations, universities, private developers, private companies and citizens. Once communities reach a mature stage, you should publish clear mission statements and have easily accessible documentation and code. You should also participate in any online or physical gatherings of open source communities. There are many OSS focused events taking place across the globe every single year. Your community could attend EU-funded workshops and conferences, such as the Sharing & Reuse Awards, where you could showcase your project and boost its visibility.
If you have resources to spare, you could take a more pro-active role in attracting new community members. Hosting a hackathon is a great way to involve interested citizens and potential new community members.
Developers Italia organised a 48-hour code sprint throughout Italy and even in San Francisco! They invited programmers, IT professionals, and students to develop functionality for public administration projects hosted by the community.
4
Long-term sustainability
4. Long-term sustainability
If there is one thing that you should take away from these Guidelines, it is that the sustainability of OSS communities is not a one-off investment. Once you either successfully join or launch an OSS community, it is important for your public administration and your steering committee to keep nurturing and growing the community behind your software.
In the long run, your community's sustainability will rely on the following key factors: a clear governance structure, the vibrancy and health of the community, continuous commitment of the public administration's political hierarchy to the project, sustainable funding, and the maturity of your software.
As mentioned throughout the Guidelines, transparency is at the heart of successful open source communities. For this reason, as your community evolves and grows over time, its governance should remain clear and transparent. This will help you to attract new members, make it easier to promote your software, and ensure the commitment of key community contributors.
Secondly, your community is only as strong as its members' commitment to it. Hence, it is imperative that, over time, core team members remain committed to the software and continue contributing code, fixing bugs, and ensuring new software releases. Similarly, it is important to invest resources in raising the community’s visibility so that it can grow over time.
Given that the Guidelines focus on open source communities in public administrations, you need to invest time in guaranteeing the long-term commitment of the public administration to your community. As detailed in the Guidelines, this can be achieved by demonstrating successful project output and providing clear communication on how the community works.
Sustainable funding is essential the community’s growth. It will attract new community developers, and the funds can be invested in new features, used to organise events, and help to raise the community's visibility.
Finally, at the core of OSS communities is the software itself. Your public administration should dedicate resources to maintaining the software over time rather than just investing in its implementation at the beginning.
It is our hope that, with the practical advice and scenarios laid out in the Guidelines, you will have more confidence and a deeper understanding of what it takes to launch a public sector open source project.
5 Methodology
5. Methodological Note
Several research methods were employed to produce the Guidelines for Sustainable Open Source Communities in the Public Sector. More specifically, a three-step approach was taken consisting of a literature review, a dedicated survey of public sector OSS community representatives, and the development of five case studies illustrating sustainable public sector OSS communities. Each step was built upon the main findings from the previous steps. This approach allowed us to put together Guidelines based on both theoretical literature and practical findings from the survey and case studies. The outcome of each step is described in more detail below.
**Step 1 – Literature Review**
The key objective of the literature review was to identify the most recurring success and failure factors of sustainable open source communities. More than 30 information sources were consulted, including academic papers and online resources. The literature review focused on the specificities of open source communities in the public sector as this is the goal of the Guidelines. The outcome of the literature review was a streamlined list of five key success factors that contribute to OSS communities' sustainability: software maturity, sustainable finance, community vibrancy, community governance, and public sector adoption incentives.
**Step 2 – Survey addressed to the open source community**
In order to validate and expand on the findings of the literature review, we launched an online survey targeting members of public sector OSS communities. Between 16 January 2020 and 15 March 2020, the survey gathered a total of 74 complete responses. In addition to gathering feedback on the success factors behind sustainable public sector OSS communities, the survey also helped us to put together a long list of existing communities in public administrations. A total of 46 examples of public sector OSS communities were identified.
**Step 3 – Case Study Analysis**
To further explore what makes public sector OSS communities sustainable, we developed five case studies. They were selected from the list of communities identified in our survey, taking into account their geographical distribution, level of administration, and type of community together with its sustainability. The resulting five case studies were: the Developers Italia community launched by the Italian government; the implementation of participatory democracy through the CONSUL platform in Groningen; the Integreat application, originally developed by German students and now used by over 60 municipalities across Germany to provide information to new arrivals; the OSKARI software in Finland and the Lutece software launched by the City of Paris and used across France. All five are available on the OSOR Knowledge Centre.
Guidelines for Sustainable Open Source Communities in the Public Sector
We had initially envisaged producing four case studies looking at sustainable public sector OSS projects and one looking at an unsustainable project. However, it proved difficult to follow up with representatives of case studies on unsustainable projects and to receive consent to publish their input. For this reason, all five case studies focus on sustainable communities.
These case studies helped us to gather an in-depth understanding of the similarities and differences across OSS communities in the public sector. They also helped us to better understand how the success factors we identified through our research contribute to communities' sustainability in practice.
More information about the above methodology can be found in a supporting study Success Factors for Sustainable Open Source Communities published on the OSOR Knowledge Centre.
Community feedback
The three-step approach described above was only possible with the kind contribution of the vibrant OSS community that shared their thoughts and experiences throughout the entire process.
Our team held a workshop at the FOSDEM 2020 conference conference to validate the research on the five key sustainability factors and to gather further input from the open source community. We also organised a community webinar where we presented the draft on the Guidelines and gathered feedback from the webinar participants on how the Guidelines could be further developed.
Finally, several community members (see Acknowledgements) provided feedback on the draft version of the Guidelines.
An action supported by ISA²
ISA² is a EUR 131 million programme of the European Commission which develops digital solutions that enable interoperable cross-border and cross-sector public services, for the benefit of public administrations, businesses and citizens across the EU.
ISA² supports a wide range of activities and solutions, among which is the Sharing and Reuse action.
ISA² solutions can be used free of charge and are open source when related to IT.
More on the programme
ec.europa.eu/isa2
Contact ISA²
isa2@ec.europa.eu
Follow us
@EU_ISA2
@Joinup_eu
isa² programme
|
{"Source-Url": "https://joinup.ec.europa.eu/sites/default/files/inline-files/Guidelines%20for%20Sustainable%20OSS%20Communities%20in%20the%20Public%20Sector%20final.pdf", "len_cl100k_base": 15194, "olmocr-version": "0.1.50", "pdf-total-pages": 44, "total-fallback-pages": 0, "total-input-tokens": 82887, "total-output-tokens": 17242, "length": "2e13", "weborganizer": {"__label__adult": 0.00045609474182128906, "__label__art_design": 0.0013170242309570312, "__label__crime_law": 0.0007228851318359375, "__label__education_jobs": 0.009674072265625, "__label__entertainment": 0.0002275705337524414, "__label__fashion_beauty": 0.00021338462829589844, "__label__finance_business": 0.007720947265625, "__label__food_dining": 0.0004503726959228515, "__label__games": 0.0014896392822265625, "__label__hardware": 0.0006551742553710938, "__label__health": 0.0004968643188476562, "__label__history": 0.0005769729614257812, "__label__home_hobbies": 0.0003521442413330078, "__label__industrial": 0.00038814544677734375, "__label__literature": 0.0004925727844238281, "__label__politics": 0.0018053054809570312, "__label__religion": 0.00039076805114746094, "__label__science_tech": 0.01291656494140625, "__label__social_life": 0.00086212158203125, "__label__software": 0.041290283203125, "__label__software_dev": 0.91650390625, "__label__sports_fitness": 0.0002830028533935547, "__label__transportation": 0.0005369186401367188, "__label__travel": 0.00032782554626464844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 84218, 0.01558]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 84218, 0.22188]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 84218, 0.9314]], "google_gemma-3-12b-it_contains_pii": [[0, 72, false], [72, 1575, null], [1575, 2203, null], [2203, 4522, null], [4522, 7812, null], [7812, 11982, null], [11982, 15499, null], [15499, 16905, null], [16905, 16971, null], [16971, 19377, null], [19377, 21790, null], [21790, 24329, null], [24329, 27099, null], [27099, 28966, null], [28966, 30890, null], [30890, 33696, null], [33696, 34223, null], [34223, 34255, null], [34255, 36566, null], [36566, 38599, null], [38599, 41269, null], [41269, 43912, null], [43912, 45736, null], [45736, 47734, null], [47734, 47780, null], [47780, 49659, null], [49659, 52238, null], [52238, 54489, null], [54489, 57067, null], [57067, 59369, null], [59369, 62345, null], [62345, 64057, null], [64057, 66373, null], [66373, 68731, null], [68731, 71277, null], [71277, 73886, null], [73886, 75549, null], [75549, 76716, null], [76716, 76744, null], [76744, 79174, null], [79174, 79188, null], [79188, 82001, null], [82001, 83632, null], [83632, 84218, null]], "google_gemma-3-12b-it_is_public_document": [[0, 72, true], [72, 1575, null], [1575, 2203, null], [2203, 4522, null], [4522, 7812, null], [7812, 11982, null], [11982, 15499, null], [15499, 16905, null], [16905, 16971, null], [16971, 19377, null], [19377, 21790, null], [21790, 24329, null], [24329, 27099, null], [27099, 28966, null], [28966, 30890, null], [30890, 33696, null], [33696, 34223, null], [34223, 34255, null], [34255, 36566, null], [36566, 38599, null], [38599, 41269, null], [41269, 43912, null], [43912, 45736, null], [45736, 47734, null], [47734, 47780, null], [47780, 49659, null], [49659, 52238, null], [52238, 54489, null], [54489, 57067, null], [57067, 59369, null], [59369, 62345, null], [62345, 64057, null], [64057, 66373, null], [66373, 68731, null], [68731, 71277, null], [71277, 73886, null], [73886, 75549, null], [75549, 76716, null], [76716, 76744, null], [76744, 79174, null], [79174, 79188, null], [79188, 82001, null], [82001, 83632, null], [83632, 84218, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 84218, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 84218, null]], "pdf_page_numbers": [[0, 72, 1], [72, 1575, 2], [1575, 2203, 3], [2203, 4522, 4], [4522, 7812, 5], [7812, 11982, 6], [11982, 15499, 7], [15499, 16905, 8], [16905, 16971, 9], [16971, 19377, 10], [19377, 21790, 11], [21790, 24329, 12], [24329, 27099, 13], [27099, 28966, 14], [28966, 30890, 15], [30890, 33696, 16], [33696, 34223, 17], [34223, 34255, 18], [34255, 36566, 19], [36566, 38599, 20], [38599, 41269, 21], [41269, 43912, 22], [43912, 45736, 23], [45736, 47734, 24], [47734, 47780, 25], [47780, 49659, 26], [49659, 52238, 27], [52238, 54489, 28], [54489, 57067, 29], [57067, 59369, 30], [59369, 62345, 31], [62345, 64057, 32], [64057, 66373, 33], [66373, 68731, 34], [68731, 71277, 35], [71277, 73886, 36], [73886, 75549, 37], [75549, 76716, 38], [76716, 76744, 39], [76744, 79174, 40], [79174, 79188, 41], [79188, 82001, 42], [82001, 83632, 43], [83632, 84218, 44]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 84218, 0.05419]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
6ae93f94a36e5c15c1a2df323640b1d78d57d494
|
Version of July 20, 1999
A Courteous Compiler
From Generalized Courteous Logic Programs
To Ordinary Logic Programs
(Preliminary Report)
(Supplementary Update Follow-On to IBM Research Report RC 21472)
Benjamin N. Grosof
IBM Research Division
T.J. Watson Research Center
P.O. Box 704, Yorktown Heights, NY 10598, USA
(914) 784-7783 direct -7455 fax -7100 main
Internet e-mail: grosof@us.ibm.com
(or grosof@watson.ibm.com or grosof@cs.stanford.edu)
Web: http://www.research.ibm.com/people/g/grosof;
or http://www.research.ibm.com to find IBM Research Reports.
Abstract
We define a generalized form of courteous logic programs (GCLP), and how to transform (i.e., compile) GCLP into ordinary logic programs (OLP). This builds upon the transformational approach in [5]. We detail the syntax of GCLP, and briefly discuss the intended semantics of GCLP in an informal fashion. Its precise semantics are defined in terms of the semantics of the OLP outputted by the transform, in a manner similar to that in [5]. We briefly discuss the computational complexity of GCLP; it retains the attractive tractability of the previous less general form of courteous logic programs. In a future version of this paper, we will give formal well-behavior results about GCLP.
The GCLP form of courteous LP’s, and of the courteous compiler that transforms a GCLP into an OLP, described here corresponds to the version currently implemented in the IBM CommonRules prototype system, an alpha release of which will be publicly available free on the Web in summer of 1999.
Contents
1 Introduction and Overview 1
2 Preliminary Definitions 1
3 Definition: Generalized Courteous LP’s 2
3.1 Overview ......................................................... 2
3.2 Syntax ........................................................... 3
3.3 Semantics Overview ............................................ 4
3.3.1 Intended Semantics and Behavior; not yet proven as results, probably needs additional expressive restrictions ....................... 5
4 Transforming GCLP to OLP 5
4.1 Overview ........................................................... 5
4.2 Definitions ...................................................... 6
5 Semantics of GCLP; Inferencing; C3LP and CU2LP 9
6 Examples 11
7 Well-Behavior 11
References 12
1 Introduction and Overview
In this paper, we define generalized courteous logic programs (GCLP), as implemented in the IBM CommonRules prototype system. This prototype is a Java class library. An alpha version of this prototype is scheduled for public release on the Web, at IBM’s AlphaWorks in July or August of 1999, with a free trial license: see http://alphaworks.ibm.com, or see the pointer to there from http://www.research.ibm.com/rules/.
GCLP is further expressively generalized relative to the form of courteous logic programs (BCLP) previously defined in [5], which was itself expressively generalized from the basic form in [4] [3]. Relative to the basic form of courteous LP’s in [4], the generalization in this paper has four aspects.
1) Mutual exclusion constraints (mutex’s), each between a pair of classical literals, are permitted. The mutual exclusion between $p$ and $\neg p$ is a special case of such a mutex. Consistency with respect to such mutex’s is then enforced.
2) Recursive dependence among the predicates is permitted without restriction.
3) The appearance of the prioritization predicate is unrestricted.
4) Reasoning about the prioritization ordering is permitted. I.e., inferring conclusions about the overrides predicate, derived from rules possibly via chaining, is permitted.
Semantic guarantees are stronger, however, under additional expressive restrictions. Only aspects (2)–(4), but not aspect (1), were contained in [5].
As part of defining GCLP, we describe a “Conflict-Resolving” (“CR”) transformer from generalized courteous logic programs (GCLP’s) to ordinary logic programs (OLP’s): for each input GCLP, the transformer outputs a corresponding OLP. This transformer is also known as a “courteous compiler”. The CR transformation provides an indirect semantics for GCLP in terms of OLP. Relative to OLP, GCLP provides additional expressive features and functional capabilities, which include classical negation and mutual exclusion constraints, as well as prioritized conflict handling. The CR transformer provides a means to achieve this higher level of functionality, by composing the transformer (embodied as a software component) with (software) components that can manipulate OLP’s, e.g., with OLP inference engines or OLP rule editors. Multiple such OLP inference engines and OLP rule editors previously exist commercially. The CR transformer is thus suitable for commercial application as a pre-processor for rule-based systems.
This paper is an update follow-on to [5].
2 Preliminary Definitions
Background: We assume the reader is familiar with: the previous published version of courteous logic programs [4] [3], extended logic programs [2], the concept of ordinary, non-extended logic programs, the semantics of stratified (ordinary, non-extended) logic programs with negation as failure (e.g., [7]), and the standard concepts in the logic programming literature (e.g., as reviewed in [1]), including predicate / atom dependency graph and its acyclicity / non-recursiveness; and instantiation. Appendix A contains some review of these concepts.
In this section, we introduce some preliminary definitions, notation, and terminology. This includes reviewing extended logic programs (ELP’s) cf. [2].
Each rule $r$ in an extended logic program $E$ has the form:
$$L_0 \leftarrow L_1 \land \ldots \land L_m \land \neg L_{m+1} \land \ldots \land \neg L_n$$
1
where \( n \geq m \geq 0 \), and each \( L_i \) is a literal.
We will define courteous LP’s’ rule syntax to be similar but not identical to that of extended LP’s.
Notation and Terminology: A literal (which we will also call a classical literal) is a formula of the form \( A \) or \( \neg A \), where \( A \) is an atom. \( \neg \) stands for the classical negation operator symbol, and \( \sim \) for the negation-as-failure operator symbol. In English, we read the former as “not” and the latter as “fail”. We say that an unnegated literal (i.e., an atom) is positive. A ground rule with empty body is called a fact. Syntactically, an “ordinary” logic program (OLP) (also known as a “general” logic program) is one in which each literal \( L_j \) above is an atom, i.e., where no classical negation is permitted.
3 Definition: Generalized Courteous LP’s
Next, we define an expressively-generalized form of courteous logic programs, concentrating on its syntax. We call these Generalized Courteous Logic Programs (GCLP) The theory of GCLP’s semantics is the subject of other papers rather than of this paper.
Our point of departure is the previous published version of courteous LP’s, which we will call here “Basic Courteous Logic Programs” (BCLP).
3.1 Overview
The generalization of GCLP (relative to BCLP) has three aspects.
- **Mutual exclusion constraints** (”mutex”s) are permitted. Each such constraint specifies mutual exclusion between a pair of (classical) literals.
Intuitively, the mutual exclusion specifies that at most one of the literals, rather than both, should be inferable from the GCLP.
Intuitively, the set of mutual exclusion constraints in a GCLP taken together specify the scope of conflict, and thereby the scope of conflict handling.
Implicitly, \( A \) and \( \neg A \) are treated as mutually exclusive, for each atom \( A \). This is essentially similar to BCLP.
- Recursive dependence among the predicates is permitted without restriction. This relaxes the restriction in BCLP; there, such recursive dependence was prohibited.
- The appearance of the prioritization predicate (\textit{Overrides}, which has a special role semantically) is unrestricted.
This relaxes two restrictions in BCLP; there, \textit{Overrides} was required to appear only in rules having the form of facts, and the prioritization relation specified by the set of rules about \textit{Overrides} as required to be a strict partial order.
Note that BCLP is a special case of GCLP, syntactically.
Semantic guarantees will be stronger under additional expressive restrictions. However, that theory about the semantics is the subject of other papers rather than of this document.
Relative to ordinary logic programs (OLP), GCLP is expressively-generalized in the following ways:
- Each rule is permitted to have a (rule) label. These labels are used as handles for specification of prioritization between rules. (This is as in BCLP.)
• Classical negation is permitted to appear in any rule literal. If it appears, it must be inside the scope of negation-as-failure. (This is as in BCLP.)
• Mutual exclusion constraints (as described above) are permitted.
Note that OLP is a special case of GCLP as well as of BCLP, syntactically.
3.2 Syntax
Next, we define GCLP’s syntax in detail.
Syntactically, a GCLP is defined as a class of extended logic programs in which, additionally, rules have (optional) labels and mutual exclusion constraints may appear. These labels are used as handles for specification of prioritization between rules.
Definition 1 (Labelled Rule)
A labelled rule has the form:
\[
\langle \text{lab} \rangle \quad L_0 \leftarrow L_1 \land \ldots \land L_m \land \lnot L_{m+1} \land \ldots \land \lnot L_n.
\]
where lab is the rule’s label (and, as before, \( n \geq m \geq 0 \), and each \( L_i \) is a literal). The label is optional. If omitted, the label is said to be empty. The label is not required to be unique within the scope of the overall logic program; i.e., two rules may have the same label. The label is treated as a 0-ary function symbol. The label is preserved during instantiation; all the ground instances of the rule above have label lab. □
Terminology: henceforth, when the context is clear, “rule” will be used to mean “labelled rule”, unless the distinction is made explicitly.
In the newly generalized version of CLP, the CLP also optionally includes a set of pairwise mutual exclusion (mutex) statements, along with the rules. These mutex’s specify the scope of conflict.
Definition 2 (Mutual Exclusion Constraint, i.e., Mutex)
A mutual exclusion constraint (mutex for short) has one of the two syntactic forms below; it is either unconditional or conditional.
An unconditional mutex has the syntactic form:
\[
\bot \leftarrow L_1 \land L_2.
\]
where each \( L_i \) is a classical literal.
Intuitively, the mutex specifies that at most one of the literals, rather than both, should be inferrable from the GCLP. More precisely, the mutex specifies this for any instantiation of the logical variables appearing in the mutex.
Intuitively, the set of mutual exclusion constraints in a GCLP taken together specify the scope of conflict, and thereby the scope of conflict handling.
As we will discuss more later when defining the transform from GCLP to OLP: implicitly, \( A \) and \( \lnot A \) are treated as mutually exclusive, for each atom \( A \). This is essentially similar to BCLP.
These mutex’s are particularly useful for specifying that at most one of a set of alternatives is to be permitted. E.g., it is straightforward to specify via 3 mutex’s that the lead time must be at most one of the values \{2 days, 14 days, 30 days\}. E.g., it is straightforward to specify via 3 mutex’s that the discount percentage must be at most one of the values \{0\%, 5\%, 10\%\}.
It is expressively more convenient sometimes to use a more general form of mutex: a conditional mutex, which has the syntactic form:
\[
\bot \leftarrow L_1 \land L_2 \mid G_1 \land \ldots \land G_g.
\]
Here, \( g \geq 0 \), each \( L_i \) is a classical literal, and each \( G_j \) is a literal (in which \( \sim \), as well as \( \neg \), may appear). If \( g=0 \), then the " | " is omitted. The conjunctive formula \( G_1 \land \ldots \land G_g \) is called the "given" part of the mutex. Intuitively, the given part of the mutex specifies conditions under which \( L_1 \) and \( L_2 \) oppose each other. More precisely, it specifies that \( L_1 \) and \( L_2 \) should not both be inferable if the given is true (i.e., if the given is inferable).
At this point in the evolution of the courteous LP formalism, the main motivation for permitting conditional (rather than simply unconditional) mutex’s is to permit conditional mutex’s that have the syntactic form:
\[ \perp \leftarrow L_1 \land L_2 \mid \left( ?Y \neq ?Z \right) \]
where \(?Y\) and \(?Z\) are logical variables that appear respectively in \( L_1 \) and \( L_2 \). E.g.,
\[ \perp \leftarrow \text{giveDiscount(?Cust, ?YPercent)} \land \text{giveDiscount(?Cust, ?ZPercent)} \mid \left( ?YPercent \neq ?ZPercent \right) \]
This conditional mutex enables one to specify with a single mutex statement (rather than with three or more unconditional mutex’s) that for a given customer \(?Cust\) there must be at most one value concluded for the discount percentage.
Beyond this restricted form of conditional mutex’s, we are treating the usefulness of conditional mutex’s as an issue to investigate both theoretically and empirically. The full expressive generality of conditional mutex’s as defined above may be unnecessary or even undesirable. In short, the full expressive generality of conditional mutex’s is experimental in this sense.
The enforcement of classical negation can be viewed as set of implicit unconditional mutex’s, one for each predicate \( Q \), that each have the form
\[ \perp \leftarrow Q(?X_1, \ldots, ?X_m) \land \neg Q(?X_1, \ldots, ?X_m) \]
where \( Q \)’s arity is \( m \). This is called a classical mutex. □
**Definition 3 (Prioritization Predicate)**
A special binary predicate \( \text{Overrides} \) is used to specify prioritization. \( \text{Overrides}(i, j) \) specifies that the label \( i \) has (strictly) higher priority than the label \( j \). □
Intuitively, prioritization is used as part of handling conflicts that arise when two rules (whose bodies are satisfied) have mutually exclusive heads; prioritization influences which rule’s head will be inferred as a conclusion.
**Definition 4 (Generalized Courteous LP: Syntax; PCNMLP)**
A generalized courteous logic program \( C \) is defined as a collection of labelled rules and mutex’s, i.e., as the union of a set of (labelled) rules and a set of mutex’s:
\[ C = C_{\text{rule}} \cup C_{\text{mutex}} \]
Both \( C_{\text{rule}} \) and \( C_{\text{mutex}} \) may be empty.
We also call this GCLP syntax: PCNMLP syntax. "P" stands for “with Priorities”, “CN” stands for “with Classical Negation”, and “M” stands for “with Mutex’s”. □
Note that the prioritization predicate \( \text{Overrides} \) and the labels are treated as part of the language of the logic program, similarly to other predicate and function symbols appearing in \( C \).
Terminology and Notation: We call \( C_{\text{rule}} \) the rule set or rules of \( C \). We call \( C_{\text{mutex}} \) the mutex set or mutex’s of \( C \). We write \( C_{\text{Overrides}} \) for the subset of \( C_{\text{rule}} \) in which \( \text{Overrides} \) appears, and call this the prioritization rules subset of \( C \).
**3.3 Semantics Overview**
In this paper, we formally do not define semantics directly for GCLP, but rather describe how to transform a GCLP into an OLP (in section 4). This continues the overall transformational approach described in [5].
4
In [3], by contrast, semantics for BCLP are defined directly in an abstract, model-theoretic fashion.
For now, our intention for usage of GCLP is summarized in the following overview of its intended semantics and behavior, *not yet proven as results*, which probably require some expressive restrictions to ensure that they hold. Elsewhere, we will give more detailed theory about GCLP, including theorems about its semantics and behavior.
3.3.1 Intended Semantics and Behavior; not yet proven as results, probably needs additional expressive restrictions
Semantically, the prioritized conflict handling in CLP is defined by a process of prioritized argumentation among opposing candidates. Opposition is specified by the set of mutex's. Each rule $r$ whose body is satisfied, i.e., which “fires”, generates a candidate $c$ for $r$'s (appropriately instantiated) head $p$. This candidate has an associated label, which is simply that rule $r$'s label. In general, there may be multiple candidates for a given $p$, i.e., a team for $p$. If there is an opposing candidate $d$ (i.e., a candidate for an opposing literal $q$) that has higher priority than candidate $c$, then $c$ is refuted. Suppose there is an unfuted candidate for $p$. If there are no unfuted candidates for any oppser of $p$, then $p$ wins, i.e., $p$ is concluded. However, it may be that there is an unfuted candidate for an oppser of $p$; in this case, the opposing unfuted candidates skeptically defeat each other. The conflict cannot be resolved by the specified priority; neither $p$ nor its oppser is concluded.
Another way to view this is as follows. An opposition-locale is a set of $h \geq 2$ ground classical literals that oppose each other, such that at most one of those literals is permitted (by the specified mutex's) to be concluded. In each opposition-locale, if the maximal-priority candidates are all for the same literal, then that literal wins.
4 Transforming GCLP to OLP
In this section, we describe how to transform any given GCLP $\mathcal{C}$ into an OLP $\mathcal{O}$. We write this transform $\mathcal{C} \rightarrow \mathcal{O}$.
Relative to OLP, GCLP contains additional expressive features, e.g., mutex's, classical negation, rule labels. These together with a special role of the prioritization predicate Overrides are used to specify prioritized conflict handling. In this sense, GCLP has a higher level of expressiveness than OLP.
The transform thus specifies how this higher level of expressiveness can be supported in OLP, albeit indirectly.
4.1 Overview
In this subsection, we give an overview of the transform's steps.
Step 1: Eliminate classical negation.
For each predicate $P$, each appearance of $\neg P$ is replaced by an appearance of the new predicate $n.P$; and a new (explicit) mutex between $P$ and $n.P$ is introduced.
Step 2: Analyze which pairs of rules are in opposition.
Opposition between two rules means that there is a mutex relating their rule heads.
Step 3: For each predicate $Q$, create an associated output set of OLP rules.
This is done by modifying the GCLP rules whose heads mention $Q$, plus adding some more rules.
Step 4: Union the results of step 3 to form the overall output OLP.
4.2 Definitions
Definition 5 (Transform to Eliminate Classical Negation (ECN))
We define the ECN transform, which eliminates (the appearance of) classical negation, as follows. It takes an input GCLP $C$ and produces an output GCLP which we write as $ECN(C)$. This is done by a simple rewriting operation, similar to that in [2]. This rewriting has two aspects. The first aspect is that each appearance of $\neg P$ (in the mutex’s as well as in the rules) is replaced by $n_P$, where $n_P$ is a newly introduced predicate symbol (with the same arity as $P$). We call $n_P$: $P$’s negation predicate. $n_P$ is only introduced if there is actually an appearance of $\neg P$ in the input PCNMLP. Note that if the input PCNMLP does not contain any appearances of classical negation, then the output PCNMLP is simply the same as the input PCNMLP.
We say that $n_P$ is the complement of $P$, and vice versa. Given a predicate $Q$ in $ECN(C)$, we write $Q\neg$ to stand for $Q$’s complement.
$n_P$ is only introduced if there is actually an appearance of $\neg P$ in the input GCLP.
The second aspect of the rewriting (which is not present in [2]) is the following. If $n_P$ is introduced, then a new (explicit) mutex between $P$ and $n_P$ is also introduced (i.e., added to the output GCLP); we call this a classical mutex. This mutex has the form:
$$ \bot \leftarrow P(x) \land n_P(x). $$
(classicalMutexP)
where $x$ is a tuple of logical variables, of arity appropriate for $P$.
Note that if the input GCLP does not contain any appearances of classical negation, then the output GCLP is simply the same as the input GCLP.
We further define the inverse ECN transform: $ECN^{-1}$, which maps $ECN(C)$ back into $C$. This just rewrites $n_P$ back to be $\neg P$. □
Intuitively, the classical mutex between $P$ and $n_P$ corresponds to there being an implicit mutex between $P$ and $\neg P$ before the ECN transform.
Definition 6 (A Predicate’s Rule Locale)
Relative to a GCLP $C$: the rule locale for a predicate $P$, written $RuleLocale(P)$, is defined as the (possibly empty) subset of rules in $C$ in which $P$ appears in the rule head (positively or negatively). □
Roughly speaking, opposition between two rules means that there is a mutex relating their heads. The following makes this more precise.
Definition 7 (Opposition between Rules, Predicates, Literals)
Relative to a GCLP $C$ in which classical negation does not appear:
Let rule $r_1$ have head $P1(t1)$ and rule $r_2$ have head $P2(t2)$, where $P1$ and $P2$ are predicates, and $t1$ and $t2$ are term tuples. The rules $r_1$ and $r_2$ are in opposition, i.e., are opposers of each other, if and only if (iff) there is some mutex $m$ having the form
$$ \bot \leftarrow P1(u1) \land P2(u2) \mid Ei[z]. $$
, where $u1$ and $u2$ are term tuples, such that $t1 = u1$ and $t2 = u2$ are simultaneously unifiable in the sense that there is a substitution $\theta$ that both unifies $t1$ with $u1$ and unifies $t2$ with $u2$.
(Note that the above concept of opposition can be straightforwardly generalized to the case where classical negation does appear: simply match literals’ classical signs, and include consideration of classical mutex’s.)
If such an $m$ exists, we say that:
$m$ is a relating mutex for the pair $\langle r1, r2 \rangle$;
$m$ is a relevant mutex for $r1$ and for $r2$;
\(\langle r_1, \theta, r_2 \rangle\) is a relevant opposition triple, with associated relating mutex \(m\), where \(\theta\) is the maximum general unifier that simultaneously both unifies \(t_1\) with \(u_1\) and \(t_2\) with \(u_2\) (as described above).
Also, if such an \(m\) exists, we say that:
the predicates \(P_1\) and \(P_2\) are in opposition, i.e., are opposers of each other;
\(m\) is a relating mutex for the pair \(\langle P_1, P_2 \rangle\); and
\(m\) is a relevant mutex for \(P_1\) and for \(P_2\).
Furthermore, if such an \(m\) exists, we say that:
the literals \(P_1(t_1)\) and \(P_2(t_2)\) are in opposition, i.e., are opposers of each other;
\(m\) is a relating mutex for the pair \(\langle P_1(t_1), P_2(t_2) \rangle\); and
\(m\) is a relevant mutex for \(P_1(t_1)\) and for \(P_2(t_2)\).
Note that \(\theta\) above is equivalent to the maximum general unifier of:
\(\langle t_1, t_2 \rangle = \langle u_1, u_2 \rangle\)
where \(\langle t_1, t_2 \rangle\) stands for the tuple formed by concatenating the tuples \(t_1\) and \(t_2\); and, likewise,
\(\langle u_1, u_2 \rangle\) stands for the tuple formed by concatenating the tuples \(u_1\) and \(u_2\).
We also write \(\theta\) as \(\text{mgu}(r_1, m, r_2)\). Note that \(\theta\) is required above to be non-empty (i.e., a non-empty unifier / substitution).
We write \(\text{RelOppTriples}(\text{rule}_j)\) to stand for the set of all relevant opposition triples in which \(\text{rule}_j\) appears as the first member of the triple.
We write \(\text{RelMuts}(q)\) to stand for the set of all mutex’s that are relevant to \(q\).
We write \(\text{HasRelOppTriples}(q)\) to stand for whether: there is a rule \(\text{rule}_j\) in \(\text{RuleLocale}(q)\) such that \(\text{RelOppTriples}(\text{rule}_j)\) is non-empty. (This is a boolean; iff true, it indicates there are indeed such triples). ∎
**Definition 8 (Conflict Resolution Transform Per Locale)**
Relative to a GCLP \(C\) in which classical negation does not appear: for each predicate \(q\), we define the per-locale transform \(\text{CR}(C, q)\) as follows.
Below, we will leave \(C\) implicit notationally.
If \(\text{HasRelOppTriples}(q)\) is false, then \(\text{CR}(q)\) is \(\text{RuleLocale}(q)\). I.e., in this case, the per-locale transform simply passes through the input’s rule locale for predicate \(q\), unchanged. A special case is when \(\text{RuleLocale}(q)\) is empty: then \(\text{HasRelOppTriples}(q)\) is false, and \(\text{CR}(q)\) is empty.
Otherwise, i.e., if \(\text{HasRelOppTriples}(q)\) is true, then \(\text{CR}(q)\) is defined (more complexly) as follows.
“Include” below means “include in the output of the transform”.
Let \(\text{RuleLocale}(q)\) stand for the set of all rules that are in the rule locale for predicate \(q\). For each rule \(\text{rule}_j\) in \(\text{RuleLocale}(q)\), include the rule:
\[
q(t_j) \leftarrow q_a(t_j) \land \sim q_s(t_j).
\]
(1j)
Here, \(q_a\) and \(q_s\) are newly introduced predicates, each with the same arity as \(q\). Intuitively, \(q_a(t)\) stands for “\(q\) has an unfuted candidate for instance \(t\)”, and \(q_s(t)\) stands for “\(q\) is skeptically defeated for instance \(t\)”.
For each rule \(\text{rule}_j\) in \(\text{RuleLocale}(q)\), include the rule:
\[
q_{cj}(t_j) \leftarrow B_j[yj].
\]
(2j)
where \(\text{rule}_j\) has the form:
\[
q(t_j) \leftarrow B_j[yj].
\]
(rule_\(j\))
Here, $B_j[yj]$ stands for the body of $rule_j$, $yj$ is the tuple of logical variables that appear in $B_j$. $tj$ is the term tuple appearing (as argument tuple to $q$) in the head of $rule_j$. $qcj$ is a newly introduced predicate. Intuitively, $qcj(t)$ stands for “$q$ has a candidate for instance $t$, generated by rule $rule_j$”.
For each rule $rule_j$ in $RuleLocale(q)$, include the rule:
$$q_u(tj) \leftarrow qcj(tj) \land \sim qr_j(tj). \quad (3j)$$
Here, $qr_j$ is a newly introduced predicate. Intuitively, $qr_j(t)$ stands for “the candidate for $q$ for instance $t$, generated by $rule_j$, is refuted”. Intuitively, “refuted” means “refuted by some higher-priority conflicting rule’s candidate”.
Recall from Definition 7 that $RelOppTriples(rule_j)$ stands for the set of all relevant opposition triples in which $rule_j$ appears as the first member of the triple.
For each rule $rule_j$ in $RuleLocale(q)$ and each relevant opposition triple $jikTriple$ in $RelOppTriples(rule_j)$, include the rule:
$$qr_j(jj\theta_{jik}) \leftarrow qcj(tj\theta_{jik}) \land p^i_{ck}(wk\theta_{jik})$$
$$\land Overrides(lab_k,lab_j) \land Ei[(zi\theta_{jik})]. \quad (4jik)$$
where $jikTriple$ has the form:
$$\langle rule_j, \theta_{jik}, rule_k \rangle \quad (jikTriple)$$
with associated relating mutex $mut_i$ having the form:
$$\bot \leftarrow q(ui) \land p^i(vi) \mid Ei[zi]. \quad (mut_i)$$
Here, $rule_k$ has the form:
$$p^i(wk) \leftarrow Bk[yk]. \quad (rule_k)$$
$p^i$ is a predicate, which may possibly be $q$. $wk$ is the term tuple appearing (as argument tuple to $p^i$) in the head of $rule_k$. $Bk[yk]$ stands for the body of $rule_k$. $yk$ is the tuple of logical variables that appear in $Bk$. $ui$ and $vi$ are term tuples of arity appropriate to $q$ and $p^i$ respectively. $\cdot$ stands for the operation of applying a substitution, as usual with unifiers. $\theta_{jik}$ stands for $muJ(rule_j, mut_i, rule_k)$, i.e., the maximum general unifier that simultaneously unifies both $tj$ with $ui$, and $vi$ with $wk$ (recall Definition 7). $p^i_{ck}$ bears the same relationship to $\langle p^i, rule_k \rangle$ as $qcj$ bears to $\langle q, rule_j \rangle$. $Overrides$ stands, as usual, for the prioritization predicate. $lab_k$ is the rule label of $rule_j$. $lab_k$ is the rule label of $rule_k$. If the rule label of $rule_j$ is empty, then $lab_k$ is assigned to be $emptyLabel$. $emptyLabel$ is a newly introduced 0-ary function (i.e., logical function symbol with 0 arity); intuitively, it stands for the empty rule label. Recall that $Ei$ is a formula (conjunction of literals) whose logical variables are $zi$. $Ei[(zi\theta_{jik})]$ stands for the result of applying the substitution $\theta_{jik}$ to $zi$, and then substituting that result into $Ei$.
For each rule $rule_j$ in $RuleLocale(q)$ and each relevant opposition triple $jikTriple$ in $RelOppTriples(rule_j)$, include the rule:
$$q_u(tj\theta_{jik}) \leftarrow q_u(tj\theta_{jik}) \land p^i_u(wk\theta_{jik}) \land Ei[(zi\theta_{jik})]. \quad (5jik)$$
Here, $p^i_u$ is a newly introduced predicate that bears the same relationship to $p^i$ as $q_u$ bears to $q$; i.e., intuitively, $p^i_u$ stands for “$p^i$ has an unrefuted candidate”.
$\square$
We are now ready to define the entire output of transforming a whole GCLP.
Definition 9 (Overall Conflict Resolution Transform For GCLP)
Let $\mathcal{C}$ be a GCLP. The conflict resolution transform’s output $\text{CR}(\mathcal{C})$ is defined as follows. Let $\mathcal{C}_{\text{NCN}}$ stand for $\mathcal{ECN}(\mathcal{C})$, i.e., for the result of applying the ECN transform to $\mathcal{C}$. “NCN” here is mnemonic for “No Classical Negation”. Let $\text{Predicates}(\mathcal{C}_{\text{NCN}})$ stand for the set of all predicates that appear in $\mathcal{C}_{\text{NCN}}$ (in the mutex’s as well as in the rules).
$$\text{CR}(\mathcal{C}) = \bigcup_{q \in \text{Predicates}(\mathcal{C}_{\text{NCN}})} \text{CR}(\mathcal{C}_{\text{NCN}}, q)$$
In other words, the output of the CR transform for the overall GCLP is the result of first eliminating classical negation, via the ECN transform, then collecting (i.e., union’ing) all the per-locale CR transforms’ outputs.
Recall from Definition 8 that intuitively, $\text{emptyLabel}$ represents the empty rule label. Note that $\text{emptyLabel}$ is introduced only if needed, i.e., if the set of relevant opposition triples is non-empty. Note also that $\text{emptyLabel}$ is introduced at most once, i.e., the same $\text{emptyLabel}$ is shared by all the per-locale CR transforms.
We write this version of the overall conflict resolution transform as $\text{CR}\_\text{Cour2}$, to distinguish it from the previous version (called $\text{CR}\_\text{Cour1}$) in [5]; we write the OLP outputted by this version of the overall as $\text{CR}\_\text{Cour2}(\mathcal{C})$. □
5 Semantics of GCLP; Inferencing; C3LP and CU2LP
Recall: the semantics overview in section 3.3.1.
PCNMLP syntax, i.e., GCLP syntax, has many possible semantics as a knowledge representation. Among these possible choices, we next define one particular choice.
Semantically, we treat a PCNMLP or OLP rule with variables as shorthand for the set of all its ground instances. This is as usual in the logic programming literature (including CILP, i.e., the basic form of courteous LP’s in [4]). We write $\mathcal{C}^{\text{instd}}$ to stand for the LP that results when each rule in $\mathcal{C}$ is replaced by the set of all its possible ground instantiations.
In the spirit of the well-founded semantics (WFS) [8], we define the model, (which we also call the set of conclusions) of a PCNMLP most generally to be a truth value assignment that maps each each ground classical literal (rather than atom as in OLP WFS) to exactly one of \{true, false, undefined\}, i.e., a model \(\langle T, F \rangle\) for the ground classical literals. This generalization from atoms to classical literals is as usual in the logic programming literature when defining semantics for classical negation.
Our semantics for PCNMLP syntax, i.e., for GCLP syntax, is defined by compiling GCLP (syntax) to OLP via $\text{CR}\_\text{Cour2}$, and adopting the well-founded semantics (WFS) for the resulting OLP. We call this formalism: version 2 of unrestricted courteous-flavor PCNMLP, abbreviated CU2LP.
Let $\mathcal{C}$ be a given PCNMLP. It has an original set of predicate and function symbols, i.e., ontology. $\text{CR}\_\text{Cour2}(\mathcal{C})$ typically has extra (i.e., newly introduced by the transform) predicate and function symbols. In general, these may include: the original negation predicates that represent classical negation of the original predicates (e.g., $n\_\text{Urgent}$ where $\text{Urgent}$ was an original predicate); the adornment predicate symbols that represent the intermediate stages of the process of prioritized argumentation (e.g., $\text{Urgent}_u$, $\text{Urgent}_c$, $\text{Urgent}_r$, $n\_\text{Urgent}_u$); and the adornment function symbol $\text{emptyLabel}$.
We define the $\text{OLP}$ conclusion set of $\mathcal{C}$ to be the WFS conclusion set of $\text{CR.Cour}_2(\mathcal{C})$. We also call this the \textit{adorned} OLP conclusion set of $\mathcal{C}$, because it contains conclusions mentioning the adornment symbols. We define the \textit{unadorned} OLP conclusion set to be the subset that does not mention any of the adornment symbols.
Corresponding to the OLP conclusion set is the \textit{PCNMLP version} of that conclusion set. The PCNMLP-version conclusion set contains classical negation rather than negation predicates. We define the (unadorned) PCNMLP-version conclusion set to be the result of applying the inverse ECN transform $\text{ECN}^{-1}$ to the unadorned OLP conclusion set, e.g., the negation predicate $n.U'rgent$ is rewritten instead as $\neg U'rgent$.
When the context is clear, we will leave implicit the distinction between these different versions (adorned vs. unadorned, OLP versus PCNMLP) of the conclusion set.
We summarize all this as follows.
**Definition 10 (Compile PCNMLP Via CR.Cour2)**
Let $\mathcal{C}$ be a PCNMLP. The CU2LP semantics for $\mathcal{C}$ is defined as the tuple
$$(\mathcal{C}, \mathcal{O}, \langle T_O, F_O \rangle, \langle T_{PCNM}, F_{PCNM} \rangle)$$
Here, the post-transform (adorned) OLP $\mathcal{O}$ is $\text{CR.Cour}_1(\mathcal{C})$. $\langle T_O, F_O \rangle$ is the (WFS OLP) model for $\mathcal{O}$. $(T_{PCNM}, F_{PCNM})$ is the unadorned PCNMLP version of $(T_O, F_O)$. □
Next, we use the $\text{CR.Cour}_2$ transform and the compilation approach to define a generalized version of courteous LP's. To keep to the spirit of "courteous"-ness cf. CILP (i.e., cf. the basic version of courteous LP’s in [4]), we wish to have some strong semantic guarantees about well-behavior that are similar to those in CILP. Accordingly, we thus restrict CU2LP somewhat so as to ensure such well-behavior.
**Definition 11 (Courteous LP's, Version 3)**
Let $\mathcal{C}$ be a CU2LP. We say that $\mathcal{C}$ is a generalized, i.e., \textit{version-3}, courteous LP, abbreviated as $\text{C3LP}$, when the following three restrictions are satisfied:
1. $\text{CR.Cour}_2(\mathcal{C})$ is locally stratified.
2. The mutex’s (including any implicit classical mutex’s) specify a collection of disjoint opposition-locales. We call this the \textit{one-of} restriction on the mutex’s/opposition.
3. Prioritization is a strict partial order “within” every opposition-locale.
By (2), we mean that after ground-instantiating the mutex’s (including any implicit classical mutex’s), the opposition specified by those mutex’s is equivalent to: a collection of ground opposition-locales that are disjoint. (Recall the definition of “opposition-locale” in section 3.3.1.)
Here, by “disjoint”-ness of two opposition-locales $A$ and $B$, we mean that the set of ground classical literals in $A$ does not intersect with the set of ground classical literals in $B$. Here, the opposition within each ground opposition-locales is unconditional. In summary, the one-of restriction says that the mutex’s specify opposition that is equivalent to a disjoint collection of opposition-locales, where each opposition-locale specifies that at most one of a set of ground classical literals is permitted to be concluded.
An important useful form of conditional mutex that obeys the one-of restriction, is:
$$\perp \leftarrow P(\text{?X1}, \ldots, \text{?Xk}, \text{?Y}) \land P(\text{?X1}, \ldots, \text{?Xk}, \text{?Z}) \mid (\text{?Y} \neq \text{?Z})$$
This specifies that the predicate $P$ is partial-function-al, i.e., that for a given value (instance) of $P$’s first $k$ arguments, one is permitted to conclude at most one value for $P$’s last argument. After instantiating it, this mutex is equivalent to a set of unconditional mutex’s, one for each instance of the first $k$ arguments and disjoint pair of instances for the last argument. E.g.,
$$\perp \leftarrow \text{giveDiscount(\text{?Cust, ?YPercent})} \land \text{giveDiscount(\text{?Cust, ?ZPercent})}$$
is equivalent, after instantiation, to a set of unconditional mutexes:
\[ \bot \leftarrow \text{giveDiscount}(\text{Joe}, 23\%) \land \text{giveDiscount}(\text{Joe}, 31\%). \]
\[ \bot \leftarrow \text{giveDiscount}(\text{Joe}, 31\%) \land \text{giveDiscount}(\text{Joe}, 42\%). \]
\[ \bot \leftarrow \text{giveDiscount}(\text{Ann}, 23\%) \land \text{giveDiscount}(\text{Ann}, 31\%). \]
\[ \bot \leftarrow \text{giveDiscount}(\text{Ann}, 31\%) \land \text{giveDiscount}(\text{Ann}, 42\%). \]
By (3.) we mean the following. For every opposition locale, the set of Overrides tuples in \( T_O \) is a strict partial order when restricted to the set of rule labels appearing in \( \text{RuleLocale}(p) \cup \text{RuleLocale}(p^-) \), where \( p \) is the locale predicate. □
6 Examples
For examples of GCLP’s, including the output of the transform and the results of inferencing, see the many examples included in the alpha release of the IBM CommonRules prototype, available at http://www.research.ibm.com/rules/ in summer 1999. Also, a long example of a GCLP (with unconditional mutexes) is given in [6]: its domain is personalized discounting and promotions in a Web bookstore storefront. In addition, a number of examples of BCLP’s (i.e., less-general-form GCLP’s, where mutexes are classical only) are given in [3] (extending [4]) and [5].
7 Well-Behavior
In a future version of this paper, we will give formal well-behavior results for GCLP, i.e., for C3LP and CU2LP. The well-behavior properties of C3LP and CU2LP are similar to those given in [5] (for C2LP and CU1LP there, respectively).
CLP always produces a consistent set of conclusions, enforcing all the mutexes. A number of other well-behavior properties also hold for CLP, including about merging and about natural behavior of prioritization; however, we defer detailing those until a future version of this paper.
The courteous compiler in effect represents the prioritized argumentation process in OLP. It introduces some extra “adorning” predicates to represent the intermediate stages of argumentation: candidates, unrefuted candidates, etc..
The courteous compiler can be “instrumented” to raise an alarm when unresolved conflict occurs, via introducing further adorning predicates that represent skeptical defeat.
The computational time and space complexity of the CR_Cour2 transform is worst-case cubic, i.e., \( O(n^3) \) where \( n \) is the size of the input GCLP, i.e., of the input PCNMLP. From the tractability of courteous compilation, it follows directly that Courteous LP inferencing under the VBD restriction is tractable: for CU2LP and thus for its special case CU2LP. Here, we say that an LP is “VBD” when either (1.) it is ground, or (2.) it has no logical functions of non-zero arity (a.k.a. the Datalog restriction), and it has a bounded number of logical variables appearing in each rule. The VBD restriction is commonly met in practice.¹ Under the VBD restriction, Courteous LP inferencing has the same worst-case time and space complexity as: OLP inferencing where the bound \( v \) on the number of variables per rule has been increased to \( v + 2 \).
¹It is usually straightforward to representationally reformulate a rule-set so as to replace a logical function \( f \) having arity \( k > 0 \) by a predicate \( fp \) having arity \( k + 1 \), where intuitively the \((k + 1)^{th}\) argument corresponds to the result of applying the function.
References
|
{"Source-Url": "http://web.mit.edu/~bgrosof/www/paps/gclp_report1.pdf", "len_cl100k_base": 10767, "olmocr-version": "0.1.50", "pdf-total-pages": 14, "total-fallback-pages": 0, "total-input-tokens": 77659, "total-output-tokens": 12547, "length": "2e13", "weborganizer": {"__label__adult": 0.00028896331787109375, "__label__art_design": 0.0003077983856201172, "__label__crime_law": 0.0003895759582519531, "__label__education_jobs": 0.0006618499755859375, "__label__entertainment": 6.937980651855469e-05, "__label__fashion_beauty": 0.00013530254364013672, "__label__finance_business": 0.0002758502960205078, "__label__food_dining": 0.0003516674041748047, "__label__games": 0.0006213188171386719, "__label__hardware": 0.0006103515625, "__label__health": 0.00042819976806640625, "__label__history": 0.00018167495727539065, "__label__home_hobbies": 8.636713027954102e-05, "__label__industrial": 0.00043320655822753906, "__label__literature": 0.00037288665771484375, "__label__politics": 0.0003063678741455078, "__label__religion": 0.0004317760467529297, "__label__science_tech": 0.0287628173828125, "__label__social_life": 7.712841033935547e-05, "__label__software": 0.00807952880859375, "__label__software_dev": 0.95654296875, "__label__sports_fitness": 0.0001971721649169922, "__label__transportation": 0.0004088878631591797, "__label__travel": 0.00014221668243408203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42485, 0.02971]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42485, 0.53895]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42485, 0.8707]], "google_gemma-3-12b-it_contains_pii": [[0, 561, false], [561, 2315, null], [2315, 5739, null], [5739, 8699, null], [8699, 11802, null], [11802, 15593, null], [15593, 18820, null], [18820, 22181, null], [22181, 25599, null], [25599, 28930, null], [28930, 32668, null], [32668, 36726, null], [36726, 40175, null], [40175, 42485, null]], "google_gemma-3-12b-it_is_public_document": [[0, 561, true], [561, 2315, null], [2315, 5739, null], [5739, 8699, null], [8699, 11802, null], [11802, 15593, null], [15593, 18820, null], [18820, 22181, null], [22181, 25599, null], [25599, 28930, null], [28930, 32668, null], [32668, 36726, null], [36726, 40175, null], [40175, 42485, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42485, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42485, null]], "pdf_page_numbers": [[0, 561, 1], [561, 2315, 2], [2315, 5739, 3], [5739, 8699, 4], [8699, 11802, 5], [11802, 15593, 6], [15593, 18820, 7], [18820, 22181, 8], [22181, 25599, 9], [25599, 28930, 10], [28930, 32668, 11], [32668, 36726, 12], [36726, 40175, 13], [40175, 42485, 14]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42485, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
cc6033d19b7d1e31dbae6f30abaf6617da644256
|
WCET analysis in shared resources real-time systems with TDMA buses
Hamza Rihani, Matthieu Moy, Claire Maiza, Sebastian Altmeyer
To cite this version:
Hamza Rihani, Matthieu Moy, Claire Maiza, Sebastian Altmeyer. WCET analysis in shared resources real-time systems with TDMA buses. RTNS 2015, Nov 2015, Lille, France. 10.1145/2834848.2834871. hal-01243244
HAL Id: hal-01243244
https://hal.archives-ouvertes.fr/hal-01243244
Submitted on 14 Dec 2015
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
WCET Analysis in Shared Resources Real-Time Systems with TDMA Buses
Hamza Rihani
Univ. Grenoble Alpes
F-38000 Grenoble, France
CNRS, VERIMAG, F-38000
Grenoble, France
hamza.rihani@imag.fr
Matthieu Moy
Univ. Grenoble Alpes
F-38000 Grenoble, France
CNRS, VERIMAG, F-38000
Grenoble, France
matthieu.moy@imag.fr
Claire Maiza
Univ. Grenoble Alpes
F-38000 Grenoble, France
CNRS, VERIMAG, F-38000
Grenoble, France
claire.maiza@imag.fr
Sebastian Altmeyer
University of Luxembourg
Luxembourg
sebastian.altmeyer@uni.lu
ABSTRACT
Predictability is an important aspect in real-time and safety-critical systems, where non-functional properties – such as the timing behavior – have high impact on the system correctness. As many safety-critical systems have a growing performance demand, simple, but outdated architectures are not sufficient anymore. Instead, multi-core systems are more and more popular, even in the real-time domain. To combine the performance benefits of a multi-core architecture with the required predictability, Time Division Multiple Access (TDMA) buses are often advocated. In this paper, we are interested in accesses to shared resources in such environments. Our approach uses SMT (Satisfiability Modulo Theory) to encode the semantics and execution time of the analyzed program in an environment with shared resources. We use an SMT-solver to find a solution that corresponds to the execution path with correct semantics and maximal execution time. We propose to model a shared bus with TDMA arbitration policy. Using examples, we show how the WCET estimation is enhanced by combining the semantics and the shared bus analysis in SMT.
1. INTRODUCTION
Time matters in safety-critical real-time systems. The predictability of these systems is needed in order to guarantee certain security and safety requirements. Determining Worst-Case Execution Times (WCET) has been the focus of research in the field of embedded systems. Static analysis methods have been developed to provide safe bound on the WCET. The challenge remains in improving the pessimistic approaches that over-estimate the execution time of the analyzed program as well as the analysis time. An example of such an approach is the Implicit Path Enumeration Technique (IPET). IPET relies on methods such as Constraint Solving or Integer Linear Programming (ILP). However, the initial version of this approach does not exclude some ‘obvious’ infeasible paths in a program, leading to an over-estimation on the WCET. Algorithm 1 illustrates this situation.
Algorithm 1 Example of mutually exclusive paths
1: LOAD ...
2: ... /* 3 cycles */
3: if c then
4: ... /* 5 cycles */
5: end if
6: if ¬c then
7: ... /* 1 cycles */
8: end if
9: STORE ...
Simple IPET without infeasible path analysis gives the longest path \{\{1\}, \{2\}, \{3\}, \{4\}, \{5\}\}. However, \{3\} and \{4\} are mutually exclusive i.e., they cannot be part of the same execution path. The longest path in this case is \{\{1\}, \{2\}, \{3\}, \{5\}\}. Infeasible paths can be excluded in IPET by adding constraints to the ILP formula [15, 14]. In this paper, we use another approach with Satisfiability Modulo Theory (SMT) that allows to encode the program’s semantics and its execution time.
In a multi-core environment, the longest path does not necessarily imply the worst-case execution time. The access time to the shared resource can vary depending on the arbitration policy of the shared bus and the access patterns in the execution path of the program. In the example of Algorithm 1, the STORE instruction at (5) can access the bus at different instants depending on whether the code at (2) or at (3) is executed. This leads to a variation of the bus access delay depending on the arbitration policy of the shared bus. An analysis that does not consider the semantics together within the micro-architecture analysis would have to analyze the WCET of the STORE instruction with reduced information about the possible instants when it is executed, and may therefore overestimate its execution time.
Henry et al. [9] proposed an SMT-based approach to encode the analyzed program into SMT expressions in order to estimate the WCET. An SMT-solver is used to find the longest feasible path exhibiting the worst-case execution time. In this paper, we extend this approach to include detailed architectural information, thus increasing the precision of the analysis. Our approach encodes parts of the architecture
of the hardware and the program semantics within the same SMT expression, allowing the SMT solver to prove WCET bounds that could not be deduced by analyzing both aspects independently. We focus in this paper on a shared bus with the arbitration policy Time Division Multiple Access (TDMA). TDMA is a time triggered arbitration policy that periodically allocates slots of communication time to each core.
We assume a Fully Timing Composable system architecture [17] without timing anomalies. A timing anomaly is a situation where the local worst-case does not necessarily lead to the global worst-case [16]. We do not support unbounded loops or unbounded recursion: the analysis has to be able to unroll all loops and inline function calls. Note that this is a common restriction for programs where a formal WCET analysis is applied. Our implementation is currently a proof-of-concept to show the feasibility of the approach, and makes simplifying assumptions: we assume the absence of cache which means that each load or store instruction issues an access to the shared bus, and we consider that each LLVM instruction takes 1 cycle. As future work, we intend to incorporate static cache and timing analysis tools, such as OTAWA [2], to include realistic execution time bounds for the instructions and to model the behavior of local caches.
To sum up, our contribution is a way to encode both the semantics of the program and a TDMA arbitration policy in a single SMT expression, and use it to compute a safe bound on the WCET of the program. The encoding is carefully optimized to avoid the performance issues of a naive encoding.
The rest of the paper is organized as follows: in Section 2, we give a background on TDMA buses and the SMT-based approach for WCET analysis. Section 3 explains how a program with accesses to a shared bus with a TDMA arbiter is modeled using SMT expressions. In Section 4, we evaluate our model using micro-benchmarks, then we apply our approach to benchmarks taken from real-life applications. Finally, related work is given in Section 5 and the conclusion and future work in Section 6. The examples with SMT expressions given in this paper are expressed in pseudo-code. In our experiments, we use SMT-LIBv2 [6] which provides standard descriptions of background theories used in SMT systems.
2. BACKGROUND
Multi-core platforms offer capabilities that respond to the growing performance demands of embedded real-time systems. However, predictability of these architectures remains a challenge. Shared resources represent the main hot topic in the predictability of such systems. In this work we are interested in shared buses with Time Division Multiple Access arbitration policy.
2.1 Time Division Multiple Access (TDMA)
Time Division Multiple Access (TDMA) is an arbitration policy for shared buses. It allows cores to share a bus by dividing the accesses into time slots. Cores may receive different slot lengths or different number of slots in a period which gives more or less priority to some cores over the others. In our work we consider a TDMA policy where each core receives one slot per period. Figure 1 illustrates an example of a TDMA bus with 3 slots associated to 3 cores. In a period of time $\pi$, each core receives a slot of length $\sigma$. The duration
Figure 1: Bus arbitration with Time Division Multiple Access policy seen from the viewpoint of core A.
Algorithm 2 Example of a code fragment with bus accesses.
\[
\begin{align*}
\text{function example}(x, y, \text{flag}) \quad & \quad \text{if } y < 0 \text{ then} \\
& \quad \quad \quad x \leftarrow x + 1 \\
& \quad \text{else} \\
& \quad \quad \quad flag \leftarrow flag + 10 \\
& \quad \text{end if} \\
& \quad \text{if } y \geq 0 \text{ then} \\
& \quad \quad \quad x \leftarrow x + 2 \\
& \quad \text{end if} \\
& \quad \text{return flag} \\
\end{align*}
\]
of an access to the bus is $acc$. An access cannot be split over several slots and is processed only if the remaining time in the slot is sufficient. A request is processed only during its dedicated slot. $req_{A,1}$ is a bus request issued by core A during its associated communication slot. This request is executed directly within a time duration $acc$. $req_{A,2}$ is an example of a request issued outside the allowed communication slot. It is, thus, stalled until the next slot of core A. Its execution time is given by $T = \pi - (t \mod \pi) + acc$. Where $t$ is the absolute time, i.e., starting from the beginning of the execution of the analyzed program. The best case delay is when the request is issued during the slot and granted directly. In the worst-case, the request is issued when there is not enough remaining time to process it. Hence, the execution delay of a bus access varies between $[acc, \pi - (\sigma - acc)]$.
We define the offset as $offset = t_{req} \mod \pi$. $t_{req}$ is the instant in time when the request is issued. A request is granted immediately, only if the offset at the issue instant falls in the communication slot’s interval. Otherwise it is delayed until the next slot of the core. Expressing the timing of the bus in offsets simplifies the bus model since the possible values of the offsets are in $[0, \pi]$. The analyzed program can start at any offset on the TDMA period. We can indicate an initial interval or a set of values of offsets in the SMT expressions. For the simplicity of our proof-of-concept implementation, we suppose that all programs start initially at offset=0. In a real application we should consider all possible values of the offset.
2.2 WCET for TDMA Accesses: an Example
To illustrate the timing behavior of a TDMA bus, consider Algorithm 2. It is a simple example with two conditions and two accesses to the shared bus.
We consider each instruction to be executed in 1 processor cycle and assume that each load and store instructions access the shared bus. The shared bus has a TDMA period $\pi=$
Figure 2: WCET of Algorithm 2 (CFG in Figure 3) with a shared TDMA bus with period $\pi=6$ and $\sigma=2$
Taking into account the parameters of the bus, a request emitted at offsets 0 or 1 is granted directly. Otherwise it is suspended until the next slot. The Control-flow graph (CFG) in Figure 3 shows two feasible paths: the first path $(y < 0)$ \{b1, b2, b3, b5, b8\} and the second path $(y \geq 0)$ \{b1, b4, b5, b6, b7, b8\}. Figure 2 shows both feasible paths and their execution times. We suppose that the program starts at instant $t=0$ and offset=0. In the case of the first execution path, block (2) emits an access request, load instruction, at offset 2. This request is delayed until the next slot. The execution time of this path is 18 processor cycles. The second execution time has 15 processor cycles. In this case the worst-case execution time of Algorithm 2 is $max(15,18) = 18$ processor cycles.
A micro-architectural analysis that does not take the semantics of the program into account would have to consider the infeasible path \{b1, b2, b3, b5, b6\} when considering the load $x$ instruction in block b6. This path would execute the load instruction with an offset of 5, hence not in the TDMA slot. As opposed to this, our analysis proves that the access is in the TDMA slot, and gives a tighter WCET.
2.3 WCET By SMT
Henry et al. [9] demonstrate how to measure the worst-case execution time using Bounded Model Checking. An SMT expressions is generated to encode the analyzed program and its execution time. The expressions mean: "Is there a path that satisfies the semantics and has an execution time greater than $T"?" The solution of this statement represents an execution path in the program with a constraint on the execution time. An SMT-solver is a program used to resolve the SMT expressions to answer the aforementioned question.
In [9], the authors use a binary search method to find an upper bound of the execution time and disprove the existence of a solution with an execution time greater than the WCET. The semantics of the program can be used in determining feasible paths. A Boolean variable is assigned to each basic block and each transition. A basic block $b_i$ is executed if any of its entering transitions is taken, i.e. $b_i = \bigvee_{k \in J_i} t_{k,i}$. Note that loops and recursive function calls are not supported in this initial work. The compiler must unroll the loops and inline function calls.
To illustrate the SMT encoding, we use the example of block (3) from Figure 4. $b_3$ is a Boolean assigned to block (3). This basic block is executed if any of the entering transitions is taken. Let $t_{1,3}$ and $t_{2,3}$ be the Booleans associated to the transitions from block (1) to (3) and from block (2) to (3) respectively. The generated SMT expression is:
$$b_3 = (t_{1,3} \lor t_{2,3})$$
The outgoing transitions are obtained from the condition $(y < 0)$. The transition $t_{3,4}$ is taken when the condition is true, $t_{3,5}$ is taken otherwise. This gives the following expressions:
$$y_{cmp} = (y < 0)$$
$$t_{3,4} = (b_3 \land y_{cmp})$$
$$t_{3,5} = (b_3 \land \neg y_{cmp})$$
In Figure 3, the control-flow graph of Algorithm 2.
3. SMT-BASED ANALYSIS FOR TDMA
In this section, we explain how the SMT model is extended to encode accesses to a shared bus with TDMA arbitration policy. In this work we consider the first slot $[0,\sigma]$ to be associated to the core on which the analyzed program is executed. In order to simplify the analysis, we transform the control-flow graph (CFG) so that the basic blocks access the shared bus at most once and only at their first instruction. Due to this, we will refer to the basic blocks in the transformed CFG simply as blocks. Figure 5 illustrates this transformation: Considering that load and store instructions access the shared bus, block(0) is split into block(0.1) and block(0.2). Each block starts with a load or a store instruction.
We extend the work of [9] to include the model of the shared bus accesses. This model is given in Section 3.1. Introducing the access delays implies modifications in the SMT encoding of the execution time from the previous work. We explain the timing encoding in presence of bus delays in Section 3.2.
3.1 Shared Bus Model
Here we explain the SMT model of an access to a shared bus with a TDMA arbiter. A TDMA arbitration policy is determined by its period $\pi$ and slot length $\sigma$. The delay of a bus access at the exit of a block $T_{exit}$ is determined according to the instant of the request emission at the entry of the block $T_{entry}$.
A naive implementation of the bus access model computes first the offset from $T_{entry}$, i.e., $(T_{entry} \mod \pi)$. Then, it checks if the offset falls in the communication slot. Algorithm 3 gives the pseudo code of a straightforward encoding in SMT of the bus access delay. The function $tdma_{access}$ takes as argument the time instant of a bus access request and finds its offset relative to the start of the TDMA period. We then check whether the current offset falls in the allowed communication slot. In this case, the access request is directly granted and the function returns the time of the entry plus the access delay and the execution time of the remaining instructions that do not access the bus: $T_{exit} = (T_{entry} + acc + cost)$. Otherwise, the request is delayed until the next slot and the function returns $T_{exit} = \pi + (T_{entry} - off_{entry}) + acc + cost$.
This method raises performance issues for the SMT-solver, caused by the use of the non-linear operator $mod$. Instead of modeling the absolute time through the program, we model only the offsets. The offset $off$ is defined by $off = (T \mod \pi)$. Algorithm 4 gives the definition of $tdma_{access}$ that returns the delay after a bus access with values in the interval $[acc, acc + (\pi - \sigma)]$. Another function $tdma_{offset}$, given in Algorithm 5, returns the offset after a bus access with values in the interval $[0,\sigma]$. Algorithms 4 and 5 are explained in Section 3.2.2.
Figure 4: Example of a basic block with a join and a condition
Figure 5: Basic blocks are split such that only a single bus access occurs at the beginning of the block
\begin{algorithm}[H]
\caption{Naive version of $tdma_{access}$: returns the absolute time after a bus access}
\begin{algorithmic}
\Require time: $T_{entry}$, execution time of the block: $cost$
\State $off_{entry} \leftarrow T_{entry} \mod \pi$
\If{$off_{entry} < \sigma$}
\State $T_{entry} + acc + cost$
\Else
\State $T_{entry} + (\pi - off_{entry}) + acc + cost$
\EndIf
\end{algorithmic}
\end{algorithm}
\begin{algorithm}[H]
\caption{$tdma_{access}$: returns the delay after a bus access}
\begin{algorithmic}
\Require $off_{entry}$, execution time of the block: $cost$
\If{$off_{entry} \in [0,\sigma - acc]$}
\State $return \; cost + acc$
\Else
\State $return \; cost + (\pi - off_{entry}) + acc$
\EndIf
\end{algorithmic}
\end{algorithm}
\begin{algorithm}[H]
\caption{$tdma_{offset}$: returns the offset after a bus access}
\begin{algorithmic}
\Require $off_{entry}$, execution time of the block: $cost$
\If{$off_{entry} \in [0,\sigma - acc]$}
\State $new_{off} \leftarrow off_{entry} + acc + (cost \mod \pi)$
\Else
\State $new_{off} \leftarrow acc + (cost \mod \pi)$
\EndIf
\If{$new_{off} \geq \pi$}
\State $return \; new_{off} - \pi$
\Else
\State $return \; new_{off}$
\EndIf
\end{algorithmic}
\end{algorithm}
3.2 Timing Encoding
In this section, we explain how the timing is encoded with SMT. The assumption made previously on the form of the CFG implies that blocks either access the shared bus or not. The blocks access the shared bus only at the first
instruction. The timing encoding should take into account such configuration.
3.2.1 Blocks Without Bus Accesses
The encoding of blocks that do not access the shared bus comes straightforward from the previous work by Henry et al. [9]. A variable \( c_{\Delta j} \) is associated to each transition between blocks \( i \) and \( j \). The worst-case execution time of each block is constant considering our assumption of a fully timing composable architecture:
\[
c_{\Delta j} = \text{if } \ell_{i,j} \text{ then } \text{wcet}_i \text{ else } 0
\]
The expression means: if the transition from block \( i \) to block \( j \) is taken, \( c_{\Delta j} \) is equal to the worst-case execution time of block \( i \), otherwise it is equal to 0.
The encoding of accesses to the shared TDMA bus requires knowledge about the offsets. These offsets are computed at each exit point of a block in the CFG. The function \( \text{get-offset} \) in Algorithm 6 is used to find the offset after a block that does not access the shared bus. This function takes the offset \( \text{off}_{\text{entry}} \) at the entry of the block and the execution time \( \text{cost} \) of the block. The \( \text{mod} \) operator in line 2 is used to find the offset after \( t \) time. This operator does not cause performance issues because its operands \( \text{cost} \) and \( \pi \) are known constants.
Let \( i \) and \( j \) be the indices of two blocks such that block \( j \) is a direct successor to block \( i \). Let \( N \geq 1 \) the number of direct predecessor of block \( i \). A first encoding of the offset between block \( i \) and block \( j \) is the SMT expression:
\[
\text{off}_{i,j} = \text{get-offset}( \text{if } \ell_{i,i} \text{ then } \text{off}_{i,i} \text{ else if } \ell_{i,i} \text{ then } \text{off}_{i,i} \text{ else } \ldots \text{ else if } \ell_{N,i} \text{ then } \text{off}_{N,i} \text{ else 0}), \text{wcet}_i)
\]
We refer to this encoding as “if..then..else” encoding below. This expression means that the offset between block \( i \) and block \( j \) is computed using the offset of the corresponding entering transition in case there are many predecessors. Another possible encoding (referred to as “sum” encoding) avoids using the nested \( \text{if}..\text{then}..\text{else} \) sequences in the SMT expression by using a \( \sum \) instead. We give such encoding as follows:
\[
\text{off}_{i,i} = \text{get-offset}(\sum_{k=1}^{N} \text{off}_{k,i}, \text{wcet}_i)
\]
\[
\text{off}_{i,j} = \text{if } \ell_{i,j} \text{ then } \text{off}_{i,j} \text{ else } 0
\]
\( \text{off}_{i,j} \) is an intermediate variable to encode the offset at the exit of block \( i \). \( \text{off}_{k,i} \) are the offsets associated to the entering transitions from blocks \( k \) to block \( i \). Only one entry transition is taken in a specific execution path. Let \( n \) be a block in an execution path \( P \):
\[
\begin{cases}
t_{k,i} = \text{false}, \text{off}_{k,i} = 0, & \forall k \neq n. \\
t_{k,i} = \text{true}, \text{off}_{k,i} \in [0, \pi], & k = n
\end{cases}
\]
This means that at most one entering offset is not null which implies that the sum of all entering offsets equals the offset at the entry of the block in an execution path. We apply this to block (3) in Figure 4. \( \text{wcet}_3 \) is the execution time of block (3). The offsets \( \text{off}_{3,4} \) and \( \text{off}_{3,5} \) at the exit of block (3) are encoded by:
\[
\text{off}_{3,4} = \text{get-offset}(\text{off}_{2,3} + \text{off}_{1,3}), \text{wcet}_3)
\]
Algorithm 6 \( \text{get-offset} \): returns the offset after a block without bus accesses
**Require:** offset \( \text{off}_{\text{entry}} \), execution time of the block \( \text{cost} \)
1. new \( \text{off} \) ← \( \text{off}_{\text{entry}} \) + (\( \text{cost} \text{ mod } \pi \))
2. if new \( \text{off} > \pi \) then
3. return new \( \text{off} - \pi \)
4. else
5. return new \( \text{off} \)
6. end if
\[
\text{off}_{3,4} = \text{if } \ell_{3,4} \text{ then } \text{off}_{3} \text{ else 0}
\]
\[
\text{off}_{3,5} = \text{if } \ell_{3,5} \text{ then } \text{off}_{3} \text{ else 0}
\]
3.2.2 Blocks With Bus Accesses
Blocks that access the shared bus should take into account the delay caused by the arbitration policy. The function \( \text{tdma-access} \) in Algorithm 4 returns the execution time of a block taking into account the offset at its entry (\( \text{off}_{\text{entry}} \)) and the execution time of the remaining instructions (\( \text{cost} \)). In line 1, it checks whether the current offset \( \text{off} \) falls in the communication slot. In this case, the request is granted and the returned time at the exit of the block is given by \( T_{\text{exit}} = \text{acc} + \text{cost} \). In the other case, \( T_{\text{exit}} = (\pi - \text{off}_{\text{entry}}) + \text{acc} + \text{cost} \).
The function \( \text{tdma-offset} \), in Algorithm 5, returns the offset at the exit of a block that accesses the bus. This function takes as inputs the offset at the entry of the block \( \text{off}_{\text{entry}} \) and the execution time \( \text{cost} \) of the remaining instructions that do not access the bus. It computes the new offset at the exit block which is \( \text{off}_{\text{entry}} + \text{acc} + \text{cost} \text{ mod } \pi \), if the \( \text{off}_{\text{entry}} \) falls in the communication slot, and \([0, \pi - \text{acc}] \) or \( \text{acc} + (\text{cost mod } \pi) \) otherwise. Since the offset values can only be in the interval \([0, \pi]\), The modulo operation is computed using \( \text{if}..\text{then}..\text{else} \) instructions (see lines 6 to 10) to avoid the non-linear instruction \( \text{mod} \).
The execution time and the offset at the exit of a block are encoded in a similar way as blocks without accesses to shared bus. Here is how the functions defined in Figure 4 are used:
\[
c_{\Delta i} = \text{tdma-access}(\sum_{k=1}^{N} \text{off}_{k,i}, \text{wcet}_i)
\]
\[
c_{\Delta i,j} = \text{if } \ell_{i,j} \text{ then } c_{\Delta i} \text{ else 0}
\]
\[
\text{off}_{i,j} = \text{tdma-offset}(\sum_{k=1}^{N} \text{off}_{k,i}, \text{wcet}_i)
\]
\[
\text{off}_{i,j} = \text{if } \ell_{i,j} \text{ then } \text{off}_{i,j} \text{ else 0}
\]
\( \text{wcet}_i \) is the worst-case execution time of the remaining instructions after the instruction that access the shared bus.
### 3.3 Adding Cuts to the SMT Expression
Experiments show a poor performance of the SMT-solver while searching for the WCET on the expression without further optimization. The same issues were observed and addressed in [9]. cuts are additional clauses that add no information but allow the SMT-solver to prune a very large number of partial traces from the decision tree.
Knowing that the offsets can only have the values in \([0, \pi]\] and block \( i \) does not access the bus, it computes the new offset \( \text{off}_{i,j} \) falls in the communication slot, and \([0, \pi - \text{acc}] \) or \( \text{acc} + (\text{cost mod } \pi) \) otherwise. Since the offset values can only be in the interval \([0, \pi]\), The modulo operation is computed using \( \text{if}..\text{then}..\text{else} \) instructions (see lines 6 to 10) to avoid the non-linear instruction \( \text{mod} \).
The execution time and the offset at the exit of a block are encoded in a similar way as blocks without accesses to shared bus. Here is how the functions defined in Figure 4 are used:
\[
c_{\Delta i} = \text{tdma-access}(\sum_{k=0}^{N} \text{off}_{k,i}, \text{wcet}_i)
\]
\[
c_{\Delta i,j} = \text{if } \ell_{i,j} \text{ then } c_{\Delta i} \text{ else 0}
\]
\[
\text{off}_{i,j} = \text{tdma-offset}(\sum_{k=0}^{N} \text{off}_{k,i}, \text{wcet}_i)
\]
\[
\text{off}_{i,j} = \text{if } \ell_{i,j} \text{ then } \text{off}_{i,j} \text{ else 0}
\]
\( \text{wcet}_i \) is the worst-case execution time of the remaining instructions after the instruction that access the shared bus.
4. IMPLEMENTATION AND EVALUATION
Our implementation relies on PAGAI [10], a tool used for modeling programs to SMT expressions. It is used by Henry et al. [9] to estimate the worst-case execution time through semantic encoding with SMT expressions. PAGAI uses an intermediate representation based on the CFG obtained from LLVM\(^1\). Due to this constraint, our tests and proof-of-concept implementation use the intermediate representation instead of the executable binary. We explain in Section 6 how a realistic analysis can be achieved.
Figure 6 shows the work flow of the proof-of-concept. The source code is compiled with CLANG to generate LLVM bitcode. A number of optimization passes are then executed. The interesting pass in our case is the one that transforms the CFG as discussed in Section 3. PAGAI is then run on the transformed CFG, which is a bitcode file, to generate the SMT expressions of the program.
We implemented an LLVM optimization pass that transforms the CFG to fit our analysis. It splits blocks before each instruction accessing the bus, so that each block contains at most one such instruction, which must be the first of the block. Figure 3 shown in Section 2.2 is the CFG obtained after this transformation.
We use the SMT-solver Z3 [7]. Z3 offers a C API that is used in our binary search program. The SMT-solver parses the SMT expressions and answers with SAT, UNSAT or, UNDEF. In case of SAT, the SMT-solver gives a model of a solution that satisfies the SMT expression. We use this model to refine the binary search. For example, we look for an execution time in the interval \([X_0, Y_0]\). The binary search algorithm checks whether the execution time is greater than \(X_0 + Y_0\). If UNSAT is returned, the new search interval is \([X_1 = X_0, Y_1 = X_0 + Y_0]\). If SAT is returned, the SMT-solver gives a model with an execution time \(Z \in \{X_0 + Y_0, Y_0\}\). The new search interval in this case is \([X_1 = Z, Y_1 = Y_0]\). The search continues until it reaches an interval \([X_n, Y_n]\) where \(X_n = Y_n\).
This approach, when applied to Algorithm 2, gives the correct and optimal worst-case execution time of 18 processor cycles after 6 iterations of the binary search. The output of the binary search is:
\[
\text{Testing } \text{wct} \geq 0 \ldots \text{ SAT (value found } = 18). \quad \text{New interval } = [18, 73].
\]
\[
\text{Testing } \text{wct} \geq 46 \ldots \text{ UNSAT. New interval } = [18, 45].
\]
\[
\text{Testing } \text{wct} \geq 32 \ldots \text{ UNSAT. New interval } = [18, 31].
\]
\[
\text{Testing } \text{wct} \geq 25 \ldots \text{ UNSAT. New interval } = [18, 24].
\]
\[
\text{Testing } \text{wct} \geq 21 \ldots \text{ UNSAT. New interval } = [18, 20].
\]
\[
\text{Testing } \text{wct} \geq 19 \ldots \text{ UNSAT. New interval } = [18, 18].
\]
\[
\text{The maximum value of wct is } 18.
\]
\[
\text{Computation time is } 0.010000s.
\]
In the following, we evaluate our model of the shared TDMA bus. First we propose a micro-benchmark to compare the results of the naive implementation of \textit{tdma}\textit{-access} and the offset-based implementation. Then we show how the semantics encoding combined with a TDMA bus model can enhance the WCET estimation using (i) a toy example to illustrate the differences and (ii) real-world applications.
\(^1\)LLVM is a compilation framework with an intermediate representation (http://www.llvm.org)
4.1 Performance of SMT Encodings for TDMA
4.1.1 TDMA Functions
We now evaluate the analysis time of our model. A simple approach is to evaluate the analysis time on a linear path, i.e. without branches. The blocks are simple and have only one instruction each. Figure 7 shows a comparison of the different setups. We compare the naive implementation and the offset-based implementation of \textit{tdma}\textit{-access} on a CFG that contains only blocks with accesses to the shared bus. The naive implementation has an exponential growth of the analysis time. At only 25 blocks, it takes 17656s for the binary search with the SMT-solver to find the WCET. Whereas, it takes only 0.44s in the case of the offset-based implementation. This is mainly due to the non-linear mod operator used in the naive implementation. The line \textit{“0% access”} represents a CFG composed with blocks that do not
access the shared bus which analyze `get_offset`.
### 4.1.2 Offset Encoding
Figure 8: Example of a diamond formula
We now compare the two encodings explained in sections 3.2.1 and 3.2.2. Figure 8 shows an example with one if condition which will generate a “diamond formula” in SMT. We compare the analysis time of the nested `if..then..else` encoding against the `sum` encoding of an increasing number of sequences of “diamond formulas” in the analyzed program. Figure 10 shows the results for execution time of the analysis when `Block A` and `Block B` in Figure 8 access the shared TDMA bus. Both encodings have almost the same analysis time with a slight advantage of the `sum` encoding. To investigate further, we analyze the program represented in Figure 9. The loop bound is 100 iterations which will generate, when the loop is unrolled, a block with 100 entering transitions. We analyze programs with `N` sequences of the same loop. Figure 11 shows the analysis time of the encodings with `N` in `{1..10}. The `sum` encoding shows better performance than the nested `if..then..else` encoding. For the rest of the experiments, we will use the `sum` encoding.
Figure 9: Example of a program with a loop
Figure 10: Comparison of nested `if..then..else` (ite) and `sum` encoding of sequences of `if..then..else` (Figure 8). TDMA bus (`σ = 40, π = 160, acc = 10`)
Figure 11: Comparison of nested `if..then..else` (ite) and `sum` encoding of sequences of loops with 100 iterations (Figure 9). TDMA bus (`σ = 40, π = 160, acc = 10`)
### 4.2 Realistic Benchmarks
#### 4.2.1 Experimental Setup
We evaluate our approach with a subset of the TacleBench\(^2\) benchmarks. The benchmarks are compiled with CLANG 3.6 to generate the LLVM bitcode. Loops are unrolled with an optimization pass of LLVM. The SMT expression is generated following the workflow in Figure 6. The examples are illustrated in Table 1 where “#LLVM instr.” refers to the number of the instructions in the LLVM bitcode after inlining and unrolling functions and loops. “#bus access” represent the total number of `load` and `store` instructions since we consider an architecture without a cache memory. The LLVM bitcode has more instructions compared to the binary executable. Some `load` and `store` instructions in the LLVM bitcode do not exist in the executable binary which makes a direct comparison with other approaches irrelevant.
\(^2\)http://tacle.knossosnet.gr/activities/taclebench
However, our proof of concept allows to demonstrate the feasibility of the SMT-based approach. The analysis is run under Linux Debian, on an Intel® Core® i5-3470 at 3.20 GHz with 8GB of main memory. We consider each instruction to execute in 1 processor cycle and the platform has no cache memory.
\subsection{4.2.2 Results}
The TDMA policy statically isolates programs in their respective slots which means that the analysis for each program is independent from the other programs. We therefore run the analysis for individual programs, but the results hold in a context where several programs are executed in parallel.
We compare the WCET of the offset-based analysis with the pessimistic WCET where all accesses to the shared bus are considered worst-case. This implies that each load and store instructions have an execution time of \( \pi - \sigma + 2 \cdot acc - 1 \). Similarly to [13], the improvement is defined as \( \frac{"WCET_{pess}"}{"WCET"} - 1 \).
We analyze different configurations of the TDMA bus. The results are illustrated in Tables 2, 3, 4, 5, and 6. The improvements we obtain from the offset-based analysis are proportional to the slot length and the period of the TDMA bus. The results also show that the greater the slot length is, the greater the improvement. This is expected since more accesses can be executed in the same slot. A greater TDMA period increases the pessimistic WCET. The highest improvement is 217.95\% of the bs benchmark (231 LLVM instructions) in Table 5 with \( \pi = 400, \sigma = 200, acc = 40 \).
Table 7 represents the lowest and highest observed analysis times. The offset encoding increases the analysis time of programs. The pessimistic WCET of benchmark fly-by-wire, from the PapaBench suite, is obtained in 4.02 seconds. The offset-based encoding has an analysis time of 149.01 seconds (\( \pi = 400, \sigma = 100, acc = 40 \)). Despite the effort to linearize the SMT functions used to model the TDMA bus access, they are still very costly. The analysis time depends on the number of accesses to the shared bus as well as the number of “diamond formulas” which appears at the encoding of sequences of if..then..else.
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Name} & \textbf{Description} & \textbf{#LLVM instr.} & \textbf{#bus access} \\
\hline
bs & Binary search & 231 & 12 \\
insertsort & Insertion sort on a reversed array & 493 & 65 & \\
jfdctint & Discrete Cosine Transformation & 2334 & 448 & \\
fdct & Fast Discrete Cosine Transform & 2502 & 385 & \\
compressdata & Data compression program adopted from SPEC95 & 674 & 131 & \\
fly-by-wire & UAV fly-by-wire software & 2815 & 515 & \\
\hline
\end{tabular}
\caption{Benchmarks}
\end{table}
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Name} & \textbf{WCET_{pess}} & \textbf{WCET} & \textbf{Improvement} \\
\hline
bs & 328 & 261 & 25.67\% \\
insertsort & 1331 & 1313 & 1.37\% \\
jfdctint & 19544 & 17893 & 9.22\% \\
f dct & 17296 & 16012 & 8.01\% \\
compressdata & 2651 & 2275 & 16.48\% \\
fly-by-wire & 6201 & 5708 & 8.63\% \\
\hline
\end{tabular}
\caption{\( \pi = 40, \sigma = 20, acc = 10 \)}
\end{table}
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Name} & \textbf{WCET_{pess}} & \textbf{WCET} & \textbf{Improvement} \\
\hline
bs & 448 & 261 & 71.64\% \\
insertsort & 1951 & 880 & 121.70\% \\
jfdctint & 28504 & 13213 & 115.72\% \\
f dct & 24996 & 11545 & 116.56\% \\
compressdata & 3790 & 1865 & 103.21\% \\
fly-by-wire & 9061 & 4312 & 110.13\% \\
\hline
\end{tabular}
\caption{\( \pi = 80, \sigma = 40, acc = 10 \)}
\end{table}
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Name} & \textbf{WCET_{pess}} & \textbf{WCET} & \textbf{Improvement} \\
\hline
bs & 1108 & 556 & 117.95\% \\
insertsort & 4431 & 1760 & 151.76\% \\
jfdctint & 64444 & 26413 & 143.60\% \\
f dct & 55796 & 23065 & 141.90\% \\
compressdata & 8550 & 3705 & 125.37\% \\
fly-by-wire & 20501 & 8082 & 136.13\% \\
\hline
\end{tabular}
\caption{\( \pi = 160, \sigma = 40, acc = 10 \)}
\end{table}
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Name} & \textbf{WCET_{pess}} & \textbf{WCET} & \textbf{Improvement} \\
\hline
bs & 1768 & 556 & 217.95\% \\
insertsort & 8771 & 3263 & 168.80\% \\
jfdctint & 127064 & 44578 & 185.03\% \\
f dct & 109696 & 38442 & 185.35\% \\
compressdata & 16330 & 5799 & 181.60\% \\
fly-by-wire & 40521 & 14196 & 185.35\% \\
\hline
\end{tabular}
\caption{\( \pi = 400, \sigma = 200, acc = 40 \)}
\end{table}
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|l|l|}
\hline
\textbf{Name} & \textbf{WCET_{pess}} & \textbf{WCET} & \textbf{Improvement} \\
\hline
bs & 2368 & 1251 & 89.28\% \\
insertsort & 11871 & 6463 & 83.67\% \\
jfdctint & 171864 & 89288 & 92.48\% \\
f dct & 148196 & 76842 & 92.85\% \\
compressdata & 22030 & 12455 & 76.87\% \\
fly-by-wire & 54821 & 29258 & 87.37\% \\
\hline
\end{tabular}
\caption{\( \pi = 400, \sigma = 100, acc = 40 \)}
\end{table}
\begin{table}[h]
\centering
\begin{tabular}{|l|l|l|}
\hline
\textbf{Name} & \textbf{\(<40,20,10>\)} & \textbf{\(<400,100,40>\)} \\
\hline
bs & 0.45 & 0.98 & \\
insertsort & 1.37 & 6.56 & \\
jfdctint & 14.10 & 48.54 & \\
f dct & 31.46 & 34.57 & \\
compressdata & 4.66 & 3.23 & \\
fly-by-wire & 28.78 & 149.01 & \\
\hline
\end{tabular}
\caption{Analysis time, in seconds, of the benchmarks with different configurations of the TDMA bus \( \pi,\sigma,acc \)}
\end{table}
5. RELATED WORK
Chattopadhyay et al. [5] improves the analysis cost of loops by aligning each loop head execution with the TDMA period. A penalty term is added to the WCET of each loop. This allows a better scaling of the analysis at the cost of the precision. The approach by Kelter et al. offers a compromise for loop analysis by modeling the offsets in the TDMA bus with an ILP problem. The proposed solution gives a tighter estimation of the WCET compared to the pessimistic approach. Considering bounded loops, the authors gives two methods to estimate the WCET in presence of a TDMA bus with minimal unrolling. The first method unroll the loop until a fix point of offsets is reached. The second method uses dynamic flow graphs to model loops.
Schranzhofer et al. [18] propose an efficient analysis of the worst case response time (WCRT) of a shared TDMA bus. The proposed framework uses the access model in periodic tasks to analyze the worst-case response time of the bus and schedulability of tasks. By separating accesses to the bus and computations, this approach exhibits tighter bounds and reduces the WCRT.
Other research works were done to improve the WCET estimation with a shared bus. Gustavsson et al. [8] use timed automata to model the software and the hardware. An upper bound on the clock of the timed automata is obtained with Model Checking tools such as UPPAAL [3]. This approach suffers from a potential explosion in the number of automata's states. Lv et al. [13] propose a better use of timed automata. With an abstract interpretation of the cache, basic blocks in the CFG are annotated with cache miss and cache hit. A model with timed automata is associated according to the annotations. Arbitration policy of the shared bus is also modeled with an automata. The results show a better estimation on the WCET compared with the pessimistic approaches.
All of the mentioned related works give improvements on the upper bound of the execution time. However, they only estimate the WCET considering an already known feasible path obtained from the semantics. Our approach does both the infeasible path analysis and the TDMA model in the same step. Using an SMT expression allows our approach to consider all feasible path without having to enumerate them individually. Our approach is more precise, but more costly. It can be used in a complementary way with other approaches in a trade-off between quality of the results and analysis time. We discuss possible approaches for loop analysis in Section 6.2.
6. CONCLUSION
6.1 Summary
We introduce a new approach for WCET analysis of shared TDMA bus using Satisfiability Modulo Theory (SMT). This approach takes into account the semantics and the accesses to a shared TDMA bus to give a tighter estimation of the execution time. In our proof-of-concept, we consider a platform without cache memory which means that all load and store instructions access the shared bus. We also analyze programs in the form of LLVM bitcode due to the constraints imposed by the tool PAGAI. This is a limitation of our implementation, but not of the approach itself: the same approach can be applied to executable binaries given a generated model in SMT and with the presence of cache memory. Accesses to the bus can be obtained from an analysis of the cache's state where a cache miss is considered as an access to the shared memory through the shared bus.
The naive model of the TDMA bus shows poor performance. To overcome the issue, we propose an offset based model. The micro-benchmarks show a better scalability but remains exponential. The added cuts on the offsets improve the analysis time by indicating to the SMT-solver “obvious” properties.
Finally, we show that the micro-architectural analysis of the shared TDMA bus, and the semantic analysis can be combined in one approach using an SMT model. This approach can achieve a more precise estimation of the WCET in presence of a shared TDMA bus. The naive encodings are very costly. We give alternative encodings that reduce considerably the solving time of the SMT expression.
6.2 Future Work
The current implementation of our approach is a proof of concept to check its viability and scalability. As such, taking into account a realistic model for the timing of the program is left to future works. Considering that each LLVM instruction takes exactly one cycle is clearly not realistic: the timing for each block should instead come from a micro-architectural analysis of the actual binary with a tool like OTAWA [2]. Keeping the analysis itself on LLVM bitcode allows exploiting high-level properties of the program that would be lost at the binary code level, and the SSA form of the bitcode greatly simplifies the encoding into SMT. As a consequence, a complete tool for a realistic analysis would need to work both on the binary code and the LLVM bitcode. The information obtained on the binary must be mapped to the LLVM bitcode. One solution to achieve this is through
pattern matching of conditions [4] between the LLVM CFG and the executable CFG. The overall approach for such an information flow is described in Figure 12. It has already been applied to SMT-based WCET analysis in [9]. The idea of combining high-level semantic information with low-level binary analysis has also already been applied in e.g. [12, 15].
Similarly, considering LLVM load and store operations as bus accesses is an oversimplification. Some LLVM load and store will actually be cache hits and will not access the bus, and conversely, some operations on LLVM registers will actually need to access the memory in the real program. The actual bus accesses must therefore be obtained by a prior cache analysis on the binary code.
Our experiments show scalability issues which is expected in NP-complete problems. We are considering optimizations and improvements in the scalability in future work. Our approach already shows substantial improvements over a naive encoding, and the results show that we do scale to reasonably-sized programs. Still, we would probably encounter performance issues in the SMT solver to scale if we try to analyze very large case-studies globally with this approach. We therefore need an approach that uses our analysis on reasonably-sized pieces of code extracted from a possibly larger codebase. One option is to analyze the program in portions and propagate the obtained results on a global analysis. For example, considering only a small piece of code surrounding a bus access may be sufficient to prove that this access is in the TDMA slot (or to prove a tight bound on its execution time), and this information can be injected in a global cheaper analysis. The challenge here is how one defines the analyzed portions and their sizes.
Loops with a large iteration count, which cannot be unrolled completely, could be handled using partial unrolling. Loop iterations are then analyzed separately with updated information on offsets between each iteration. Kelter et al. [11] already address the loop analysis with minimum unrolling. The SMT-based approach can be complementary to include the semantics in the loop body analysis.
7. REFERENCES
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01243244/file/rtns-2015.pdf", "len_cl100k_base": 12406, "olmocr-version": "0.1.48", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 41579, "total-output-tokens": 15006, "length": "2e13", "weborganizer": {"__label__adult": 0.0005102157592773438, "__label__art_design": 0.0005044937133789062, "__label__crime_law": 0.0005125999450683594, "__label__education_jobs": 0.0005688667297363281, "__label__entertainment": 0.0001183152198791504, "__label__fashion_beauty": 0.00022983551025390625, "__label__finance_business": 0.00039505958557128906, "__label__food_dining": 0.0004608631134033203, "__label__games": 0.0012531280517578125, "__label__hardware": 0.007080078125, "__label__health": 0.0007090568542480469, "__label__history": 0.0005221366882324219, "__label__home_hobbies": 0.0001666545867919922, "__label__industrial": 0.0010395050048828125, "__label__literature": 0.0002663135528564453, "__label__politics": 0.0004878044128417969, "__label__religion": 0.0007944107055664062, "__label__science_tech": 0.1910400390625, "__label__social_life": 8.147954940795898e-05, "__label__software": 0.00852203369140625, "__label__software_dev": 0.7822265625, "__label__sports_fitness": 0.0004875659942626953, "__label__transportation": 0.001537322998046875, "__label__travel": 0.0003275871276855469}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50330, 0.05643]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50330, 0.14252]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50330, 0.82846]], "google_gemma-3-12b-it_contains_pii": [[0, 996, false], [996, 5461, null], [5461, 11419, null], [11419, 14625, null], [14625, 19154, null], [19154, 27143, null], [27143, 31469, null], [31469, 33938, null], [33938, 39433, null], [39433, 44438, null], [44438, 50330, null]], "google_gemma-3-12b-it_is_public_document": [[0, 996, true], [996, 5461, null], [5461, 11419, null], [11419, 14625, null], [14625, 19154, null], [19154, 27143, null], [27143, 31469, null], [31469, 33938, null], [33938, 39433, null], [39433, 44438, null], [44438, 50330, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50330, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50330, null]], "pdf_page_numbers": [[0, 996, 1], [996, 5461, 2], [5461, 11419, 3], [11419, 14625, 4], [14625, 19154, 5], [19154, 27143, 6], [27143, 31469, 7], [31469, 33938, 8], [33938, 39433, 9], [39433, 44438, 10], [44438, 50330, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50330, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
08b364ae6d55d54c53fe21d566cdf4ee4263a43b
|
How Stable are Eclipse Application Framework Internal Interfaces?
John Businge*, Simon Kawuma*, Moses Openja*, Engineer Bainomugisha† and Alexander Serebrenik‡
*Mbarara University of Science and Technology, Mbarara, Uganda
†Makerere University, Kampala, Uganda
‡Eindhoven University of Technology, Eindhoven, The Netherlands
Abstract—Eclipse framework provides two interfaces: stable interfaces (APIs) and unstable interfaces (non-APIs). Despite the non-APIs being discouraged and unsupported, their usage is not uncommon. Previous studies showed that applications using relatively old non-APIs are more likely to be compatible with new releases compared to the ones that used newly introduced non-APIs; that the growth rate of non-APIs is nearly twice as much as that of APIs; and that the promotion of non-API to APIs happens at a slow pace since API providers have no assistance to identify public interface candidates.
Motivated by these findings, our main aim was to empirically investigate the entire population (2,380K) of non-APIs to find the non-APIs that remain stable for a long period of time. We employ cross-project clone detection to identify whether non-APIs introduced in a given Eclipse release remain stable over successive releases. We provide a dataset of 327K stable non-API methods that can be used by both Eclipse interface providers as possible candidates of promotion. Instead of promoting non-APIs which are too fine-grained, we summarized the non-API methods groups in given classes that are stable together and present class-level non-APIs that possible candidates promotion. We have shown that it is possible to predict the stability of a non-API in subsequent Eclipse releases with a precision of \(\geq 56\%\), a recall of \(\geq 96\%\) and an AUC of \(\geq 92\%\) and an F-measure of \(\geq 81\%\). We have also shown that the metrics of length of a method and number of method parameters in a non-API method are very good predictors for the stability of the non-API in successive Eclipse releases. The results provided can help the API providers to estimate a priori how much work could be involved in performing the promotion.
Index Terms—Eclipse; Framework; Internal Interfaces; Internal Interfaces Promotion; Internal Interfaces Stability; Software Evolution
I. INTRODUCTION
Application developers build their systems on top of frameworks and libraries [1]. Building applications this way fosters reuse of functionality [2] and increases productivity [3]. This is why large application frameworks such as Eclipse [4], MSDN [5], jBPM [6], JUnit [7] commonly provide public (stable) interfaces (APIs) to application developers.
In addition to public (stable) interfaces all these frameworks also provide internal (possibly unstable) interfaces (non-APIs). Eclipse, jBPM, JUnit, all adopt the convention of internal interfaces by using sub-string internal in their package names while JDK non-APIs packages start with the substring sun. Framework developers discourage the use of non-APIs because they may be immature, unsupported, and subject to change or removal without notice [4], [5], [7], [8]. Supporting these recommendations previous empirical studies have shown that when the Eclipse application framework evolves, APIs do not cause compatibility failures in applications that solely depend on them [9], while non-APIs cause compatibility failures in applications that depend on them [9], [10].
Despite the non-API being discouraged and causing compatibility failures, usage of non-APIs is not uncommon. Businge et al. have observed that about 44% of 512 Eclipse plug-ins use non-APIs [11], [12]; application developers claim that they cannot find APIs with the functionality they require among APIs and therefore feel compelled to use non-APIs [13].
Much as the developers discourage the use of non-APIs they do know that application developers use them. One example of non-API client usage known to the API providers is the non-API class org.eclipse.jdt.internal.corext.dom.NodeFinder.
On Bugzilla an Eclipse bug tracking forum a client requested that: NodeFinder class is part of the package org.eclipse.jdt.internal.corext.dom and provides very useful logic. Would be nice if the node finder (or a similar one) becomes part of the AST API (reported after the release of Eclipse 2.1 (25-20-2004)). After a series discussions and adaptations on NodeFinder over years, the interface providers promoted the NodeFinder to API package org.eclipse.jdt.core.dom during Eclipse release 3.6 (05-10-2009 six years later).
In a preliminary study of the non-APIs, Kawuma et al. [14] observed twice as many fully qualified non-API methods compared to APIs methods. As a solution to mitigate discussed risks and help client developers, API producers may promote some internal interfaces to public ones. However, Hora et al. [15] discovered that promotion occurs slowly causing a delay to client developers to benefit from stable and supported interfaces. The authors further state that slow promotion results from API producers having no assistance in identifying public interface candidates (i.e., internal interfaces that should be public). In this paper, using clone detection techniques, we study the stability of Eclipse internal interfaces over subsequent Eclipse releases. Our main aim is to detect internal interfaces that could be recommended to the API producers for promotion to public interfaces.
The remainder of this paper is organized as follows: Section II presents the background information on Eclipse Framework and its interfaces. Section III discusses the experimental setup of our study. We present our answers for the research questions in Sections IV and V. Section VI presents threats to the validity of our study, while Section VII provides an overview of the related work. Finally, Section VIII concludes the paper and outlines some avenues for future work.
II. BACKGROUND
Similarly to most of the previous studies of non-APIs we focus on Eclipse [9], [10], [11], [12], [13], [14], [15]. This section introduces the background related to Eclipse interfaces and to the context of the technique we use, software clones.
A. Eclipse Interfaces
Eclipse application framework provides two different types of interfaces.
Eclipse non-APIs: Non-APIs are internal implementation artifacts that according to Eclipse naming convention [4] are found in packages with the substring internal in the fully qualified name. These internal implementation artifacts include public Java classes or interfaces, or public or protected methods, or fields in such a class or interface. Usage of non-APIs is strongly discouraged since they may be unstable [6]. Eclipse clearly states that clients who think they must use these non-APIs do it at their own risk as non-APIs are subject to arbitrary change or removal without notice. Eclipse does not usually provide documentation and support to these non-APIs.
Eclipse APIs: These are public Java classes or interfaces found in packages that do not contain the segment internal in the fully qualified package name, a public or protected method, or field in such a class or interface. Eclipse states that, the APIs are considered to be stable and can be used by any application developer without any risk. Furthermore, Eclipse also provides documentation and support for these APIs.
B. Clone Terminology
We use clone detection techniques to determine the stability of a non-API method between subsequent Eclipse releases. Software clone detection is a well-established research area [17], [18]; in the remainder of the section we briefly introduce notions related to clone detection.
Code Fragment [17] is a sequence of code lines with or without comments. A code fragment is identified by its file name and begin-end line numbers in the original code base.
A code fragment CF2 is a clone of another code fragment CF1 if they are similar by some given definition of similarity. The pair (CF1; CF2) form then a clone pair. If multiple fragments are similar, they form a clone class or clone group [17].
Code Clone Types Depending on definition of similarity different clone types can be distinguished. In this study we consider code clones of Types I, II, & III [17]. Type-1 clones are identical code fragments except for variations in identifiers, literals, types, layout, and comments. Type-3 code clones are copies with further modifications, statements can be changed, added, or removed in addition to variations in identifiers, literals, types, layout, and comments.
C. Stability of non-APIs
In this section we formalize the notion of non-API stability. Def. 1: Let \( E_{old} \) and \( E_{new} \) be two Eclipse releases. We say a non-API method \( m \) is stable between \( E_{old} \) and \( E_{new} \), if \( m \) in \( E_{old} \) and \( m \) in \( E_{new} \) are a pair of Type-1 or Type-2 clones.
Since the inception with Eclipse 1.0, the Eclipse framework has been introducing a new release every year. Therefore, the non-APIs that have remained unchanged since Eclipse release 1.0 and still present in Eclipse 4.6 are now 15 years old.
Using the notion of stability we pose the following research questions.
RQ1 Are there stable non-API methods that could be candidates for promotion to APIs?
We hypothesize that the non-APIs that have not changed over subsequent Eclipse releases could be mature and therefore possible candidates of promotion to APIs. Using our methodology identify stability of the non-APIs at method-level as a way of identifying candidates for promotion. We understand that method-level non-APIs that are candidates of promotion may be too fine grained for recommendation. However, if we identify groups of methods in a class that are stable, then they could be together candidates for promotion at class-level.
RQ2 Can we predict whether a non-API will remain stable in subsequent Eclipse releases?
The results to this question can help the API providers to estimate a priori how much work could be involved in performing the promotion.
Contributions of our work are twofold:
1) A dataset of 327K stable non-API methods that can be used by Eclipse interface providers as possible candidates for promotion. Instead of promoting individual non-API methods which might be too fine-grained, we identify groups of non-API methods in given classes that are stable together. These groups are presented as possible candidates promotion.
2) We have shown that it is possible to predict the stability of a non-API in subsequent Eclipse releases with precision \( \geq 56\% \), recall \( \geq 96\% \), AUC \( \geq 92\% \) and the F-measure \( \geq 81\% \). We have also shown that the length of a method and the number of method parameters are very good predictors for the stability of the non-API method in successive Eclipse releases.
III. EXPERIMENTAL SETUP
Our study is based on all the 19 major releases of Eclipse SDK downloaded from the Archive website [19]. Details of the releases are summarized in Table I.
To answer the RQS we extract the data using the NiCad clone detection tool [20]. We opt for NiCad as it has also been extensively validated in the past [21], [22], [23]. When NiCad
Listing 1: Nicad Cross Clone Report
```xml
<clones>
<clone nlines="74" similarity ="100">
public void m1(C1 c1) { <source File="E_1.0/org/eclipse/p1/sp1/pk1/F1.java"/>
public void m1(C1 c1) { <source File="E_4.6/org/eclipse/p2/sp2/pk2/F2.java"/>
</clone>
<clone nlines="79" similarity ="100">
void m2(){ <source File="E_1.0/org/eclipse/p3/ internal/sp3/pk3/F3.java"/>
void m2(){ <source File="E_4.6/org/eclipse/p4/ internal/sp4/pk4/F4.java"/>
</clone>
<clone nlines="90" similarity ="100">
public C1 m3(){ <source File="E_1.0/org/eclipse/p5/ internal/sp5/pk5/F5.java"/>
public C1 m3(){ <source File="E_4.6/org/eclipse/p6/sp6/pk6/F6.java"/>
</clone>
</clones>
```
TABLE I: Eclipse major releases and their corresponding release dates
<table>
<thead>
<tr>
<th>Major Releases</th>
<th>Release Date</th>
<th>Major Releases</th>
<th>Release Date</th>
</tr>
</thead>
<tbody>
<tr>
<td>E-1.0</td>
<td>07-Nov-01</td>
<td>E-3.7</td>
<td>13-Jun-11</td>
</tr>
<tr>
<td>E-2.0</td>
<td>27-Jun-02</td>
<td>E-3.8</td>
<td>08-Jun-12</td>
</tr>
<tr>
<td>E-2.1</td>
<td>27-Mar-03</td>
<td>E-4.0</td>
<td>27-Jul-10</td>
</tr>
<tr>
<td>E-3.0</td>
<td>25-Jun-04</td>
<td>E-4.1</td>
<td>20-Jun-11</td>
</tr>
<tr>
<td>E-3.1</td>
<td>27-Jun-05</td>
<td>E-4.2</td>
<td>08-Jun-12</td>
</tr>
<tr>
<td>E-3.2</td>
<td>29-Jun-06</td>
<td>E-4.3</td>
<td>05-Jun-13</td>
</tr>
<tr>
<td>E-3.3</td>
<td>25-Jun-07</td>
<td>E-4.4</td>
<td>06-Jun-14</td>
</tr>
<tr>
<td>E-3.4</td>
<td>17-Jun-08</td>
<td>E-4.5</td>
<td>03-Jun-15</td>
</tr>
<tr>
<td>E-3.5</td>
<td>11-Jun-09</td>
<td>E-4.6</td>
<td>06-Jun-16</td>
</tr>
<tr>
<td>E-3.6</td>
<td>08-Jun-10</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Fig. 1: Evolution of the number of non-API methods (left y-axis) and their percentage (right y-axis).
is applied to the collection of the 19 releases of Eclipse, in addition to detecting clones it generates an XML report with a list of all methods in any given Eclipse release. Since non-API methods can be distinguished from API methods by having a substring `internal` in their fully qualified name, we counted the number of methods with substring `internal` in the XML report. We used this report to obtain the total number of non-API methods in each Eclipse release.
Figure 1 superimposes two charts—evolution of the number of non-API methods and of the percentage of non-API methods. The percentage of non-API methods shows a slow decrease. We determine the percentage of the non-API methods in a given Eclipse release as a ratio of the non-API methods to the total interfaces (i.e., APIs plus non-API methods). The number of non-API methods per releases shows a non-linear increasing trend in the different subsequent Eclipse releases.
IV. RQ1: STABILITY OF INTERNAL INTERFACES
With RQ1, we want to investigate if non-API methods released in earlier Eclipse releases remain stable in later Eclipse releases.
A. Data extraction for RQ1
Often later releases of Eclipse contain interfaces that were introduced in the earlier Eclipse releases. Therefore, before carrying out the Nicad clone detection, we first eliminate the old non-API methods in the new Eclipse release by locating the unchanged non-API in $E_{\text{new}}$ that were previously introduced $E_{\text{old}}$. This leaves only non-API methods newly introduced in $E_{\text{new}}$.
We illustrate the data collection for RQ1 using Figure 2 and Listing 1. For a given Eclipse release—R4, in Step 1 of Figure 2 we identify files from R4 absent from earlier releases R1–R3, i.e., the shaded area R4’. Next, in Step 2 we subject R4’ and a later Eclipse release, say R5, to Nicad cross-project clone detection. Nicad reports clones similarly to the report in Listing 1. Using different Nicad configurations, the tool is able to produce Type-1 and Type-2 clone reports.
Listing 1 is an example of fragment of the XML clone report generated by Nicad cross-project clone detection for Eclipse.
**TABLE II**: The number of stable non-APIs methods in subsequent Eclipse releases identified through clone detection--Type-1 and Type-2
<table>
<thead>
<tr>
<th>Eclipse</th>
<th>E-1.0</th>
<th>E-2.0</th>
<th>E-3.1</th>
<th>E-3.2</th>
<th>E-3.3</th>
<th>E-3.4</th>
<th>E-3.5</th>
<th>E-3.6</th>
</tr>
</thead>
<tbody>
<tr>
<td>New</td>
<td>28,732</td>
<td>30,993</td>
<td>19,011</td>
<td>42,281</td>
<td>30,094</td>
<td>27,344</td>
<td>19,992</td>
<td>28,852</td>
</tr>
<tr>
<td>T1</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T2</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T3</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T4</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T5</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T6</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T7</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T8</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T9</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
**TABLE III**: non-APIs that have remained stable over subsequent Eclipse releases–candidates of promotion summarized at class level.
<table>
<thead>
<tr>
<th>Eclipse</th>
<th>E-1.0</th>
<th>E-2.0</th>
<th>E-3.1</th>
<th>E-3.2</th>
<th>E-3.3</th>
<th>E-3.4</th>
<th>E-3.5</th>
<th>E-3.6</th>
</tr>
</thead>
<tbody>
<tr>
<td>New</td>
<td>28,732</td>
<td>30,993</td>
<td>19,011</td>
<td>42,281</td>
<td>30,094</td>
<td>27,344</td>
<td>19,992</td>
<td>28,852</td>
</tr>
<tr>
<td>T1</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T2</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T3</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T4</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T5</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T6</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T7</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T8</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>T9</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
**B. Results**
Tables II and III present the results of RQ1, i.e., the number of stable non-API methods in a given Eclipse release observed in subsequent Eclipse releases. The first row of Table II shows the different Eclipse old releases (Eold) where we carried NiCad cross-project clone detection with the corresponding successive Eclipse new releases (Enew), in the first column. Due to space limitations, in the first row, we present the results from Eclipse 1.0 to 3.6. However, the remaining Eclipse releases show similar figures. The second row–**Total** shows the total number of non-API methods in the different Eclipse releases; e.g., E-2.0 has a total of 46,156 non-API methods. The third row–**New** shows the number of newly introduced non-API methods in the different Eclipse releases; e.g., E-2.0 has a total of 30,993 newly introduced non-API methods during its release and the rest (46,156 − 30,993 = 15,163) evolved with Eclipse from earlier releases. The rest of the values in the matrix report the number of non-API methods of the newly introduced non-API methods in the given Eclipse releases that remained unchanged in successive Eclipse releases. For example, the value (E-2.1, E-2.0–T1) = 3,523 indicates that among 30,993 non-API methods introduced in E-2.0, 3,523 stayed unchanged (Type-1) in E-2.1. The last four rows of Table II present the descriptive statistics of stability of the non-API methods. From the results presented in Table II, we observe that a few of the non-API methods that were newly introduced in a given Eclipse release still exist and have remained unchanged in subsequent Eclipse releases. In Table II, in the summary statistics in the last four rows, we can observe high values on unchanged newly introduced non-API methods of given current Eclipse releases in successive Eclipse releases. Take for example the results of Eclipse 1.0, after 15 years of the evolution of Eclipse framework producing a major release every year in Table II in cell (E-1.0, E-4.6) we still find 1.02%–Type 1 and 1.24%–Type 2 of the 28,732 have remained stable. In Eclipse-E-3.5, we observe that in the last Eclipse release-E-4.6 there still exists over 8.8%–Type 1 and 9.19%–Type 2 of the 19,603 non-API methods newly introduced in E-3.5 that have not been changed. Looking at row-E4.6 in Table II we can see the numbers of old non-API methods still present in Eclipse 4.6. For example Type 1 E-4.6–295, 411, 233, ... shows the number of old non-API methods from Eclipse release–1.0, 2.0, 2.1, ... respectively. The 295 non-API methods in E-1.0 present in E-4.6 indicate releases 1.0 and 4.6. In the first clone pair in Listing 1, both methods are from APIs (no segment internal in the source file paths). In the second clone pair both methods are from non-API methods. This clone pair indicates that the method p4.internal.sp4.pk4.F4.m2() was introduced in Eclipse 1.0 and is still unchanged in the Eclipse release 4.6.
that they have never been changed throughout the evolution of Eclipse.
In Table II we have presented stable non-API methods that are candidates of promotion to APIs. However, we understand that non-API methods are too fine grained to be considered as candidates of promotion. To this end, we present a summarized version of Table II in Table III. For example, in Table III cell (E-2.1, E-2.0-T2) = 233/1, 308 is a class-level summary of the non-API methods in cell (E-2.1, E-2.0-T2) = 3, 865 of Table II. The value 1, 308 in cell (E-2.1, E-2.0-T2) = 233/1, 308 indicates that the 3, 865 non API methods are contained in a total of 1, 308 non-API classes. Whereas the value 233 in (E-2.1, E-2.0-T2) = 233/1, 308 indicates that 233 of the 1, 308 non-API classes contain five of more non-API methods. Due to space limitations, in Table III we only present the results of Eclipse 1.0, . . . , 3.4.
The detailed lists of Eclipse releases is available on-line2.
C. RQ1-Findings
The main reason for Eclipse interface providers to label the interfaces as non-API methods is the expectation of evolutionary changes. Once a non-API is through these evolutionary changes it is supposed to be promoted to an API [24].
To understand why some non-API methods remain unchanged for a very long time during the evolution of the framework, we contacted the Director of Open Source Projects—The Eclipse Foundation, Wayne Beaton. According to Mr. Beaton promotion of the non-API methods to APIs is something that the project teams decide for themselves. He also believes that “internal API oftentimes becomes official API when somebody steps up to do the work to make it so”.
High number of stable non-API methods in Table II suggests that promotion indeed does not happen often. In addition to lack of developers interested in the promotion task suggested by Mr. Beaton, lack of promotion can be attributed to presence of developers dependent on non-API methods. However, at the same time plug-in developers might prefer to avoid these non-API methods since they are advertised as being unstable and likely to change. Hence, a developer intending to carry out such a promotion should balance the costs incurred on the developers making use of a non-API and the potential gains obtained by engaging more developers that might have been reluctant to use the non-API (cf. [25], [26]).
We identify methods in the same classes that have been stable for a long time. For example in Table II, the in cell (E-4.6, E-1.0-T1) = 295 non-API methods introduced in E-1.0 and have not changed (Clone Type-1) until E-4.6. We identify these stable non-API methods as candidates of promotion. We understand that Eclipse providers normally perform non-API promotion at the level of a class. Promotion at the method level seems to be fine grained. We have therefore summarized the non-API methods that are possible candidates for promotion to APIs to the class-level. Instead of promoting
V. RQ2: PREDICTING NON-API STABILITY
Next we want to predict whether non-API methods present in a given Eclipse release will remain stable in the subsequent Eclipse releases. We want to investigate possible factors that relate to the stability of the non-API methods. We hypothesize that in a given Eclipse release, length of the methods, the number of parameters of the method signature and the age of the non-API methods could have an influence on the stability of the non-API methods in the next Eclipse release.
A. Approach
We want to compare the importance of multiple metrics of methods in a given Eclipse release. For the dependent variable, we consider non-API stability—Stability. Stability on a non-API method in the subsequent Eclipse release can take one of two values—stable or unstable.
As independent variables we consider metrics of lengths of a methods—mLengths, number of methods parameters—mParams, age of a method—Age on the non-API. We want to build a random-forest classifier to predict whether an internal interface will be promoted, given the values of the metrics. We choose the random-forest classifier because it is known to have several advantages, such as being robust to noise and outliers [27], [15]. In selecting the training and testing set, we rely on the built-in internal evaluation of performance of random forests based on out-of-bag dataset [28]. In the implementation of the random forest algorithm, each tree is trained on about 2/3 of the total training data also known as the bootstrapped data. As the forest is built, each tree can thus be tested on the out-of-bag data (similar to leave one out cross validation) on the samples not used in building that tree.
To assess the effectiveness of the classifier in predicting stability of the non-API methods we use such common measures as precision, recall, F-measure, and AUC [29], [27], [15], [30], [31].
B. Data extraction
As explained earlier, a newer Eclipse release is composed of newly introduced non-API methods as well as non-API methods carried over from older Eclipse releases. We illustrate the different steps we used collect the data for RQ2
2https://sites.google.com/view/eclipse-saner-2019/home
Using Listings 2, 3, and Figure 3. Using the NiCad tool, from sources of the different Eclipse releases, we extracted signatures of non-API methods, the fully qualified name of Java files, start-line and end-line of the method in the file. Using set differencing on the lists of non-API method signatures, we isolate the newly introduced non-API methods in each Eclipse release.
In Step 1 of Figure 3, we automatically annotate non-API methods in each .java file in a given Eclipse release with the Eclipse release where these methods have been introduced. For example in Step 1, the release of interest R4 has methods that were introduced in R1–R3 as well as those newly introduced in R4. After annotating the non-API methods in R4 that are uniquely identified from which Eclipse release they were introduced, the output is R4—Annot. In Listing 2 we present an extract of four method signatures from Eclipse release 4.6 before method annotation. The methods in the listing show the fully qualified methods name, its parameter list, the method start line–number after the first full colon and end line–number after the second full colon. In Listing 3 we show the corresponding method after the annotation. The non-API method annotations are on the method name—E4_2, E3_6, and E3_6 and E4_6. For example, getInstallLocation_E4_2 tells us that the method getInstallLocation was introduced in Eclipse 4.2 but still present in Eclipse 4.6.
For building the models, we considered data from Eclipse releases 4.2, 4.3, 4.4, 4.5, and 4.6. Looking at Listing 3, we can determine the values for the metrics mLengths—difference between method end-line and start-line, mParams—count of the method parameters. For the Age metric, newly introduced non-API methods in Eclipse release under study have an Age of zero, those introduced in previous release Age of one, etc. For example in Eclipse 4.2, the newly introduced non-API methods in 4.2 would have zero years, those introduced in 3.7 would have one year and those introduced in 1.0 would be 11 years.
Extracting data for dependent variable Stability, we subject two annotated Eclipse releases to NiCad cross-project (see Step 2 in Figure 3). The output of Step 2 is an annotated clone report in XML format. We configure NiCad cross-project to extract Type-2 and Type-3 clone pairs between two Eclipse releases. We do not extract Type-1 clones since the method annotations eliminate the occurrences of Type-1. In Listing 4 we present an XML file that is an illustration of the cross-project between Eclipse 4.2 and the target Eclipse 4.6. Considering for example the total number of non-API methods in Eclipse 4.2, one is able to determine those that remained stable in the target Eclipse 4.6—those that appear in the annotated clone report and the unstable non-API methods—the rest of the non-API methods in Eclipse 4.2 not
TABLE IV: Stability prediction results (percentages) of non-API between a pair of Eclipse releases.
<table>
<thead>
<tr>
<th>Target</th>
<th>4.2</th>
<th>4.3</th>
<th>4.4</th>
<th>4.5</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Prec</td>
<td>Rec</td>
<td>F-m</td>
<td>AUC</td>
</tr>
<tr>
<td>4.3 T2</td>
<td>82</td>
<td>96</td>
<td>86</td>
<td>97</td>
</tr>
<tr>
<td>4.3 T3</td>
<td>86</td>
<td>97</td>
<td>91</td>
<td>98</td>
</tr>
<tr>
<td>4.4 T2</td>
<td>71</td>
<td>98</td>
<td>82</td>
<td>95</td>
</tr>
<tr>
<td>4.4 T3</td>
<td>83</td>
<td>98</td>
<td>90</td>
<td>97</td>
</tr>
<tr>
<td>4.5 T2</td>
<td>65</td>
<td>97</td>
<td>78</td>
<td>93</td>
</tr>
<tr>
<td>4.5 T3</td>
<td>80</td>
<td>97</td>
<td>88</td>
<td>97</td>
</tr>
<tr>
<td>4.6 T2</td>
<td>56</td>
<td>98</td>
<td>71</td>
<td>92</td>
</tr>
<tr>
<td>4.6 T3</td>
<td>78</td>
<td>97</td>
<td>86</td>
<td>92</td>
</tr>
</tbody>
</table>
T2 Type-2 Clones
T3 Type-3 Clones
TABLE V: Stability prediction results (percentages) of non-API between a pair of Eclipse releases.
<table>
<thead>
<tr>
<th>Target</th>
<th>4.2</th>
<th>4.3</th>
<th>4.4</th>
<th>4.5</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>L</td>
<td>P</td>
<td>A</td>
<td>L</td>
</tr>
<tr>
<td>4.3 T2</td>
<td>98</td>
<td>2</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.3 T3</td>
<td>86</td>
<td>14</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.4 T2</td>
<td>90</td>
<td>1</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.4 T3</td>
<td>99</td>
<td>1</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.5 T2</td>
<td>86</td>
<td>14</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.5 T3</td>
<td>99</td>
<td>1</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.6 T2</td>
<td>96</td>
<td>4</td>
<td>0</td>
<td>97</td>
</tr>
<tr>
<td>4.6 T3</td>
<td>74</td>
<td>26</td>
<td>0</td>
<td>97</td>
</tr>
</tbody>
</table>
L mLength
P mParams
A Age
in the clone report.
We extracted cross-project clone reports for Type-2 and Type-3 between pairs of Eclipse releases 4.2 to 4.6. A total of 20 cross-project clone reports were obtained from the considered Eclipse releases. Thereafter, we carried out random forest predictions of the stability of non-API methods between all the 20 pairs of Eclipse releases. We used a commercial tool called Salford Predictive Modeler\(^3\) to perform the predictions. In the tool, some of the key controls of the random forest process were set as follows: number of trees to 200, the number of predictors considered for each tree node to two and the parent node minimum cases to two records.
C. Model Evaluation
To evaluate our models, we assess the effectiveness of the classifier in correctly predicting stability of the new Eclipse releases. We use precision, recall, F-measure and AUC (area under curve) to measure its effectiveness, which are commonly adopted in classification tasks [32], [27]. Precision and recall measure the correctness and completeness, respectively, of the classifier in predicting whether a non-API is stable. F-measure is the harmonic mean of precision and recall. AUC is a commonly used measure to judge predictions in binary classification problems, and it refers to the area under the Receiver Operating Characteristic (ROC) curve. AUC is robust toward unbalanced data [33]. AUC of 70% is considered reasonably good [34], [35], [27].
\(^3\)https://www.salford-systems.com/
D. Results RQ2
The number of non-API methods present in Eclipse 4.2 to 4.5 range from 147K to 152K. The number of stable non-API methods in the 20 different pairs of Eclipse releases 4.2 to 4.6 for Clone Type-2 and Type-3 range from 33K to 40K (about 19 to 28\% of the total target observations). This implies that the majority of the values in the dependent variable in the 20 different datasets are class-0–unstable interfaces. To ensure that our models are not suffering from over-fitting/under-fitting, we employed other model testing methods other than out-of-bag like: test sample contained in a separate file and fraction of testing selected at random. The two testing cases did not yield different results from the out-of-bag method. The predictions success results reveal that in solving the classification problem, the random forest model shows that the out-of-bag internal validation performance as being in the range of 82 to 94\% correct in correctly classifying stability class-0–unstable interfaces and a range of 96 to 99\% correct in correctly classifying class-1–stable interfaces.
Table IV and V present the prediction results of RQ2. Table IV shows effectiveness of the classifier in correctly predicting the non-API stability using precision, recall, AUC and F-measure. For example, the value in cell (4.4-T2, 4.2-Prec) = 71\% indicates that the non-API methods present in Eclipse 4.2 were predicted to be stable/unstable in the target Eclipse release 4.4 with a precision of 71\%.
The results show that the precision is between 56\%–86\%, recall 96\%–99\%, F-Measure 81\%–89\%, and AUC 92\%–98\% for all the data of clone Type-2 & 3. From the results presented we observe relatively high prediction values for
all the considered measures. We observe very high recall compared to the precision. Precision is the ratio of correctly predicted positive observations to the total predicted positive observations (i.e., \( \text{Precision} = \frac{TP}{TP + FP} \)). Recall is defined as the ratio of correctly predicted positive observations to the total predicted positive observations (i.e., \( \text{Recall} = \frac{TP}{TP + FN} \)). The reason we have very high values of recall is that, as stated earlier, the prediction success of the classifier was very high (i.e., all the models revealed very few cases of incorrectly classified stable non-API methods—\( FN \)).
In Software Engineering domain the value of AUC between \( \geq 70\% \) is considered a reasonably good measure [15], [27], [30], [35].
In Table V we show the predictor importance that summarizes how the individual variables have contributed to the prediction accuracy. The Gini importance was used to indicate how large a variable’s overall discriminative value was for the classification problem. We observe that the predictor \( m\text{Length} \) of the non-API methods is the most influential followed by \( \text{Params} \) and finally \( \text{Age} \). As can be seen, the variable \( \text{Age} \) is insignificant in separating the two target classes.
### E. RQ2-Findings
Yes we can predict the stability of a non-API in subsequent Eclipse releases with a precision of 56% and higher, a recall of 96% and higher and an AUC of 92% and higher and an F-measure of 81% and higher. From the results presented in Section V-D we can observe that the number of parameters and the lengths of a non-API method have a significant effect in determining the non-API stability in new Eclipse releases. Developers who use the non-API methods in their applications can use our dataset to estimate the stability of the non-API methods in new Eclipse releases. We have also observed that the age of a non-API has an insignificant impact on the stability of a non-API in a new Eclipse release. Our observation contradicts with the earlier observation of Busing et al. [10], [9] that older non-API methods are more stable than the more recently introduced ones.
### VI. Threats to Validity
We observe a construct validity threat related to the results of RQ1. An object-oriented API may much more complex than it is assumed in the paper. To use the functionality provided by an API, in some cases one be required to instantiate an object and call two or more methods from this object.
Furthermore, we determine non-API stability using clone Type 1 & 2. Using Type 2 clones could threaten the construct validity since the changes in the stable non-API determined by clone Type 2 might actually make the non-API unstable.
Internal validity threat related to the tool (i.e., NiCad) used to extract the data used in our experiments. However, studies who have compared NiCad tool with other clone detection tools have observed that NiCad tool has the highest precision and recall of any existing code clone detector tools [22], [36]. Threats to external validity concern the possibility to generalize our results. Our study focus on only one framework. Validation on other frameworks and libraries developed in the same setting like Eclipse like those we presented in Section I (i.e., JDK, MSDN, jBPM and JUnit) is desirable.
### VII. Related Work
In the previous sections, we implicitly discussed how the current work relates to the previous work [12], [11], [9], [37], [10], [13]. In general, the previous studies were based on empirical analysis of the co-evolution of the Eclipse SDK framework and its third-party plug-ins (ETPs). During the evolution of the framework, the authors studied how the changes in the Eclipse interfaces used by the ETPs, affect compatibility of the ETPs in forthcoming framework releases. The authors only used open-source ETPs in the study and the analysis was based on the source code. One of previous studies [13] was based on analysis of a survey, where they complement other previous studies by including commercial ETPs and taking into account human aspects. One of the major findings of the previous studies was that interface users are continuously using unstable interfaces and the reason for using these unstable interfaces was because there no alternative stable interfaces offering the same functionality. This study was based on understanding the evolutionary trend followed by the Eclipse non-APIs in successive Eclipse releases. We use code clone detection analysis to carry out our investigation.
Another study that is directly related to ours is that of Hora et al. [15] who investigated the transition from internal to public interfaces. They carried out their investigation on Eclipse (JDT), JUnit, and Hibernate. Their main aim was to study the transition from internal to public interfaces (i.e., internal interface promotion). They detect internal interface promotion when the two conditions are satisfied: 1) there is at least a file change that removes only one reference to Internal and adds only one reference to Public, and 2) the class names of the references remain the same or have a suffix/prefix added/removed. They discovered that 7% of 2,277 of internal interfaces are promoted to public interfaces. They also found that the promoted interfaces have more clients. They also predicted internal interface promotion with precision between 50%–80%, recall 26%–82%, and AUC 74%–85%. Finally, by applying their predictor on the last version of the analyzed systems, they automatically detected 382 public interface candidates. Our study and this study both aim at identifying internal interfaces that are candidates of promotion. However, in comparison to our study, we use clone detection techniques on the Eclipse releases to determine stable internal interfaces that we recommend as possible promotion candidates.
Other work related to ours includes [38], [39], [40], [41], [42], [43], [44], [45], [46] Sawant et al. [38] studied the effects of deprecation of Java API artifacts on their clients. Their work expands upon a similar study done on the Smalltalk ecosystem. The main differences between the two studies is in the type systems of the language targeted (static type vs dynamic type), the scale of the dataset (25,357 vs 2600 clients).
and the nature of the dataset (third-party APIs vs third-party and language APIs). They found that few API clients update the API version that they use. In addition, the percentage of clients that are affected by deprecated entities is less than 20% for most APIs—except for Spring where the percentage was unusually low. In the case of the JDK API, they saw that only 4 clients were affected, and all of them were affected by deprecation because they introduced a call to the deprecated entity at the time it was already deprecated, thereby limiting the probability of a reaction from these clients.
Wu et al. [39] analyzed and classified API changes and usages in 22 framework releases from the Apache, Eclipse ecosystems and their client programs. They discovered that framework APIs are used on average in 35% of client classes and interfaces and that about 11% of APIs usages could cause ripple effects in client programs when these APIs change. The authors also found that missing classes and methods happen more often in frameworks and affect client programs more often than the other API change types do. Mastrangelo et al. [40] discovered that client projects often use internal interfaces provided by JDK. Brito et al. [41] introduced APIDIFF, a tool to identify API breaking and non-breaking changes between two versions of a Java library. The tool detects changes on three API elements: types, methods, and fields. We also report usage scenarios of APIDIFF with four real-world Java libraries. McDonnell et al. [42] investigated API stability and adoption on Android ecosystem. They discovered that Android is evolving fast with an average of 115 API updates per month but developers are resistant to embrace unstable fast evolving APIs quickly. They found out that 28% of Android references in client code are out-of-date with a median lag of 16 months. Dig and Johnson [43] studied the role of refactorings in API evolution and found that 80% of the changes that break client applications are API-level refactorings.
Henkel et al. [44] propose CatchUp, a tool that uses an IDE to capture and replay refactorings related to API evolution. Hora et al. [47], [48] propose tools to track path of API evolution by mining fine-grained code changes. Hou [49] studied the evolution of Eclipse Java editor by exploring the Eclipse source code for six releases. He discovered that although there are changes to the design of individual features, architecturally, the editor benefits from the MVC based design laid out in the outset of the project. Hou and Wang [50], [51] analyzed release note entries in seven releases of the Eclipse IDE both quantitatively and qualitatively. The authors found that majority of the changes were refinements or incremental additions to the feature architecture set up in early releases.
API evolution has also been studied for many other platforms. Jezek et al. [52] investigated the API changes and their impacts on Java programs. They found out that API instability is common and will eventually cause problems. Hora et al. [45] studied how developers react to API evolution for the Pharo system, they discovered that API evolution can have a large impact on a software ecosystem in terms of client systems, methods, and developers. Hou and Yao [46] explored the intent behind API evolution by by analyzing the evolution of a production API in detail. The authors discovered that a large part of API evolution is minor correctives.
VIII. CONCLUSION AND FUTURE WORK
In this study we have carried out an extensive investigation on the evolution of Eclipse non-APIs. 1) In RQ1, we observed that indeed there exist non-API methods that remain stable in subsequent Eclipse releases during the evolution of Eclipse. 2) In RQ2, We have shown that the metrics of length of a method and number of method parameters in a non-API method are good predictors for the stability of the non-API method in subsequent Eclipse releases. We have observed that age of an non-API is not a significant predictor of the non-API’s stability in subsequent framework releases.
We determined non-API stability in subsequent Eclipse releases using clone detection techniques. Our recommendation/contributions to Eclipse interface providers are as follows:
1) We provide a dataset of 327K stable non-API methods that can be used by both Eclipse interface providers as possible candidates of promotion. Instead of promoting non-APIs which are too fine-grained, we summarized of non-API methods groups in given classes that are stable together and presented class-level non-APIs that possible candidates promotion. The Eclipse providers can use our data as a starting point to analyze and promote stable non-APIs to APIs.
2) We have shown that it is possible to predict the stability of a non-API in subsequent Eclipse releases with a precision of \( ≥ 56\% \), a recall of \( ≥ 96\% \) and an AUC of \( ≥ 92\% \) and an F-measure of \( ≥ 81\% \). We have also shown that the metrics of length of a method and number of method parameters in a non-API method are very good predictors for the stability of the non-API in successive Eclipse releases. The results provided can help the API providers to estimate a priori how much work could be involved in performing the promotion.
As future work we would extend the current study by 1) gathering data about how often each stable non-API methods is used (popularity), and 2) carrying out a survey with the interface providers to investigate why non-APIs remain unstable for a long time. In the survey, we shall also get the opinion of the developers on how best our work can be packaged for them the dataset for non-APIs that are candidates for promotion.
ACKNOWLEDGEMENT
This work was supported by the Sida/BRIGHT project under the Makerere-Sweden bilateral research programme 2015-2020. We would like to thank Prof. Thorsten Berger who helped us with proofreading our manuscript.
REFERENCES
|
{"Source-Url": "https://www.win.tue.nl/~aserebre/SANER2019John.pdf", "len_cl100k_base": 11537, "olmocr-version": "0.1.46", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 38455, "total-output-tokens": 12146, "length": "2e13", "weborganizer": {"__label__adult": 0.0003018379211425781, "__label__art_design": 0.0002503395080566406, "__label__crime_law": 0.00025081634521484375, "__label__education_jobs": 0.0007457733154296875, "__label__entertainment": 4.214048385620117e-05, "__label__fashion_beauty": 0.00011295080184936523, "__label__finance_business": 0.00014829635620117188, "__label__food_dining": 0.00019121170043945312, "__label__games": 0.0004012584686279297, "__label__hardware": 0.00042557716369628906, "__label__health": 0.0002417564392089844, "__label__history": 0.00017690658569335938, "__label__home_hobbies": 5.066394805908203e-05, "__label__industrial": 0.00016820430755615234, "__label__literature": 0.0001665353775024414, "__label__politics": 0.0001653432846069336, "__label__religion": 0.0002665519714355469, "__label__science_tech": 0.003173828125, "__label__social_life": 8.046627044677734e-05, "__label__software": 0.00646209716796875, "__label__software_dev": 0.9853515625, "__label__sports_fitness": 0.00019371509552001953, "__label__transportation": 0.00024020671844482425, "__label__travel": 0.00015079975128173828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45709, 0.06154]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45709, 0.2489]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45709, 0.90319]], "google_gemma-3-12b-it_contains_pii": [[0, 5521, false], [5521, 11304, null], [11304, 15107, null], [15107, 20158, null], [20158, 25326, null], [25326, 28194, null], [28194, 33087, null], [33087, 39447, null], [39447, 45709, null], [45709, 45709, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5521, true], [5521, 11304, null], [11304, 15107, null], [15107, 20158, null], [20158, 25326, null], [25326, 28194, null], [28194, 33087, null], [33087, 39447, null], [39447, 45709, null], [45709, 45709, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45709, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45709, null]], "pdf_page_numbers": [[0, 5521, 1], [5521, 11304, 2], [11304, 15107, 3], [15107, 20158, 4], [20158, 25326, 5], [25326, 28194, 6], [28194, 33087, 7], [33087, 39447, 8], [39447, 45709, 9], [45709, 45709, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45709, 0.29592]]}
|
olmocr_science_pdfs
|
2024-11-23
|
2024-11-23
|
694ee6b01472372e2d49ddbea5c8d499d6a6e74e
|
How Can We Help Software Rearchitecting Efforts? Study of an Industrial Case
Brice Govin, Nicolas Anquetil, Anne Etien, Stéphane Ducasse, Arnaud Monegier
To cite this version:
Brice Govin, Nicolas Anquetil, Anne Etien, Stéphane Ducasse, Arnaud Monegier. How Can We Help Software Rearchitecting Efforts? Study of an Industrial Case. 2017. <hal-01451242>
HAL Id: hal-01451242
https://hal.archives-ouvertes.fr/hal-01451242
Submitted on 31 Jan 2017
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Abstract—Legacy software systems are valuable assets for organisations and are sometimes their main source of incomes. From time to time, renewing legacy software system architecture becomes necessary in order to offer them a new future. Migrating the architecture of a legacy software system is a difficult task. It involves understanding and aggregating a large set of data (the entire source code, dependencies, etc.); it may have a profound impact on the system's behaviour; and because it occurs very rarely in the life of a system, it is hard to gain experience in this domain. Based on the study of an industrial architecture migration case, we discuss how this essentially manual effort could be helped with automated tools and a better defined process. We identified several issues raised during the task, characterized their impact, and proposed possible solutions.
I. INTRODUCTION
Legacy software systems represent a significant part of companies’ wealth. Maintainability of such systems has become an important goal for companies which own them. Software evolution activities can be classified in two: day to day evolution, where engineers correct bugs, implement new features, or adapt the system to new working conditions; and, much rarer, restructuring, where engineers need to completely re-think the architecture of a system because it seems no longer possible to adapt it in small steps. Because it occurs so rarely in the life of the system, restructuring software architecture is mostly a case-by-case activity. It is difficult to gain much experience in it and to improve its practice through the definition of a formal process.
In our specific case, the company we are working with wants to restructure a real-time, embedded, critical system. The system is an old (> 20 years) Ada system in the defence area. The goal is to modularise the system to ease day to day evolution and take advantage of technological improvements that were introduced since the creation of the system. The wished architecture is partially specified in the sense that high level components and main architectural rules have been defined. In this restructuring, there is no immediate change in the functionalities and one goal is to reuse existing code as much as possible.
The classical process for architecture restructuring is the horseshoe “process” [1]. However, this is a very generic one that defines high level operations. As such it has been specialised in various publications (e.g. [2]). A line of research try to generalise the target system into a Software Product Line [2] by abstracting variation points in the functionalities, this is not our case since we are keeping the same functionalities. Others focus on migrating toward a Service-Oriented Architecture [3], which, again is not our case, since it has been decided to go for a component based architecture. The Component Recovery line of research is an old one (e.g. [4], [5]) but it typically only tries to extract the components without allowing to specify a wished architecture. Confronted to architecture restructuring in a real software architecture migration case, we found that existing literature often relies on hypotheses that were not true in our case.
In this paper we discuss a three steps process that we formalised from the activities of the software engineers in the project. We list the difficulties that arose when trying to automate some of these activities and possible solutions that we experimented. The efficacy of the different experiments are evaluated against an oracle resulting from the work of software engineers and ourselves on a part of the system.
Section II describes the problem of software architecture migration and the potential related solutions in the literature. Section III details the actions of the software engineers performing the restructuring and points out weaknesses of this project. Section IV presents a process formalising the actions taken by the software engineers and ideas to (partly) automate it. Finally, section VI draws lessons learned from this project and explains the future work.
II. BACKGROUND
As stated previously, the classical process for architecture restructuring is the Horseshoe process [1]. It is divided into three main parts: reverse engineering, re-engineering and forward engineering. The reverse engineering part aims to model and understand the current system architecture, the re-engineering part aims to restructure the architecture of the system and the forward engineering part aims to re-implement the new architecture in the source code [6]. In our project, the reverse engineering part is already handled by the Moose infrastructure [7]. This offers us a model of the system with all its software elements (packages, procedures, types, variables) and their interdependencies (use of variables, invocation of methods, etc.). We will therefore focus on the re-engineering
part. We found in the literature different approaches that can tackle this part, e.g. Software Architecture Transformation [8]; migration towards Service-Oriented Architecture (SOA) [3]; and Component Recovery [9].
A. Main Lines of Research
The phrase Software Architecture Transformation is defined in [1] as the line of research that aims at transforming the current architecture of a legacy system into a new one. Transformation between old and new architecture is done thanks to a set of “recipes” transformation between elements from the two different architectures [10]. This domain focuses on monitoring the impact of architectural changes on the overall quality of the system. It also only considers small architectural transformations that can be applied automatically and guarantees the executability of the resulting source code. This line of research does not concern us since the project we are involved with will completely restructure the system around an architecture radically different from the existing one.
Migration towards Service-Oriented Architecture (SOA) aims to “move the legacy system architecture to the more flexible SOA while preserving the original system data and functionality” [11]. SOA migration approaches either address the technical perspective to expose legacy code as services, or determine the migration feasibility regarding the characteristics of the legacy system and the requirements of the target SOA system [12]. We are not interested in the technical aspects because, in our case, the current and future systems are both implemented using the same technologies and we foresee no technical difficulties there. Moreover, components and services, even though they are close, have fundamental differences that would make it very difficult to reuse SOA migration approaches for component architecture migration.
On the other hand, SOA migration work, e.g. [11], [12], [13], introduced interesting techniques such as Concept Slicing to associate the existing source code with the services they extract. The idea behind Concept Slicing is to identify the source code associated with the implementation of a human-oriented “concept”. The human oriented concept thus becomes a service and the code associated to it is used to implement that service. Concept slicing works by combining Concept Assignment solutions, that identify relevant pieces of code from a concept, with Program Slicing solution, that identify an executable piece of code.
A last related line of research named Component Recovery, or Component Identification, automatically organises the software elements of a system into components. Component recovery corresponds to the detection of subsystems [14], it works by clustering the nodes of a dependency graph of the application [4], [5], [15] into independent components. Yet because they work on structural information (a graph of dependencies between the elements of the system), they can only extract structurally coherent components whereas they should include human and domain knowledge in the process to be able to extract business components [16], [17]. Another issue with existing Component Recovery techniques is that they do not accept a predefined target architecture, but focus on extracting what they consider the best possible components. In our case, the target architecture is already partly defined and we already know what the main components (more abstract ones) should be and even for some of them what sub-components they should contain. We are not aware of a Component Recovery approach that would suit this requirement.
B. Extraction of components from existing source code
Although the existing Component Recovery approaches do not apply to our project, they offer some useful techniques.
All the techniques are based on the idea of representing the source code as a dependency graph where the nodes are software elements and the vertices are dependencies between them [4], [5], [15]. Any given approach will work at a specific level of abstraction and consider a small number of software element kinds, Koschke [5] calls them Quarks, “the smallest significant element at the architectural level”. For example, Allier and Seriai [4], [15] work with classes and Koschke [5] with subprograms, user defined types and variables (in a C program). On the other hand, the example of SOA migration shows that it might be necessary to work at a very fine-grained level. This is the case when program slicing is used to extract executable services.
From the dependency graph, software elements are clustered to form components. The clustering tries to maximise dependencies within a component (known as Cohesion) and minimise dependencies between components (known as Coupling). Many different metrics have been proposed to compute Cohesion and Coupling and we will not consider them in this paper.
Finally we should add that Johnson [18] noted the necessity of an iterative process.
III. DESCRIPTION OF THE PROJECT
We are accompanying a large company which undertook a big software migration project where the architecture of the subject system will be completely redesigned. This section describes the project. Section III-A explains the context of the project; Section III-B details the informal process followed by the re-engineers. Section III-C points out the weaknesses of this informal process.
A. Context of the Migration
The migration project is to restructure a real-time, embedded, critical system in the defence area. The system is old (> 20 years), big (> 300 KLOC) written in Ada 83. It counts around 15 500 packages and 15 000 subprograms gathered into modules. Table I summarises main characteristics of this system and Figure 1 gives a general idea of the existing software architecture. It should be noted that this existing architecture was not explicit prior to the project and has been reconstructed as part of a reverse engineering effort. This reverse engineering effort has been done by engineers inside the company and none of the authors have participated.
TABLE I
CHARACTERISTICS OF THE SOFTWARE SYSTEM
<table>
<thead>
<tr>
<th>Technical Characteristic</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Age</td>
<td>>20 years</td>
</tr>
<tr>
<td>Size</td>
<td>>300 kLoC</td>
</tr>
<tr>
<td>Programming Language</td>
<td>Ada 83</td>
</tr>
<tr>
<td>#Package</td>
<td>1537</td>
</tr>
<tr>
<td>#Subprograms</td>
<td>14 650</td>
</tr>
<tr>
<td>Specificity</td>
<td>Embedded, Real Time, Critical</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Design Characteristic</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Architecture</td>
<td>Modules with single responsibility</td>
</tr>
<tr>
<td>Communication System</td>
<td>Message exchanges</td>
</tr>
</tbody>
</table>

The problems identified with this system are:
- This is a real time system developed a long time ago with the best techniques of that time. As such, a strong emphasis was placed on the processing with little consideration for a high level data model. The company now wishes to correct this situation by defining and using high level, business oriented, data structure that could possibly be shared with other systems in the company.
- The legacy system uses a communication system, that is a proprietary middleware, based on messages exchanges. Since its installation, new communication standards have been defined, that the company wants to use. Instead of using an event based communication system (messages), interactions should be based on shared data.
- Changes in the physical environment of the system are foreseen in the near future, and there is a concern whether these changes could be easily accommodated in the existing system. For example, the Algorithm layer (Figure 1) regularly interacts directly with the physical devices. The company now wishes to have a more modular system that will constraint the impact of any of these changes to a small portion of the system.
- The legacy system adopts a layered architecture. However, communication and dependencies between layers are frequent and not only between two adjacent layers.
- Ultimately, there is a hope to be able to reuse some of the components of the target architecture in other systems of the company in the same business domain. Again, this implies having a more modular system, with better-defined components and data structures.
With these requirements in view, some high level components were defined by domain experts and structured in the target architecture sketched out in Figure 2. The target architecture is only partially specified in the sense that these high level components and main architectural rules were defined, but the exact content of the composite components (i.e. the small boxes within the big ones) was not clear at the start of the project. In this restructuring, all functionalities should remain the same. One goal is to reuse existing code as much as possible and what parts of the existing code should map to what components (composite or atomic) is to be decided by the restructuring project.
The planned architecture has two levels: a component can either be composite (large boxes in Figure 2), and contain other components, or atomic (smaller boxes), and be associated to current code. A few architectural rules were defined to constraint relationships between components, such as a strict three layer architecture (+ the physical device layer) where any layer can only interact with the layers directly above or below it (therefore Business layer cannot interact with Interface layer).

B. Existing Activities in Details
The restructuring relies on manual code analysis. A brief overview of the Ada language is given here to help the reader understand the activities taking place in this project.
The Ada entities of interest are: packages, subprograms and instructions. Packages contain entities that can be packages, subprograms or instructions. Subprograms contain only subprograms or instructions. Instructions are elementary entities (e.g. subprograms calls).
The software engineers study the source code to allocate software elements to one of the 16 pre-defined composite components. They do this by actually assigning software elements to potential atomic components within the composite components. Two tasks are therefore performed concurrently: assign software elements to the composite components and decomposing these into a number of atomic components. Software engineers try to allocate entire packages to a given atomic component. Yet studying it, they may consider that a part of it, maybe a subprogram, will need to be assigned to another atomic component (but always in the same composite component); they may sometimes even go down to assigning instructions (always subprogram invocations) to another atomic component.
From this informal process, we identified two interesting characteristic. First, they work at very different levels of abstraction, from coarse grained elements (packages) to very detailed ones (single instruction). To the best of our knowledge, we have not seen a proposition in the literature that allows to work with such a wide range of entities. Second, they adopted an iterative approach that tends to refine the results, working first on packages, then on subprograms and eventually on instructions.
Allocating Packages: Based on their understanding of the source code, the re-engineers select a set of packages that are likely to answer the responsibility of a component. The packages imported by each of these initial packages are normally allocated to the same component. Exceptions occur when an imported package has already been allocated to some other component. In that case, a deeper analysis of the package is performed, by looking at the comments in the source code, to resolve the conflict.
In case of doubt, another possibility is available: a library component gathering all the packages that could not be allocated to one single component.
Allocating Subprograms and Subprograms Invocations: Subprograms and subprograms invocations may be moved from one atomic component to another but only between sibling components (meaning they remain in their composite component). Re-engineers’ analysis of the packages content relies on structural information such as dependencies between subprograms, and instructions in order to identify flows of execution. One must recall that we are dealing with a real time system which implies that functionalities or task within this system are first class citizens that receive a large part of the developers’ attention. In comparison with more traditional information system, it seems that data received less attention during the system initial development. It is actually one of the goal of the system to correct this fact and identify high level, business, data structures that could possibly be reused in other related systems.
The analysis of the software engineers also relies on their knowledge of the system, their experience in the domain, the identification of features in the source code and the extraction of the source code associated to a feature. They are basically applying a concept slicing to determine the instructions that perform a specific feature and then allocate these instructions to the component that should implement this feature. Respect of the mandatory / prohibited relationships between components are also used in the allocation of subprograms and subprograms invocations.
Code Rewriting: In accordance with the allocation, re-engineers rewrite the existing code to make the legacy software system work with its new architecture. Classic V-cycle is the basis of this part and it is done in parallel with the previous step.
At the moment, this project is ongoing, atomic components have been identified in all 16 composite components. Many packages and subprograms have been allocated to their components, but all the work is not done yet and the final step of rewriting the code to actually build the new system did not start yet.
C. Existing Approach Weaknesses
This informal process mostly relies on a comprehension of the legacy system by the re-engineers. A deep knowledge of each entity (package, subprogram or subprograms invocations) is required. Consequences are twofold.
First, the process is fully manual leading to time consumption and possible error creation. Due to the significant size of the legacy system, the full content of each package cannot be analysed in details by humans. Consequently, in the package allocating stage, the re-engineers use imported packages declarations to navigate dependencies from a given package. However, these declarations may be a super set of the actual dependencies. Unrelated packages are analysed together whereas they have no connected responsibilities and their analysis should be postponed.
Second, the process mostly relies on the skills of very few re-engineers who know the software enough. This deep knowledge eases their task, by enabling them to eventually skip the analysis of entities. However, their analysis strongly depends on the coding convention, making the process strongly dependent on the legacy software system. Consequently, the process is ad hoc and is difficult to reproduce on another legacy system or with another engineer.
IV. A PROPOSED TOOL SUPPORTED PROCESS
To help overcome these weaknesses, we are working on formalizing a restructuring process and developing tools to automate it. Our solution is based over an existing industrial tool using the Moose technology [7]. Our hopes are: to validate the work already done and/or identify possible erroneous decisions; To speed up the remaining of the project; To prepare for envisioned future similar efforts in the company. While describing this process, we will highlight decision points (DP)
that we evaluated to understand which solution was the best and what consequences they could bring.
Our process consists in an iterative refinement of the allocation of software elements to components: In a first step, packages will be assigned to components, possibly resulting in conflicting assignments. We then go down to the level of subprograms to decompose the conflicting packages into coherent “sub-packages”, and decompose composite components into atomic components. Finally we propose to go down to decomposing subprograms by allowing to assign some of our instructions to different atomic components. This last step assumes one would do subprogram extraction refactorings.
The process does not try to create components as often seen in past research, but relies on the knowledge of software engineers in their business domain to propose meaningful components and assign software elements to these components. This knowledge is reinforced by structural information (dependencies between elements) and the identification of special elements.
At the start of each iteration, a model of the system (or of a part of the system) is built with the software elements to be allocated (called architectural quarks following the convention in [5], i.e. the smallest significant elements) and their relationships (or dependencies). Each iteration then consists in asking the software engineers to identify core quarks and assign them to components. From these core quarks, we navigate the dependencies between all quarks to assign them to the components. The main decision points (DP) in evaluating our process and its automation will therefore be, at each iteration (or level): (i) how to choose the right core quarks; (ii) what dependencies to follow (or how to follow the dependencies as will be explained further down); and (iii) how to resolve conflicting assignments. Note that it is not mandatory to solve every conflict during a given step. Thus, at the end of an iteration, some conflicts might still exist.
Finally, we must note that our process does not yet address the code rewriting step.
A. First iteration: Package allocation
This first iteration aims to allocate packages into composite components. At the architectural level of this iteration, the quarks are Ada packages. The edges of the dependency graph are the dependencies between packages as when one package imports another one.
The software engineers helped us to identify simple rules that allowed to identify the core packages of each composite component (DP$_{c}^{1}$). There can be as little as one core per component. It was easy for the software engineers to select them. Actually, the choice of the composite components of the wished architecture already implicitly relied on the identification of important part of the system that were easy to map to some packages. For the system under study, it was possible to define rules, based on naming convention and the presence of some specific software elements (an Ada procedure named run), allowing to automatically identify core packages for each high level component.
We experimented two alternative solutions for DP$_{d}^{1}$: the packages indicated by the software engineers (see above) and random choice of packages. Obviously, the second one will give poorer results, but it may be a specificity of this project that high level composite components and core packages seemed very clear to the software engineers.
The dependency graph is navigated from each core, following its dependencies recursively (see Figure 3). Each reached node is allocated to the same component as the core. Obviously, the same node may be reached from different cores because several packages depend on it (e.g. the triangle and diamond elements on the right of the figure) resulting in conflicting quarks (multi-core conflict). It may also occur that some quarks are never reached from the cores resulting in another type of conflict (isolation conflict as for the dotted elements on the left of the figure).
We experimented with three solutions for Decision Point DP$_{r}^{1}$: First the dependency relationships can be Ada declared imports between packages (Ada instruction with). Second they can be what we call referenced imports which are the declared imports that are actually necessary in the code to make it compile (as in many languages, the compiler does not check that a declared import is actually necessary). This is one point where an automated tool has an advantage over manual analysis in identifying the imports that are really required. The referenced imports are guaranteed to be a subset of the declared imports. Third, dependencies between packages can be the same referenced imports, but this time followed upward and downward, that is to say we look on what packages the core quarks depend (as for the two other solutions), but we also include in the component, the packages that depend on the core quarks.
Re-engineers may solve conflicts manually according to their knowledge of the application. They are helped by information about the packages e.g. their names, their comments or all the dependent packages in the dependency graph. In this iteration, conflicts resolution is not required since the iteration is used to set out the architecture migration process.
We experimented with two solutions for Decision Point $DP_{d}^{1}$: first and as currently done by the software engineers, the “resolution” of multi-core conflicting packages may be to assign them to a special component called the Library. The rational is that packages that are required by more than one component need to be accessible from everywhere. In this first solution, we propose to resolve isolation conflict by following the dependencies from the isolated packages towards the core packages (note that the isolated packages are those that could not be reached from any core towards them). This part is similar to the third choice for $DP_{d}^{1}$.
A second option that we evaluated for $DP_{d}^{1}$ was to leave the components in conflict and evaluate them as if they were
$DP_{c}^{1}$ stands for Decision Point for Core quarks at iteration 1.
$DP_{d}^{1}$ stands for Decision Point for Dependency relationship at iteration 1.
$DP_{r}^{1}$ stands for Decision Point for Resolving conflicts at iteration 1.
† $DP_{d}^{1}$ stands for Decision Point for Dependency relationship at iteration 1.
actually member of both components (multi-core conflict) or of no component at all (isolation conflict).
B. Second Iteration: Subprograms allocation
This second iteration aims to refine the allocations done in the first iteration by defining atomic components in the composite components and allocating subprograms to these atomic components. The dependency graph is built from subprograms (the quarks) and the dependencies between them are invocations. Again, the iteration starts by choosing core quarks and allocating them to components following transitively the dependencies.
Allocation is always considered within a composite component, which means that subprograms in a package will always remain within the composite component of their package, but two subprograms of one package may be allocated to two different atomic components.
We experimented with only one composite component in this iteration.
The first option for $DP_c^2$ (choosing of core quarks for iteration #2) is again to follow the indications of the software engineers. (They were less clear cut this time). Several atomic components of the composite component considered for this evaluation were named by the software engineers from one package of the same composite component. All the subprograms of such packages were an obvious choice as core quarks for their respective atomic components. In other cases, we tried to rely on subprogram naming convention to choose core quarks for other atomic components.
For Decision Point $DP_d^2$, we relied on invocation between subprograms as stated above. We considered three options (not all mutually exclusive): only using downward invocation from the cores to other subprograms; using both upward and downward invocations; and/or considering what variables the subprograms use. The last option is based on the hypothesis that some variables are “indicators” of atomic components. By identifying these variables, we want to assign subprograms that use them to the components.
This iteration will also result in conflicts that may be resolved by the software engineers or left for the next iteration.
C. Third Iteration: Subprograms invocations allocating
This iteration aims to resolve some of the conflicts left in the previous iteration by decomposing the subprograms and assign individual instructions (extracted in new subprograms) to atomic components. As for the manual process, the instructions considered here are invocation (subprogram calls) instructions.
We identified some conflicting subprograms that act as “dispatcher” between several atomic components: The flow of execution reaches them and they channel it toward the appropriate atomic component after a series of tests. Such dispatcher subprograms are often in conflict in that they appear to be assignable to several atomic components, usually all the components to which they may dispatch the flow of control. One idea is to try to decompose these dispatchers so that each flow of execution is concentrated in its atomic component and the dispatching done earlier in the flow of execution.
We neither had the time nor enough data yet to experiment solutions for this step.
V. EXPERIMENT DESCRIPTION
We presented a process to help software engineers restructure a software system. At each iteration of the process, we identified decision points and proposed solutions. We compared these solutions to an oracle corresponding to the manual work of the software engineers after possible modifications.
We first present the oracle before discussing in detail each proposed solution and see their respective efficiency and what impact they have on the result.
A. Oracle
The manual work described in section III-B is considered the oracle. The target architecture is composed of 16 composite components. One of them is the Library component and is used to gather all the packages that are needed (i.e. imported by a package) by several composite components. The engineers allocated 1537 packages on to the 16 composite components. 408 packages, out of the 1537 packages of the application, were allocated to the Library. 593 packages have been categorized as messages and are treated by the engineers during the second iteration. This first step took about two weeks long to four engineers to complete. This first assignment of packages into composite components is the base for our oracle (evaluation of our first step solutions).
At the time of this writing, the engineers finished defining all the atomic components belonging to the composite components. However, few of these atomic components have been populated by software elements (packages, subroutines, instructions). The engineers focused on two of the 16 composite components, and their atomic components are considered
complete. These two composite components and their atomic components are used to evaluate the results of our second step solutions. This part of the oracle took some time to establish as it requires a more in depth study of the packages and their subprograms. Each of these two composite components took one person/month to complete. The software engineers established a first classification that was too low level (not sufficiently abstract). After reworking they merged some of the atomic components originally identified together.
Unfortunately, we could not establish a meaningful oracle for the evaluation of the third step solutions.
B. Evaluation of solutions
Evaluation of all proposed solutions will be computed against the oracle. We use Precision and Recall metrics, also summarised in the F-Score metric. For any possible allocation of quarks in components:
- Precision = % of quarks allocated to a component in the evaluated solution that are in the same component in the oracle.
- Recall = % of quarks allocated to a component in the oracle that are in the same component in the evaluated solution.
- F-Score = 2*(precision*recall)/(precision + recall)
Typically, one may achieve better precision (all allocated quarks are in their right component) by lowering the recall (very few quarks are actually allocated to any component). The opposite is also true. For this reason, the F-Score metrics offers a balanced value of both metrics together.
The result we give are the arithmetic mean of the metrics values over all components.
For reference, we give the results of the first allocation of software elements into atomic components made by the engineers (Table II). They later improved this work, but considering their initial result can give some ground of comparison to rank the quality of the automated solutions. These results may be compared to what we did on the second iteration of our process (see Section V-D. The results are not perfect and show how difficult it can be for human experts to allocate software elements into components.
<table>
<thead>
<tr>
<th>Precision</th>
<th>Recall</th>
<th>F-Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>65%</td>
<td>83%</td>
<td>66%</td>
</tr>
</tbody>
</table>
C. Proposed Solutions For Iteration 1
- **DP1c**: Software engineers identified 64 packages as the core quarks for the 16 composite components. As mentioned in Section V-C, we could easily define rules to automatically identify the core packages based on naming convention of the packages and the presence of some specific software elements (an Ada procedure named run). This is due to the fact that the composite components match high level features of the system which themselves each correspond to some easily recognizable package.
- **DP1**: We experimented three solutions:
- **Declared imports** between packages (Ada instruction with), going from core packages to the packages they import (and transitively);
- **Referenced imports** which are the declared imports backed up by some actual use of the package content, going from core packages to the packages they import (and transitively);
- **Up/Down imports** which are the referenced imports going from core packages to the packages they import (and transitively) and also from core packages to the packages that import them (and transitively). Both paths (up and down) are followed completely from cores without going back. In other terms directions are not mixed.
- **DP3**: We experimented two solutions:
- **With library** where packages in conflict are allocated to a special component called the library (precision and recall are computed for this special component as well as the other);
- **No library** where packages are allowed to remain in conflict and are considered allocated to several composite components and the library components is empty which already means precision and recall will be lower.
<table>
<thead>
<tr>
<th>Decision Points</th>
<th>Precision</th>
<th>Recall</th>
<th>F-Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>DP1c</td>
<td>68%</td>
<td>93%</td>
<td>76%</td>
</tr>
<tr>
<td>DP1</td>
<td>94%</td>
<td>89%</td>
<td>90%</td>
</tr>
<tr>
<td>DP1</td>
<td>25%</td>
<td>3%</td>
<td>6%</td>
</tr>
<tr>
<td>DP1</td>
<td>9%</td>
<td>96%</td>
<td>12%</td>
</tr>
<tr>
<td>DP1</td>
<td>1%</td>
<td>93%</td>
<td>11%</td>
</tr>
</tbody>
</table>
The first conclusion is that precision is much better when we resolve conflict by assigning packages to the library component. This was expected as this library contains 1 001 packages in the oracle that will all hurt the precision metrics if they were not allocated to their library component. Recall is better if we do not assign conflicting packages to the library because it gives a chance to some packages that should not be in the library to be actually allocated to their component. Overall, the loss in precision largely outweighs the gain in recall as shown by the F-Score.
We also see that referenced imports are better than declared imports in terms of precision. The explanation must be that some packages are indeed imported where they are not needed.
and this introduces noise. As expected this improve in precision is made at the expense of the recall but the F-Score still is better for referenced imports. This, therefore, seems to be the solution of choice.
Finally, considering referenced imports both downward and upward from the core packages significantly lowers the results. The explanation is that much more packages can be reached from any core with this solution. Some of them may be correct hits, but many more should not have been reached thus hurting precision. For line 3, recall also diminishes drastically, because with more packages reached from any core, many end up in conflict and are therefore allocated to the library component instead of their right component.
Because of its size (two third of all the packages of the application), including the library in the comparison could impact the precision, recall and F-Score. We decided then to make two comparisons for our chosen solution (line 2 of table VI): a comparison that includes the packages of the library; a comparison that does not include the packages of the library. Table IV shows that precision and F-Score are increased without taking the library into account in the comparison while recall is stable (only a decreasing of on but it is mostly due to the fact that metrics are rounded).
**TABLE IV**
CHOSEN SOLUTION INCLUDING AND NOT INCLUDING LIBRARY COMPONENT IN COMPARISON
<table>
<thead>
<tr>
<th>Precision</th>
<th>Recall</th>
<th>F-Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>$DP^1_r$ Referenced imports</td>
<td>94%</td>
<td>89%</td>
</tr>
<tr>
<td>$DP^1_l$ With library Library in Comparison</td>
<td></td>
<td></td>
</tr>
<tr>
<td>$DP^1_d$ Referenced imports</td>
<td>98%</td>
<td>88%</td>
</tr>
<tr>
<td>$DP^1_c$ With library No Library in Comparison</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Table V gathers precision, recall and F-Score for each composite component of the application (excluding the Library) in case of a comparison like in line 2 of table IV. Name of the composite components are changed to respect the company rules on confidentiality.
Precision is stable for each composite component, except for the composite F. We took a deeper look at this composite and it appears that packages are coming from the others composite. However no general rule can be found to handle this effect. Although recall fluctuates between 70% and 100%, leading the F-Score to also fluctuates, these two metrics stay above 70%.
**D. Proposed Solutions For Iteration 2**
In this Iteration, quarks are subprograms that are allocated to atomic components. One decision in this iteration is that we would not go back on the previous results and leave subprograms in the composite component where their parent packages are allocated. But two subprograms in the same package may be allocated to two different atomic components (within the same composite component). For the evaluation of our solution, we only consider two specific composite components that were fully treated by the software engineers.
$DP^2_r$: Based on some indications by the software engineers, rules were defined using a naming convention on the subprograms to identify core subprograms of some atomic components (the name of the atomic components can be found in the name of some subprograms). In other cases, one package was identified as central to an atomic component and all its subroutines were consequently chosen as core quarks for this component. This work was performed without the direct help of software engineers and therefore, we cannot ensure that our chosen cores are the best we could have defined for each atomic component. The rational was that we wanted to see how well we could do with a more limited understanding of the system. We did had to correct some of our rules after a first try when we obtained results that were not those expected. We believe, this kind of iterative refinement of the core quarks selection is normal and reflects actual working conditions when the software engineers would not have a perfect understanding of the existing system.
$DP^2_r$: We experimented two solutions:
- Downward invocations between subprograms, going from core subprograms to the subprograms they call (and transitively);
- Up/Down invocations going from core subprograms to the subprograms they call (and transitively) and also from core subprograms to the subprograms that call them (and transitively).
$DP^2_c$: We experimented three solutions:
- No action where subprograms are left in conflict. Contrarily to the previous iteration, in this case we consider that subprograms in conflict are not allocated to any atomic component. This is somehow similar to saying they are allocated to a kind of “library atomic component”
although such atomic component does not really exist. The subprograms in conflicts are left to be disambiguated in the next iteration of the process;
- **Variable uses (post)** where some variables were identified that are only used within an atomic component (we say they are endemic to this component). Using these variables, we try to resolve subprograms in conflict by looking if they refer to any of these variables and if so, allocating them to the atomic component related to this variable.
- **Variable uses (during)** where we worked again with variables endemic to an atomic component. But this time, we try to resolve conflicts immediately as they arise during propagation from the cores. If we could resolve the conflict, this allowed us to propagate one step further the allocation to a component. In this setting, the set of endemic variables is recomputed at each step of the propagation and gradually shrink, but it is larger at the beginning, allowing to allocate more subprograms to atomic components.
### TABLE VI
<table>
<thead>
<tr>
<th>Decision Points for Iteration 2</th>
<th>Precision</th>
<th>Recall</th>
<th>F-Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>(DP_{d}^{2}) Downward invocations</td>
<td>57%</td>
<td>51%</td>
<td>51%</td>
</tr>
<tr>
<td>(DP_{r}^{2}) No action</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(DP_{d}^{2}) Downward invocations</td>
<td>60%</td>
<td>49%</td>
<td>51%</td>
</tr>
<tr>
<td>(DP_{r}^{2}) Variables Uses (post)</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(DP_{d}^{2}) Downward invocations</td>
<td>74%</td>
<td>48%</td>
<td>54%</td>
</tr>
<tr>
<td>(DP_{r}^{2}) Variables Uses (during)</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(DP_{d}^{2}) Up/Down invocations</td>
<td>37%</td>
<td>65%</td>
<td>45%</td>
</tr>
<tr>
<td>(DP_{r}^{2}) No action</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(DP_{d}^{2}) Up/Down invocations</td>
<td>53%</td>
<td>58%</td>
<td>52%</td>
</tr>
<tr>
<td>(DP_{r}^{2}) Variables Uses (post)</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(DP_{d}^{2}) Up/Down invocations</td>
<td>53%</td>
<td>62%</td>
<td>57%</td>
</tr>
<tr>
<td>(DP_{r}^{2}) Variables Uses (during)</td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
The first line of result is not very good due to a large number of subprograms in conflict.
Result of the second line are a slightly better, showing that resolving conflicts with endemic variables can improve precision. Unfortunately, there are actually few such variables.
The third line brings much better precision with very little impact on recall. This is due to the fact that we have a larger set of endemic variables at the beginning, when only few subprograms are allocated to an atomic component. This suggest that we might want to be more permissive when computing endemic variables.
The fourth line is interesting because it brings an increase in recall when compared to the first one. This was expected as we gather more subprograms, taking the ones called by the core quarks and the ones that call the core quarks. Precision is low because, as for iteration 1 (Section V-C), a lot more nodes are reached from any core, including some that should not be.
When introducing conflict resolution with the help of endemic variables, we observe the same phenomenon as for line 2: higher precision, lower recall.
Finally, the last experiment raises again the recall, while not affecting precision. This gives the best F-Score over all six experiments.
Results for this iteration are encouraging, but still not satisfying. They are definitely worse than the first try of the experts. However, they were obtain which much less efforts (automated solutions) and by people with a lesser understanding of the system (we are not experts).
We are still working on this iteration to try to get more satisfying results. One direction of possible improvement would be to continue working on the variables, either by loosening the constraint for endemic variables, or finding other interesting data. We noticed for example some “dispatching” subprograms (see also Section IV-C) that allow to distribute the flow of execution over several atomic components. They do this by looking at the value of specific variables. Identifying these variables and the values of interest could help us improve our results, somehow as endemic variables already helped us.
### VI. CONCLUSION AND FURTHER WORK
A large company called us to follow and help in its legacy software migration project. The legacy software had modularisation problems that led the company to decide for a restructuring of the system architecture. The project started, before we stepped in, by the definition of a wished, target architecture at a rather high abstraction level. Then, the engineers and architects performed an informal software architecture migration process from which we pointed out weaknesses that could prevent its reproduction in another migration.
We decided to propose a tool-supported process that remedies these weaknesses. We based the definition of our process on the informal one that we witnessed in the project. Our tool supported solution is an iterative process that combines dependency graph extraction, data uses analysis, and domain knowledge of the re-engineers to select core elements that serve as seed for components. While other research only work with a fixed kind of software elements (typically classes or procedures), our process works with different kinds (packages and subprograms for now).
We identified several points of decision in our process and proposed possible choices at each point. These choices were then evaluated to see which one made more sense.
The next steps of our work will be to improve our results in the second iteration and/or concentrate on the third step that is intended to resolve the conflicts left in the second one. Our main hopes for now will be to analyze data usage in the subprograms to either allocate them to their correct component or understand how to split them into different subprograms each going more clearly into one atomic component.
### ACKNOWLEDGEMENT
We wish to express all our gratitude to people at Thales for helping us understanding their system and evaluating our results.
REFERENCES
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01451242/file/2016-ICSME-Industrial-Paper-Camera-Ready.pdf", "len_cl100k_base": 9995, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 33957, "total-output-tokens": 11519, "length": "2e13", "weborganizer": {"__label__adult": 0.0002841949462890625, "__label__art_design": 0.00036263465881347656, "__label__crime_law": 0.0002446174621582031, "__label__education_jobs": 0.0005550384521484375, "__label__entertainment": 4.178285598754883e-05, "__label__fashion_beauty": 0.00011748075485229492, "__label__finance_business": 0.00016677379608154297, "__label__food_dining": 0.0002440214157104492, "__label__games": 0.0003647804260253906, "__label__hardware": 0.0005092620849609375, "__label__health": 0.0002453327178955078, "__label__history": 0.000179290771484375, "__label__home_hobbies": 5.692243576049805e-05, "__label__industrial": 0.00025200843811035156, "__label__literature": 0.00017559528350830078, "__label__politics": 0.00017845630645751953, "__label__religion": 0.00030732154846191406, "__label__science_tech": 0.004627227783203125, "__label__social_life": 6.222724914550781e-05, "__label__software": 0.004444122314453125, "__label__software_dev": 0.98583984375, "__label__sports_fitness": 0.0001933574676513672, "__label__transportation": 0.0002884864807128906, "__label__travel": 0.00015652179718017578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52701, 0.02258]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52701, 0.37209]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52701, 0.93288]], "google_gemma-3-12b-it_contains_pii": [[0, 991, false], [991, 5925, null], [5925, 11996, null], [11996, 15853, null], [15853, 21921, null], [21921, 28343, null], [28343, 33127, null], [33127, 38109, null], [38109, 42730, null], [42730, 48772, null], [48772, 52701, null]], "google_gemma-3-12b-it_is_public_document": [[0, 991, true], [991, 5925, null], [5925, 11996, null], [11996, 15853, null], [15853, 21921, null], [21921, 28343, null], [28343, 33127, null], [33127, 38109, null], [38109, 42730, null], [42730, 48772, null], [48772, 52701, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52701, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52701, null]], "pdf_page_numbers": [[0, 991, 1], [991, 5925, 2], [5925, 11996, 3], [11996, 15853, 4], [15853, 21921, 5], [21921, 28343, 6], [28343, 33127, 7], [33127, 38109, 8], [38109, 42730, 9], [42730, 48772, 10], [48772, 52701, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52701, 0.19626]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
1e0ed3d1aa60be9ef83cb023a9060541ab2a1ae2
|
GDB Tutorial
University of Waterloo
Version 1.0
Caroline Kierstead and Peter A. Buhr ©*2002
April 1, 2002
*Permission is granted to make copies for personal or educational use
Contents
1 Introduction 3
2 Before Using GDB 3
2.1 Debug Print Statements .................................................. 3
2.2 Errors ........................................................................... 4
3 Getting Started 5
4 Using GDB 5
4.1 Getting Help ................................................................. 5
4.2 Starting a Program ........................................................ 6
4.3 Setting a Breakpoint ....................................................... 6
4.4 Listing Source Code ....................................................... 7
4.5 Printing Variables .......................................................... 7
4.6 Controlling Execution ..................................................... 8
4.7 Controlling Breakpoints ................................................. 9
4.8 Changing Values ............................................................ 9
5 Debugging Example 1 ......................................................... 10
6 Debugging Example 2 ........................................................ 14
A Basic .............................................................................. 16
B ArraySum ....................................................................... 17
C Strings ............................................................................ 17
Index ................................................................................. 21
1 Introduction
This tutorial is designed to give a very basic introduction to the GNU Source-Level Debugger. It is organized with a basic introduction to the debugger commands and then two programs with several errors are debugged using the debugger. By working through the exercises, basic concepts are introduced and can be practiced. The tutorial is not intended as a complete instructional guide. A manual on GDB is available.
GDB can be used in and out of the Emacs environment. It is recommended that GDB be run within Emacs as it is easier to trace the execution of a program. While this tutorial uses GDB within Emacs, additional instructions are given on how to run GDB outside of Emacs; it is assumed that you are familiar with Emacs. As well, you should be familiar with the UNIX environment. (UNIX consultants are available in MC3011.)
Throughout the tutorial, the following symbols are used:
⇒ This symbol indicates that you are to perform the action marked by the arrow.
≈ This symbol indicates that the section explains a concept that may be unfamiliar even if you have some previous experience using a computer (e.g., DOS). Make sure you understand this concept before advancing in the tutorial.
2 Before Using GDB
Before starting any debugger it is important to understand what you are looking for. A debugger does not debug your program for you, it merely helps in the debugging process. Therefore, you must have some idea about what is wrong with a program before starting to look or you will simply waste your time. Furthermore, you should not rely solely on a debugger to debug a program. You may work on a system without a debugger or the debugger may not work for certain kinds of problems. This section discusses traditional approaches to debugging.
2.1 Debug Print Statements
The best way to debug a program is to start by inserting debug print statements as the program is written. It does take a few extra minutes to include debug print statements, but the alternative is wasting hours trying to figure out what the program is doing.
The two aspects of a program that you need to know about are: where the program is executing and what values it is calculating. Debug print statements show the flow of control through a program and print out intermediate values. For example, every routine should have a debug print statement at the beginning and end, as in:
```
int p( . . . ) {
// declarations
cerr << "Enter p( . . . )\n" << parameter variables << endl;
...
cerr << "Exit p: . . .\n" << return value(s) << endl;
return i;
} // p
```
This results in a high-level audit trail of where the program is executing and what values are being passed around. To get finer resolution of a program’s execution, more debug print statements can be included in important control structures, as in:
```
if ( a > b ) {
cerr << "a > b" << endl; // debug print
for ( . . . ) {
cerr << "x=" << x << " , y=" << y << endl; // debug print
} // for
} else {
cerr << "a <= b" << endl; // debug print
...
} // if
```
By examining the control paths the program takes and the intermediate values calculated, it is possible to determine if the program is executing correctly.
Unfortunately, debug print statements can generate enormous amounts of output, far more than is useful.
It is of the highest importance in the art of detection to be able to recognize out of a number of facts which are incidental and which vital.
*Sherlock Holmes, The Reigate Squires*
So gradually comment out debug statements as parts of the program begin to work to remove clutter from the output, but do not delete them until the program works completely. You never know when they will be needed again.
In general, when you go for help, either from your instructor or an advisor, you should have debug print statements in your program. Their presence shows that you have at least attempted to track the problem yourself. If you have no debug print statements, you may be told to come back when you have! Finally, debug print statements never appear in the program you hand in for marking. They are only there to help get the program working.
### 2.2 Errors
Debug print statements do not prevent errors, they simply aid in finding the errors; your programs will still have errors. What you do about an error depends on the kind of error. Errors fall into two basic categories:
**Syntax Errors** are errors in the arrangement of the basic tokens of the programming language. These errors correspond to spelling or punctuation errors when writing in a human language. Fixing syntax errors is usually straightforward especially if the compiler generates a meaningful error message. Always read the error message carefully and check the statement in error.
> You see (Watson), but do not observe.
*Sherlock Holmes, A Scandal in Bohemia*
Watch out for the following general errors:
- Forgetting a closing " or ". The remainder of the program is *swallowed* as part of the character string or comment.
- Missing a { or }. If the program is indented and closing braces are appropriately commented, it is easy to find the missing block delimiter.
- Putting a semi-colon before the keyword word *else*.
**Semantic Errors** are errors in the behaviour or logic of the program. These errors correspond to incorrect meaning when writing in a human language. Semantic errors are harder to find and fix than syntax errors. Often a semantic or execution error message from the runtime libraries only tells why the program stopped not what caused the error. Usually, you must work backwards from the error to determine the cause of the problem.
In solving a problem of this sort, the grand thing is to able to reason backwards. This is very useful accomplishment, and a very easy one, but people do not practise it much. In the everyday affairs of life it is more useful to reason forward, and so the other comes to be neglected.
*Sherlock Holmes, A Study in Scarlet*
For example, this is an infinite loop but there is nothing wrong with the loop, it is the initialization that is wrong.
```c
i = 10;
while ( i != 5 ) {
...
i += 2;
} // while
```
In general, when a program stops with a semantic error, the statement that caused the error is not usually the one that must be fixed.
Watch out for the following general errors:
- Forgetting to assign a value to a variable before using it in an expression.
• Using an invalid subscript or pointer value.
Finally, if a statement appears not to be working properly, but looks correct, check the syntax.
```c
if ( a = b ) {
cerr << "a == b" << endl;
} // if
```
When you have eliminated the impossible whatever remains, however improbable must be the truth.
*Sherlock Holmes, Sign of Four*
An interactive debugger effectively allows debug print statements to be added and removed to/from a program dynamically, as will be seen shortly. However, a good programmer usually uses a combination of debug print statements and an interactive debugger when debugging a complex program.
### 3 Getting Started
You need the following files for this tutorial:
- Copy the following files to some location under your home directory:
- `/u/cssystems/examples/gdb_basic.cc`
- `/u/cssystems/examples/gdb_q1.cc`
- `/u/cssystems/examples/gdb_q2.cc`
- `/u/cssystems/examples/data1`
- `/u/cssystems/examples/data2`
To start GDB within Emacs, enter the command
```
M-x gdb <Return>
```
and you will be prompted in the mini-buffer for the name of an executable file to be debugged. To start GDB outside of Emacs, the general format of the command is:
```
gdb executable-file-name
```
### 4 Using GDB
- Start up Emacs and create a buffer containing the file `gdb_basic.cc`.
This program’s sole purpose is to demonstrate the debugger commands; the program itself does nothing in particular (see Appendix A).
- Compile the program using the command:
```
g++ -g gdb_basic.cc
```
The `-g` option includes additional information for symbolic debugging.
- Enter the command: `M-x gdb <Return>`.
- Enter the name of the program’s executable, `./a.out`, after the prompt in the mini-buffer and press `<Return>`.
GDB responds with a number of messages and with the GDB prompt, `(gdb)`.
#### 4.1 Getting Help
To obtain help in GDB use the command `help`. The information is divided by topic. (NOTE: All commands in GDB are executed when `<Return>` is pressed.)
- Enter the command: `help`
GDB responds with the following list of command classes:
List of classes of commands:
- aliases -- Aliases of other commands
- breakpoints -- Making program stop at certain points
- data -- Examining data
- files -- Specifying and examining files
- internals -- Maintenance commands
- obscure -- Obscure features
- running -- Running the program
- stack -- Examining the stack
- status -- Status inquiries
- support -- Support facilities
- tracepoints -- Tracing of program execution without stopping the program
- user-defined -- User-defined commands
Type "help" followed by a class name for a list of commands in that class.
Type "help" followed by command name for full documentation.
Command name abbreviations are allowed if unambiguous.
4.2 Starting a Program
⇒ Enter the command: help run
GDB responds with:
Start debugged program. You may specify arguments to give it.
Args may include "*", or "[. . .]"; they are expanded using "sh".
Input and output redirection with ">", "<", or ">>" are also allowed.
With no arguments, uses arguments last specified (with "run" or "set args").
To cancel previous arguments and run with no arguments,
use "set args" without arguments.
⇒ Enter the command: run
GDB responds with a message indicating which object file it is executing and that it executed normally. When there are no errors in a program, running it via GDB is the same as running it in a shell.
4.3 Setting a Breakpoint
In order to trace the execution of the program, breakpoints are required. A breakpoint causes suspension of the program's execution when that location is reached. Breakpoints can be set on routines, line numbers and addresses. They are numbered consecutively from 1 up and can be enabled or disabled as required by using the enable, disable, and delete commands.
In order to allow the execution to be traced, set a breakpoint in the first routine that is executed, main.
⇒ Enter the command: break main or b main
GDB responds with:
(gdb) break main
Breakpoint 1 at 0x10624: file gdb_basic.cc, line 24.
indicating that breakpoint number 1 has been set at location 0x10624, which is line 24 of the file gdb_basic.cc. If a program is not compiled with the -g flag, only the address location is given.
⇒ Enter the command: run
The program is restarted (it was run once already) and execution continues until the first breakpoint is reached. The breakpoint is at the first executable line within main, line 24. Your screen will have split horizontally and the source code about to be executed is displayed with an arrow (=>). (The arrow may cover the first two characters of the current line of code.)
### 4.4 Listing Source Code
When not executing GDB in Emacs, the source file does not appear in another window. To list source code around the execution location, use the `list` command.
⇒ Enter the command: list 24 or l 24.
GDB responds with:
```
(gdb) list 24
19 return r;
20 }
21 }
22
23 int main() {
24 int r, x = 1;
25 mary m;
26 r = m.bar( x );
27 return 0;
28 }
```
### 4.5 Printing Variables
The `print` command is used to print the values of variables accessible in the current routine, plus all those whose declared in the global/external area.
⇒ Print the contents of variable `r` by entering the command: print `r` or p `r`.
GDB responds with:
```
(gdb) p r
$1 = 0
```
The value of `r` is 0. The `$1` is the name of a history variable (like history variables in a shell). The name `$1` can be used in subsequent commands to access previous values of `r`.
The value to be printed may be any C++ expression, so if the variable is a pointer, the pointer and the value it references are printed with the commands:
```
(gdb) print p
(gdb) print * p
```
(Unfortunately, a list of variables is taken to be a C++ language “comma expression” and only the last value in the list is printed.)
During debugging, it is often necessary to print certain variables each time the program stops at a breakpoint. This requires typing in a series of `print` commands each time the program stop. The `display` command is like the `print` command, and in addition, it prints the specified variable each time the program stops.
⇒ Enter the command: display `r` or disp `r`
GDB responds with:
```
(gdb) disp r
1: r = 0
```
⇒ Enter the command: display `x` or disp `x`
Each displayed variable is numbered, in this case, \( r \) is numbered 1 and \( x \) is numbered 2. The number is used to stop displaying a variable using the undisplay \( n \) command.
Note: variables \( r \) and \( x \) have not yet been initialized. The values displayed are that of the memory where the variables are allocated. Sometimes the values are 0, and sometimes they are not. Do not assume that the values are always 0.
4.6 Controlling Execution
Once a breakpoint is reached, execution of the program can be continued in several ways.
<table>
<thead>
<tr>
<th>Command</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>step [n]</code></td>
<td>Execute the next ( n ) lines of the program and stop. If ( n ) is not present, 1 is assumed. If the next line is a routine call, control stops at the first line in that routine. Abbreviated to <code>s</code>.</td>
</tr>
<tr>
<td><code>next [n]</code></td>
<td>Like <code>step</code>, but routine calls are treated as a single statement, so control stops at the statement after the routine call instead of the first statement of the called routine. Abbreviated to <code>n</code>.</td>
</tr>
<tr>
<td><code>continue</code></td>
<td>Continue execution until the next breakpoint is reached. Abbreviated to <code>c</code>.</td>
</tr>
<tr>
<td><code>finish</code></td>
<td>Finish execution of the current routine and stop at the statement after the routine call. Print the value returned by the finished routine, if any. Abbreviated to <code>fin</code>.</td>
</tr>
</tbody>
</table>
⇒ Step to the next line to be executed.
Notice that the arrow (=>) has moved and the variables \( r \) and \( x \) are printed (\( x \) has changed). The program has now stopped execution on the line \( r = m.bar( x ); \):
⇒ Step into routine `mary::bar`.
GDB responds with:
```
(gdb) s
mary::bar (this=0xffbefaf7, x=1) at gdb_basic.cc:17
```
indicating that execution has stopped within `mary::bar` at line 17, and that `bar` has a single parameter, \( x \), containing the value 1. Also the arrow has moved to line 17 in the buffer containing `gdb_basic.cc`.
⇒ Display the values of variables \( x \) and \( r \).
⇒ Step to the next line.
⇒ Step into routine `fred::foo`.
GDB responds with:
```
(gdb) s
fred::foo (this=0xffbefaf7, x=2) at gdb_basic.cc:5
```
⇒ Display the variable \( i \).
⇒ Set a breakpoint at line 8 (`return x;`).
⇒ Enter the command: `step 4` or `s 4`.
⇒ Continue to the next breakpoint by entering the command: `cont` or `c`.
⇒ Print the contents of variable \( x \). Why is the value 7?
⇒ Enter the command: `step 2` or `s 2`.
Control has returned to routine `mary::bar`, which is about to return a value of 7. From the display statements, it can be seen that the changes to \( x \) in `fred::foo` have not affected \( x \) in `mary::bar` because \( x \) was passed by value.
⇒ Continue execution.
GDB responds with:
```
(gdb) c
Continuing
```
Program exited normally
Notice that the arrow has not moved to the end of the routine `main`.
Set a breakpoint at line 28.
Set a breakpoint in routine mary::bar by entering the command: break mary::bar
Run the program again.
Enter the command step 3 to move you to the line r = f.foo(x);
Enter the command next or n to step over the call to routine fred::foo.
Why did execution stop in fred? (Because there is a breakpoint at line 8.)
Enter the command finish to complete execution of routine fred.
GDB responds with:
Run till exit from #0 fred::foo (this=0xffbefaf7, x=7) at gdb_basic.cc:8
0x10718 in mary::bar (this=0xffbefaf7, x=2) at gdb_basic.cc:18
4: r = 0
3: x = 2
Value returned is $3 = 7
which indicates that fred::foo is returning the value 7 as it finishes. Control now returns to routine mary::bar.
Press <Return>. This repeats the last command, which was finish.
GDB responds with:
(gdb)
Run till exit from #0 0x10718 in mary::bar (this=0xffbefaf7, x=2) at gdb_basic.cc:18
0x10640 in main () at gdb_basic.cc:26
2: x = 1
1: r = -268436580
Value returned is $4 = 7
which indicates that mary::bar is returning the value 7 as it finishes.
Continue until execution of the program completes.
4.7 Controlling Breakpoints
Enter the command info breakpoints to obtain information on the breakpoints currently set.
GDB responds with:
Num Type Disp Enb Address What
1 breakpoint keep y 0x00010624 in main at gdb_basic.cc:24
breakpoint already hit 1 time
2 breakpoint keep y 0x00010778 in fred::foo(int) at gdb_basic.cc:8
breakpoint already hit 1 time
3 breakpoint keep y 0x0001065c in main at gdb_basic.cc:28
breakpoint already hit 1 time
3 breakpoint keep y 0x00010704 in mary::bar(int) at gdb_basic.cc:17
breakpoint already hit 1 time
In order to avoid stopping at the breakpoint on line 8, disable it by entering the command: disable 2
Disable breakpoint 4.
4.8 Changing Values
The set command changes the values of variables in the current routine or global/external variables.
Run the program again.
Step to the next line.
Change the initial value of x to 6 by entering the command: set x = 6
Continue execution.
Notice how the value of \( r \) is larger. In this way, it is possible to change the values of variables while debugging to investigate how the program behaves with new values instead of having to restart the debugging process or change and recompile the program.
\[ \text{Continue the program.} \]
\[ \text{Quit out of GDB. If using Emacs, enter the command C-x k; otherwise, enter the command quit or q.} \]
\[ \text{Close the \texttt{gdb\_basic.cc} buffer.} \]
5 Debugging Example 1
\[ \text{Create a buffer within Emacs containing the file \texttt{gdb\_q1.cc}.} \]
This program calculates the sum of an array of size \( n \), given \( n \) (see Appendix B), and it currently contains some errors. The program is terminated by entering either the end of file key sequence (C-c C-d in Emacs, or <CTRL>-d in the Unix shell) or the sentinel value -999.
\[ \text{Notice the compilation error message displayed in the compilation buffer.} \]
\[ \text{gdb\_q1.cc:38: unterminated string or character constant} \]
\[ \text{gdb\_q1.cc:22: possible real start of unterminated constant} \]
The compiler believes that a string or character constant is not terminated in line 38.
\[ \text{Go to line 38. Since the error probably consists of a missing quotation mark, start by examining line 38.} \]
\[ \text{cout} \text{ << array[i] } \text{<< "} \text{ is "} \text{<< returnvalue } \text{<< endl;} \]
Examining line 38 of the code, it is clear that the string on that line is terminated properly! Therefore, the error comes from a previous line that contained a string that is not terminated properly. Start searching from line 22 forwards, as indicated by the second compiler error message.
\[ \text{Make the required correction.} \]
\[ \text{Save the program.} \]
\[ \text{Compile the program.} \]
Having achieved a successful compilation:
\[ \text{Start up GDB on the program’s executable, a.out.} \]
\[ \text{Enter the command: run} \]
\[ \text{Enter the number 5 in response to the prompt Enter the size of the array to sum [<CTRL>-D or -999 for EOF]:} \]
\[ \text{and press <Return>.} \]
\[ \text{Enter a number at the next prompt, Enter value [1].} \]
GDB responds with:
\[ \text{(db) run} \]
\[ \text{Starting program: /u/cssystems/tutorial/GDB/C++/a.out} \]
\[ \text{Enter the size of the array to sum [<CTRL>-D or -999 for EOF]: 5} \]
\[ \text{Enter value [1] 1} \]
Program received signal SIGSEGV, Segmentation fault.
0xffffffff in \texttt{istream::operator>}> (this=0x20ed0, i=0x4) at \texttt{iostream.cc:352} 352 \texttt{iostream.cc: No such file or directory.} \]
The program received a “Segmentation fault” signal at address 0x6ff738e in routine \texttt{istream::operator>>}. This message often indicates a pointer addressing problem.
\[ \text{Enter the command where to receive more information about the location of the error in the program.} \]
GDB responds with:
```
(gdb) where
#0 0xff153974 in istream::operator>> (this=0x20ed0, i=@0 x4) at iostream.cc:352
#1 0x108c0 in readInArrayAndSum (array=0x4, size=1) at gdb_q1.cc:11
#2 0x109cc in main () at gdb_q1.cc:32
```
This information is about the *stack frames*. A *frame* is the data associated with a call to a routine. It contains the arguments passed to the routine, variables local to the routine, and the executing routine’s address.
Upon starting a program, the stack has only one frame (the *outer-most frame*) which is for routine *main*. A new frame is created for each routine called. The frame labeled 0 (the *inner-most frame*) is the most recently created frame.
In this example, frame 0 involves the I/O output operator, `>>`. This routine is invoked by the routine `readInArrayAndSum` in frame 1. The information associated with frame 2 gives the file name containing the program (`gdb_q1.cc`). Each frame also gives a line number. This number is either the line on which the error occurred, or the line from which the routine containing the error was invoked. The frame for the I/O operator `>>` has no file and line numbers because it was not compiled with the `-g` flag. As a result, GDB cannot display the source code where the error occurred. Therefore, you have to manually begin the search in your program.
⇒ Enter frame 2 by typing: `frame 2` or `f 2`
⇒ List line 32.
```
27 if ( !cin.good() ) {
28 cerr << "\nERROR: cannot have char or string for the array size\n";
29 exit(2);
30 } // if
31 int *array;
32 int returnValue = readInArrayAndSum(array, size);
33 cout << "\nsum of [";
34 int i;
35 for (i = 0; i < size-1; i += 1) {
36 cout << array[i] << ", ";
```
Line 32 is the invocation of `readInArrayAndSum`. Since it appears correct, move into the frame associated with the routine and examine its associated information.
⇒ Enter frame 1.
GDB responds with
```
(gdb) frame 1
#1 0x108c0 in readInArrayAndSum (array=0x4, size=1) at gdb_q1.cc:11
```
You should notice that the address associated with the parameter `array` looks a bit odd.
⇒ Try printing the element at index 1.
GDB responds with
```
(gdb) print array[1]
Cannot access memory at address 0x4
```
So, the address contained in `array` is invalid.
⇒ Make the buffer containing `gdb_q1.cc` visible.
⇒ Go to line 31 (`C-x @` command).
⇒ The declaration of `array` doesn’t actually allocate any space. Change the declaration to read `int array[size];` instead.
⇒ Save and recompile the file.
⇒ Create buffer containing `data1` and examine its contents.
⇒ Make the the `*gdb-a.out*` buffer visible in a window.
⇒ Run the program again, but now use a data file for the input. Use the command: `run < data1` What does the `< data1 do after the run command? You will be prompted to restart it. Why is this essential?
Is the program working correctly? No, we still have a segmentation fault.
- Print the value of i. You should see that it is significantly larger than 10, the size of the array.
- Correct the code by changing the increment of i on line 9 to be by one rather than by two.
- Recompile the code.
- Run the program as before by entering just run on the GDB command line. Be aware that entering run is equivalent to run < data1 (see help run).
Is the output correct given the contents of data1? No, the output just have been a single sum, not two, and the single sum should have been 10, not 9. To determine the exact location of the error, the execution of the program needs to be traced. The error is likely to be in readInArrayAndSum since that routine handles the input and summation.
- Enter the command: break readInArrayAndSum.
- Run the program as before.
The program continues execution until the first breakpoint is reached.
The following code is displayed in the gdb_q1.cc buffer:
```
#include <iostream.h>
int readInArrayAndSum( int * array, int size ) {
int sum = 0;
for ( int i = 1; i != size; i += 1 ) {
cout << "\nEnter value: ";
cin >> array[i];
sum += array[i];
} // for
return sum;
} // readInArrayAndSum
```
GDB tells you the values of the parameters array and size.
To trace the values of the variables that readInArrayAndSum() uses as they change, use the display command.
- Step through the next two statements by using the next 2 command.
- Display the variables i, sum, and array[i].
- Step through the next statement, cout << "\nEnter value [" << i << "] ";
- Step through the next statement, cin >> array[i];.
- Step through the next statement, sum += array[i];.
- Step to the next statement, the for loop. sum is now set to 1, the value in array[1]. So far, everything seems appropriate.
- Notice that the parameter to readInArrayAndSum indicates that 10 values will be read in. We don’t want to step through all of the statements, we want to concentrate on the final stages of our loop, so set a break point on line 13.
- Continue to the next breakpoint.
- Bypass the next 8 crossings of the breakpoint by entering cont 8
GDB responds with
(gdb) cont 8
Will ignore next 7 crossings of breakpoint 3. Continuing.
Enter value:
Enter value:
Enter value:
Enter value:
Enter value:
Enter value:
Enter value:
Enter value:
Enter value:
Breakpoint 3, readlnArrayAndSum (array=0xffbafac8, size=10) at gdb_q1.cc:13
3: array[i] = 1
2: sum = 9
1: i = 9
⇒ Step to the next instruction. Suddenly, we’re about to return sum instead of executing the loop one more time.
⇒ Print the value of array.
⇒ Print the address of the element at index 1 of array.
GDB responds with
(gdb) print array
$1 = (int *) 0xffbefac8
(gdb) print &(array[1])
$2 = (int *) 0xffbefacc
These two addresses do not match. So, the array actually starts one position earlier, at index 0.
⇒ Change the initialization of i in the for loop to 0 rather than 1.
⇒ Save and compile the code.
⇒ Move back to the *gdb-a.out* buffer.
⇒ Run the program again. You will be prompted to restart it. The program stops at the breakpoint in readlnArrayAndSum.
⇒ Delete breakpoints 1 and 2.
⇒ Continue execution.
Does the code work correctly now? The sum is calculated correctly, but the array is not printed out correctly.
⇒ List line 32, since the print loop is in that general vicinity.
⇒ Put a break point on line 34.
⇒ Run the program again.
⇒ When you reach the loop, display variable i.
⇒ Step through the loop. Notice that the value of i has suddenly reached 9.
While the for loop appears to be correct, there is a very subtle error, which is the semi-colon at the end of the for line terminating the loop body; therefore, the code in the braces is simply a block separate from the for statement. In other words, the for loop executes until it is done, and then the code within the braces is executed.
⇒ Remove the semi-colon from the end of the for statement.
⇒ Save and compile the code.
⇒ Move back to the *gdb-a.out* buffer.
⇒ Run the program again.
Does the code work correctly now?
⇒ Close all of the current buffers.
6 Debugging Example 2
⇒ Create a buffer containing the file gdb_q2.cc.
This program reads in strings, and stores the string alphabetically, along with its number of occurrences, in a linked list (see Appendix C). The program currently contains some errors.
⇒ Compile the code by using the command: g++ -g gdb_q2.cc.
⇒ Create a buffer containing file data2 and examine the data.
⇒ Start up GDB on the program’s executable, a.out.
⇒ Enter the command: run data2
GDB responds with:
(gdb) run data2
Starting program: /u3/ctkierstead/GDB/a.out data2
Program received signal SIGSEGV, Segmentation fault.
basic_string<char, string_traits<char>, __default_alloc_template<false, 0>>::rep (this=0x1) at /software/arch/gcc-2.95.2/distribution/lib/gcc-lib/sparc-sun-solaris2.6/2.95.2/././.include/g++-3/std/bastring.h:147
with the arrow on a line in the string library.
An error of “Segmentation Fault” usually indicates a problem with a pointer.
⇒ It is unlikely the string library has a bug, so let’s determine where the offending call was made. Use the where command.
GDB responds with:
(gdb) where
#0 basic_string<char, string_traits<char>, __default_alloc_template<false, 0>>::rep (this=0x1) at /software/arch/gcc-2.95.2/distribution/lib/gcc-lib/sparc-sun-solaris2.6/2.95.2/././.include/g++-3/std/bastring.h:147
#1 0x14b88 in basic_string<char, string_traits<char>, __default_alloc_template<false, 0>>::basic_string (this=0xe0fff998, str=@0x1) at /software/arch/gcc-2.95.2/distribution/lib/gcc-lib/sparc-sun-solaris2.6/2.95.2/././.include/g++-3/std/bastring.h:172
#2 0x14df0 in ListNode::getWord (this=0x1) at gdb_q2.cc:20
#3 0x13170 in ListADT::searchInsert (this=0xe0fff6b1c, word={static npos = 4294967295, static nilRep = {len = 0, res = 0, ref = 1, selfish = false}, dat = 0x27d20 "This"}) at gdb_q2.cc:112
#4 0x12128 in ListADT::ListADT (this=0xe0fff6b1c, fileName=0xe0fffcc6 "data2") at gdb_q2.cc:78
#5 0x12d30 in main (argc=2, argv=0xe0fff9d4) at gdb_q2.cc:49
The call listed in frame 2 has an invalid address assigned to the internal object pointer, this. So, the error probably came from the previous frame.
⇒ Use the frame 3 command to enter the frame so we can examine the previous frame’s values.
GDB puts the arrow on the following line:
⇒ if ( head == NULL || head->getWord() > word ) {
Since it was the call to getWord that failed, and the method was being called on head, the problem likely lies with head.
⇒ Print the contents of head. This is the first word that we are inserting into the list, and yet head contains an address of 1 rather than the expected 0.
⇒ Find the initialization of head in ListADT’s constructor. Replace the statement (ListNode*) 1 with NULL.
⇒ Recompile the code and try running the program again.
Is the program correct? No, since no information is output for the list. Either the list is empty, or there is something wrong with the printing of its contents. The execution of the program must be traced in order to pinpoint the problem by setting some breakpoints and observing what happens when the code is run.
⇒ Set a breakpoint at line 112. This location is at the start of the insertion routine (If you had written the program, you would know this.) We could have set a breakpoint at line 78, just after the first word is read in; however, when we step into searchInsert, we’d have to first get through a number of string library calls.
Run the program again.
GDB stops at the breakpoint. To ensure that the list is being correctly maintained, print the value of head, which should be 0x0/NULL.
Display the object pointed to by the pointer head using the command display *head. (GDB will complain that it cannot display a NULL pointer and will disable the display.)
Display the value of head instead. We can always turn the other display back on later. The pointer to the top of the list is still NULL, which is correct for inserting the first token.
Step through the next 3 lines using the next command (watch the arrow), carefully observing the value of head. head suddenly went from a non-zero value back to 0x0. This indicates an error with the if statement. Close examination of the if statement reveals that an assignment operator appears where an equals operator should be. Instead of ==, = is used which assigns the value of NULL to *head and causes the program lose all previous information stored in the list.
Correct the error.
Save and compile the program.
Enter the *gdb-a.out buffer.
Run the program again. (You will be prompted to restart it.) The program stops at the breakpoint in main.
Delete breakpoint 1 and continue execution.
The program now runs properly.
Before leaving GDB, two more useful features are worth mentioning: the ability to print out structures and the ability to easily follow pointers and print out the objects pointed to.
Enter buffer gdb_q2.cc
Move the cursor down to the line myList.printList();
Enter the command: M-x what-line <Return>. The line number of the line containing the cursor is printed in the mini-buffer.
Set a breakpoint at this line.
Run the program again.
Enter the command: p *myList.head
GDB responds with:
```
$1 = {token = {static npos = 4294967295, static nilRep = {len = 0, res = 0, ref = 1, selfish = false},
dat = 0x27f60 "Either"}, timesFound = 1, next = 0x28388}
```
Enter the command: set print pretty to print structures in a nice format.
Print *myList.head again.
GDB responds with:
```
$2 = {
token = {
static npos = 4294967295,
static nilRep = {
len = 0,
res = 0,
ref = 1,
selfish = false
},
dat = 0x27f60 "Either"
},
timesFound = 1,
next = 0x28388
}
```
Enter the command: print *myList.head.next:
GDB responds with:
$$3 = \{
\text{token} = \{
\text{static npos} = 4294967295,
\text{static nilRep} = \{
\text{len} = 0,
\text{res} = 0,
\text{ref} = 1,
\text{selfish} = \text{false}
\},
\text{dat} = 0x27f00 "Some"
\},
\text{timesFound} = 1,
\text{next} = 0x28220
\}$$
⇒ Enter the command: print *$3.next:
GDB responds with:
$$4 = \{
\text{token} = \{
\text{static npos} = 4294967295,
\text{static nilRep} = \{
\text{len} = 0,
\text{res} = 0,
\text{ref} = 1,
\text{selfish} = \text{false}
\},
\text{dat} = 0x27d20 "This"
\},
\text{timesFound} = 1,
\text{next} = 0x28268
\}$$
Notice the use of a history variable to save typing. This can be continued until the end of the list is reached, allowing a user to verify that the data structure is set up correctly.
⇒ Enter the command: cont
⇒ Close all of Emacs buffers.
⇒ Terminate Emacs by using the C-x C-c command.
A Basic
class fred {
public:
int foo( int x ) {
int i;
for ( i = 1; i <= 5; i += 1 ) {
x += 1;
} // for
return x;
} // foo
};
class mary {
fred f;
public:
int bar( int x ) {
int r;
x += 1;
} // bar
```cpp
int main() {
int r, x = 1;
mary m;
r = m.bar(x);
return 0;
}
B ArraySum
/**************************************************
** GDB Test File 1 - contains several errors
**************************************************
#include <iostream.h>
int readInArrayAndSum(int *array, int size) {
int sum = 0;
for (int i = 1; i != size; i += 2) {
cout << "Enter value [" << i << "] ";
cin >> array[i];
sum += array[i];
} // for
return sum;
} // readInArrayAndSum
/**************************************************
** GDB Test File 2 - contains a few errors
**************************************************
#include <iostream.h>
#include <fstream.h>
#include <string>
```
class ListNode {
string token;
int timesFound; // Times that token has been found
ListNode *next; // Next node in the list
public:
ListNode(string word) : token(word), timesFound(1), next(NULL) {}
ListNode(string word, ListNode *next) : token(word), timesFound(1), next(next) {}
~ListNode() { if (next != NULL) delete next; }
string getWord() { return token; }
int getNumOccurrences() { return timesFound; }
void incNumOccurrences() { timesFound++; }
ListNode *getNext() { return next; }
void setNext(ListNode *next) { ListNode::next = next; }
};
class ListADT {
ListNode *head; // Head of the list
public:
ListADT(char *fileName); // Initialize the list from the specified file
~ListADT();
bool findWord(string word);
void searchInsert(string word);
void printList();
};
int main(int argc, char *argv[]) {
// Must have an input file specified on the command line.
if (argc != 2) {
cerr << argv[0] << " input-file" << endl;
exit(-1);
}
ListADT myList(argv[1]); // List of words.
cout << "The linked list contains:" << endl;
myList.printList();
} // main
class ListADT { // Head of the list
ListADT( char *fileName ); // Initialize the list from the specified file
~ListADT();
bool findWord( string word );
void searchInsert( string word );
void printList();
};
/*----------------------------- Class Implementations -----------------------------*/
Builds a list of words contained in the specified input file.
Input: name of the input file
Output: builds a list where head contains the address of the first node
Error: program ends with error message and exit code -2 if the file could not be opened for input.
ListADT::ListADT( char *fileName ) {
head = (ListNode *) 1; // Initialize list to empty.
string word;
ifstream inFile(fileName, ios::in); // Open input file
if (inFile) {
cerr << "File " << fileName << " could not be opened for input." << endl;
exit(-2);
} // if
while (true) {
string word; // Read each word
inFile >> word; // Use default whitespace delimiter
if (inFile) {
// Increment the timesFound field
if (myList.findWord(word)) {
myList.searchInsert(word);
}
}
} // while
inFile.close(); // Close input file
} // ListADT::ListADT
infile >> word;
if ( infile.eof() ) break;
searchInsert( word );
} // while
} // ListADT::ListADT
/*******************************************************************************************/
Determines if the specified word is in the list or not.
Input: word to be searched for
Output: flag indicating whether a word has been found or not.
Errors: N/A
*******************************************************************************************/
bool ListADT::findWord( string word ) {
bool foundWord = false;
for ( ListNode * ptr = head; ptr != NULL && !foundWord; ptr = ptr->getNext() ) {
if ( ptr->getWord() == word ) {
foundWord = true;
} // if
} // for
} // ListADT::findWord
/*******************************************************************************/
Searches the list for the word. If the word is in the list, the
repetition count of the word is incremented. Otherwise, the word is
added to the list.
Input: Pointer to the start of the list - ListHead
Pointer to the buffer which contains the word - Token
Output: A list of words with their frequencies of occurrence
Errors: If no space for new word, then print message and exit program
*******************************************************************************/
void ListADT::searchInsert( string word ) {
ListNode * newNode, * temp, * prev;
int value;
if ( head == NULL || head->getWord() > word ) {
head = new ListNode( word, head );
if ( head == NULL ) { // Ran out of space.
cerr << "ERROR: ran out of space\n";
exit(-3);
} // if
} else if ( head->getWord() == word ) {
head->incNumOccurrences();
} else {
newNode = new ListNode( word );
if ( newNode == NULL ) { // Ran out of space.
cerr << "ERROR: ran out of space\n";
exit(-3);
} // if
prev = head;
for ( temp = head->getNext(); temp != NULL; temp = temp->getNext() ) {
if ( word == temp->getWord() ) {
temp->incNumOccurrences();
break;
} else if ( word < temp->getWord() ) {
newNode->setNext( temp );
prev->setNext( newNode );
break;
} // if
prev = temp;
} // for
if ( temp == NULL && prev != NULL ) { // Fell off list
prev->setNext( newNode );
} // if
} // else
} // ListADT::SearchInsert
Prints the list with the word repetition counts.
**Input:** N/A
**Output:** The words and their frequencies of occurrence.
```cpp
void ListADT::printList() {
for ( ListNode * ptr = head; ptr != NULL ; ptr = ptr->getNext() ) {
cout << "word: " << ptr->getWord() << " occurs " << ptr->getNumOccurrences() << " time(s) " << endl;
} // for
} // ListADT::printList
```
Deletes the list.
**Input:** N/A
**Output:** The list has been freed.
```cpp
ListADT::~ListADT () {
if ( head != NULL ) {
delete head;
} // if
} // ListADT::~ListADT
```
Index
⇒, 3
▷, 3
<Return>, 9
break, 6, 12
breakpoint, 6
continue, 8
delete, 6
disable, 6
enable, 6
finish, 8
next, 8
step, 8
continue, 8
display, 7, 12
enable, 6
execution error, 4
finish, 8, 9
gdb
<Return>, 9
break, 6
breakpoint, 6
continue, 8
delete, 6
disable, 6
enable, 6
finish, 8
next, 8
step, 8
continue, 8
delete, 6
disable, 9
display, 7
enable, 6
finish, 8
finish, 9
help, 5
info, 9
list, 7
next, 8
print, 7
run, 6
set, 9
stack frame, 11
step, 8
undisplay, 8
where, 10
gdb, 5
help, 5
info, 9
inner-most frame, 11
list, 7
next, 8
outer-most frame, 11
print, 7
run, 6
semantic error, 4
set, 9
stack frame, 11
step, 8
syntax error, 4
undisplay, 8
unix consultant, 3
where, 10
|
{"Source-Url": "https://www.student.cs.uwaterloo.ca/~cs343/documents/C++GDBTutorial.pdf", "len_cl100k_base": 11227, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 50916, "total-output-tokens": 12694, "length": "2e13", "weborganizer": {"__label__adult": 0.0003223419189453125, "__label__art_design": 0.00034165382385253906, "__label__crime_law": 0.00014650821685791016, "__label__education_jobs": 0.0010356903076171875, "__label__entertainment": 8.761882781982422e-05, "__label__fashion_beauty": 0.0001093745231628418, "__label__finance_business": 7.301568984985352e-05, "__label__food_dining": 0.0002617835998535156, "__label__games": 0.0013561248779296875, "__label__hardware": 0.0007653236389160156, "__label__health": 0.00016009807586669922, "__label__history": 0.0001475811004638672, "__label__home_hobbies": 8.273124694824219e-05, "__label__industrial": 0.00017559528350830078, "__label__literature": 0.00022077560424804688, "__label__politics": 8.803606033325195e-05, "__label__religion": 0.0003864765167236328, "__label__science_tech": 0.0024433135986328125, "__label__social_life": 7.605552673339844e-05, "__label__software": 0.01105499267578125, "__label__software_dev": 0.97998046875, "__label__sports_fitness": 0.00021791458129882812, "__label__transportation": 0.0002334117889404297, "__label__travel": 0.0001646280288696289}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 42999, 0.03707]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 42999, 0.46359]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 42999, 0.79429]], "google_gemma-3-12b-it_contains_pii": [[0, 181, false], [181, 1654, null], [1654, 4893, null], [4893, 8112, null], [8112, 10146, null], [10146, 12417, null], [12417, 14486, null], [14486, 17280, null], [17280, 19319, null], [19319, 22190, null], [22190, 25019, null], [25019, 27233, null], [27233, 29175, null], [29175, 32576, null], [32576, 34938, null], [34938, 36086, null], [36086, 36820, null], [36820, 39254, null], [39254, 41725, null], [41725, 42300, null], [42300, 42999, null]], "google_gemma-3-12b-it_is_public_document": [[0, 181, true], [181, 1654, null], [1654, 4893, null], [4893, 8112, null], [8112, 10146, null], [10146, 12417, null], [12417, 14486, null], [14486, 17280, null], [17280, 19319, null], [19319, 22190, null], [22190, 25019, null], [25019, 27233, null], [27233, 29175, null], [29175, 32576, null], [32576, 34938, null], [34938, 36086, null], [36086, 36820, null], [36820, 39254, null], [39254, 41725, null], [41725, 42300, null], [42300, 42999, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 42999, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 42999, null]], "pdf_page_numbers": [[0, 181, 1], [181, 1654, 2], [1654, 4893, 3], [4893, 8112, 4], [8112, 10146, 5], [10146, 12417, 6], [12417, 14486, 7], [14486, 17280, 8], [17280, 19319, 9], [19319, 22190, 10], [22190, 25019, 11], [25019, 27233, 12], [27233, 29175, 13], [29175, 32576, 14], [32576, 34938, 15], [34938, 36086, 16], [36086, 36820, 17], [36820, 39254, 18], [39254, 41725, 19], [41725, 42300, 20], [42300, 42999, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 42999, 0.00736]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
19ddda981fcce26981f6366c5add36b59cb98804
|
Energy Transparency for Deeply Embedded Programs
Kyriakos Georgiou\textsuperscript{1}, Steve Kerrison\textsuperscript{1}, Zbigniew Chamski\textsuperscript{2}, Kerstin Eder\textsuperscript{1}
\textsuperscript{1} University of Bristol
\textsuperscript{2} Infrasoft IT Solutions, Poland
Abstract. Energy transparency is a concept that makes a program’s energy consumption visible, from hardware up to software, through the different system layers. Such transparency can enable energy optimizations at each layer and between layers, and help both programmers and operating systems make energy-aware decisions. In this paper, we focus on deeply embedded devices, typically used for Internet of Things (IoT) applications, and demonstrate how to enable energy transparency through existing Static Resource Analysis (SRA) techniques and a new target-agnostic profiling technique, without hardware energy measurements. Our novel mapping technique enables software energy consumption estimations at a higher level than the Instruction Set Architecture (ISA), namely the LLVM Intermediate Representation (IR) level, and therefore introduces energy transparency directly to the LLVM optimizer. We apply our energy estimation techniques to a comprehensive set of benchmarks, including single- and also multi-threaded embedded programs from two commonly used concurrency patterns, task farms and pipelines. Using SRA, our LLVM IR results demonstrate a high accuracy with a deviation in the range of 1% from the ISA SRA. Our profiling technique captures the actual energy consumption at the LLVM IR level with an average error of 3%.
1 Introduction
The various abstraction layers introduced through the system stack to make programming easier, make it very difficult to understand how coding and data structures affect the energy consumption when the program is executed. Energy transparency aims to leverage this information from the lower levels of the system stack up to the user [1]. Such information can be of significant value for Internet of Things (IoT) applications which typically have to operate on limited or unreliable sources of energy.
Deploying millions of embedded devices into IoT environments poses the challenge of how to power them. Battery-based solutions can be costly and impractical due to the need for replacement. A better solution is a combination of energy harvesting with ultra-low energy embedded devices. Energy harvesting comes with two caveats. Firstly, it is an unreliable source of energy and, secondly, it cannot yet deliver the required energy budgets for many IoT applications. While many achievements have been made in optimizing the energy
consumption of hardware, too little is done to expose potential hardware-level energy savings to the software developer. We propose techniques for exposing the bounds and the actual energy consumption of software written for a specific platform, as part of the embedded systems software development cycle. This enables programmers, tool chains and runtime systems to make energy-aware decisions in order to meet their strict energy constraints.
The energy consumption of a program on specific hardware can always be determined through physical measurements. Although this is potentially the most accurate method, it is often not easily accessible. Measuring energy consumption can involve sophisticated equipment and special hardware knowledge. Custom modifications may be needed to probe the power supply. Even though energy monitoring counters are becoming increasingly popular in modern processors, their number and availability are still limited in deeply embedded systems. Moreover, fine-grained energy characterization of software components, such as Control Flow Graph (CFG) basic blocks or loops, can not be achieved by just using energy measurements. All this makes it very difficult for the majority of software developers to assess a program’s energy consumption.
Energy consumption is a resource constraint, with another frequently examined constraint being execution time. Significant progress has been made in the area of Worst Case Execution Time (WCET) prediction using Static Resource Analysis (SRA) techniques that determine safe upper bounds for the execution time of programs. A popular approach used for WCET is the Implicit Path Enumeration Technique (IPET), which retrieves the worst case control flow path of programs based on a timing cost model. Instead, in [2], an energy model that assigns energy values to blocks of Instruction Set Architecture (ISA) code is used to statically estimate Worst Case Energy Consumption (WCEC). We also adopted IPET in our SRA, retrieving energy bounds for the processor under investigation, the XMOS XS1-L “Xcore”.
The Xcore is a multi-threaded deeply embedded processor with time deterministic instruction execution. Such systems are simpler than general purpose processors and favor predictability and low energy consumption over maximizing performance. Processors with such characteristics are the backbone for IoT applications. Moreover, the absence of performance-enhancing complexity at the hardware level, such as caches, make them ideal for critical applications. We base our choice of the Xcore processor among other more popular architectures used for IoT applications, such as the ARM Cortex-M series [3], on the fact that the Xcore is a time deterministic multi-threaded architecture that can be extended to many-core systems [4], allowing for a variety of design space exploration choices. Our SRA uses an ISA multi-threaded energy model for the Xcore introduced in [5].
In addition, we have developed a novel mapping technique to lift our ISA-level energy model to a higher level, the intermediate representation of the compiler, namely LLVM IR [6], implemented within the LLVM tool chain [7]. This enables SRA to be performed at a higher abstraction level than ISA, thus introducing energy transparency into the compiler tool chain by making energy consump-
tion information accessible directly to the optimizer. Transparency of energy consumption at this level enables programmers to investigate how optimizations affect their program’s energy consumption [8], or even helps introduce new low energy optimizations [9, 10]. This is more applicable at the LLVM IR than at the ISA level, because more program information exists at that level, such as types and loop structures. Our mapping and analysis techniques at the LLVM IR level are applicable to any compiler that uses the LLVM common optimizer, provided that an energy model for the target architecture is available. Our LLVM IR analysis results demonstrate a high accuracy with a deviation in the range of 1% from the ISA SRA.
Because currently, there is no practical method to perform actual case static analysis [11], we introduce a profiling technique that can provide actual energy estimations directly at the LLVM IR level. The profiler is implemented at the LLVM IR level in order to keep the technique as target-agnostic as possible. Moreover, the technique is more favorable than Instruction Set Simulation (ISS) based estimations, as building an ISS for an architecture is a significantly bigger task. Our profiling-based estimation can provide at least the same performance or significantly outperform the estimation speed of an ISS-based estimation, depending on the complexity of the algorithm implemented and the size of the resulting program. This makes it more suitable for iterative optimizations during software development. The profiling-based estimation is evaluated on a large set of benchmarks, showing an only 1.8% deviation compared to a cycle accurate ISS for the Xcore.
The main contributions of this paper are:
1. Formalization and implementation of a novel target-agnostic mapping technique that lifts an ISA-level energy model to a higher level, the intermediate representation of the LLVM compiler (Section 3);
2. SRA energy estimation at the ISA level and at the LLVM IR level using our mapping technique (Section 4.1);
3. A new target-agnostic profiling-based energy estimation technique, that retrieves estimations at the LLVM IR level by the use of our mapping technique, and with an accuracy close to a cycle accurate ISS-based estimation (Section 4.2);
4. SRA and profiling extension for a set of multi-threaded programs (Section 4.3), focusing on task farms and pipelines, two commonly used concurrency patterns;
5. Comprehensive evaluation of our SRA and profiling energy estimation techniques and our mapping technique accuracy on a large set of benchmarks (Section 5).
The rest of the paper is organized as follows. Section 2 gives an overview of the Xcore architecture and its ISA energy model. Section 3 introduces our mapping technique and its instantiation for the Xcore processor. Section 4 details our two estimation methods, SRA and profiling-based. Our experimental evaluation methodology, benchmarks and results are presented and discussed in Section 5.
Section 6 critically reviews previous work related to ours. Finally, Section 7 concludes the paper and outlines opportunities for future work.
2 Xcore Architecture and Energy Model
2.1 Xcore Architecture Overview
The Xcore processor is a deeply embedded processor intended to allow hardware interfaces to be implemented in software. This makes the Xcore well suited to embedded applications requiring multiple hardware interfaces with real-time responsiveness. Interfaces, such as SPI, I2C and USB, can be written efficiently in C-style software, rather than relying on hardware blocks provided in a System-on-Chip or synthesized onto FPGA. To achieve this, the Xcore is designed to be a time deterministic hardware multi-threaded architecture, that provides inter-thread communication and I/O port control directly in the ISA. Moreover, for energy efficiency the processor is event-driven; busy waiting is avoided in favor of hardware-scheduled idle periods.
The processor supports up to 8 threads, with machine instructions and hardware resources dedicated to thread creation, synchronization and destruction. Each thread has its own instruction buffer and register bank. The pipeline of the processor was designed to provide time-deterministic execution and to maximize responsiveness, making the processor ideal for IoT applications. It is integer only, with no floating point hardware. By design the architecture avoids the need for forwarding between pipeline stages, speculative instruction issue and branch prediction and allows for zero time overhead in thread context switching. Threads are executed round-robin through a four-stage pipeline. Each thread can have only one instruction occupy the pipeline at any time, avoiding data hazards. Therefore, if fewer than four threads are active there will be clock cycles with inactive pipeline stages. This means that, to reach the maximum computation power of the processor, four or more threads have to be active to fully occupy the processor’s pipeline. When more than four threads are active, maximum throughput is maintained, but compute time is divided between active threads.
The Xcore is many-core scalable, with 2- or 5-wire “X-Links” and a network switch embedded into each core. Communication between threads on the same or different cores is done via synchronous channel-based message passing. Threads on the same core can communicate without contention, whereas the links used for multi-core communication may be contended. These properties allow design space exploration of multi-threaded programs that are core-local and/or multi-core. A case of the trade-off between processor count and energy efficient execution is investigated in Section 5.1.2. Full details of the architecture are provided in [12].
2.2 Xcore Multi-threaded ISA Energy Model
The underlying energy model for this work is captured at the ISA level. Individual instructions from the ISA are assigned a single cost each. These can then
be used to compute power or energy for sequences of instructions. The modeling technique is built upon [13], which is adapted and extended to consider the scheduling behavior and pipeline characteristics of the Xcore [5]. The model captures the cost of thread scheduling performed by the hardware, in accordance with a series of profiling tests and measurements, because it influences the energy consumption of program execution. The cost associated with an instruction represents the average energy consumption obtained from measuring the energy consumed during instruction execution based on constrained pseudo-randomly generated operands.
A new version of this model that is well suited for static analysis has been developed. It represents energy in terms of static and dynamic power components to better reflect inter-instruction and inter-thread overheads. This has improved model accuracy by an average of four percentage points.
\[ E_{prg} = (P_s + P_{di}) \cdot T_{idle} + \sum_{i \in prg} \left( \frac{P_s + P_i M_{N_p} O}{N_p} \cdot 4 \cdot T_{clk} \right) , \text{ where } N_p = \min(N_t, 4) \]
In Equation (1), \( E_{prg} \) is the energy of a program, formed by adding the energy consumed at idle to the energy consumed by every instruction, \( i \), executed in the program. At idle, only a base processor power, the sum of its static power, \( P_s \), and dynamic idle power, \( P_{di} \), is dissipated for the total idle time, \( T_{idle} \). For each instruction, static power is again considered, with additional dynamic power for each particular instruction, \( P_i \). The dynamic power contribution is then multiplied by a constant inter-instruction overhead, \( O \), that has been established as the average overhead of instruction interleaving. This is then multiplied by a scaling factor to account for the number of threads in the pipeline, \( M_{N_p} \). The result is divided by the number of instructions in the pipeline, which is at most four and is dependent upon the number of active threads, \( N_t \). Each instruction completes in four cycles, so \( 4 \cdot T_{clk} \) gives the energy contribution of the given instruction, based on the calculated power.
When more than four threads are active, the issue rate of instructions per thread will be reduced. The energy model accounts for this with the min term in Equation (1). From a purely timing perspective, the latency between instruction issues for a thread is \( \max(N_t, 4) \cdot T_{clk} \). This property means that instructions are time-deterministic, provided the number of active threads is known. A thread may stall in order to fetch the next instruction. This is also deterministic and can be statically identified [12, pp. 8–10]. These instruction timing rules have been used in simulation-based energy estimation, and are also utilized in both the SRA and profiling performed in this paper.
A limited number of instructions can be exceptions to these timing rules. The divide and remainder instructions are bit-serial and take up to 32 cycles to complete. Resource instructions may block if a condition of their execution is not met, e.g. waiting on inbound communication causes the instruction’s thread to be de-scheduled until the condition becomes satisfied. This paper focuses its
contributions on fully predictable instructions, with timing disturbances from communication forming future work.
2.3 Utilizing the Xcore energy model for energy consumption estimations
To determine the energy consumption of a program based on Equation (1) the program’s instruction sequence, \(i_1, \ldots, i_n\), the idle time \(T_{idle}\), and the number of active threads \(N_p\) during instruction execution must be known. In [5] an ISS was used to gather full trace data or execution statistics to obtain these parameters. In this work we use ISS only as a reference for comparison of SRA and profiling results, with a second reference being direct hardware measurement.
For both SRA and profiling, we need to extract the CFGs for each thread and identify the interleavings between them. This allows for each instruction in the program to identify the \(N_p\) component in Equation (1). It also allows to estimate the total idle time, \(T_{idle}\) of the program. For single-threaded programs the energy characterization of the CFG is straightforward, as there is no thread interleaving. For SRA, the IPET can be directly applied to the energy characterized CFG to extract a path that bounds the energy consumption of the program, as described in Section 4.1. For arbitrary multi-threaded programs, using static analysis to energy characterize the CFG of each thread is challenging. We have therefore concentrated on two commonly used concurrency patterns, task farms and pipelines, which we use with evenly distributed workloads across threads. For these classes of programs the number of active threads across the whole execution is constant and equal to the number of threads used to implement the task farm or the pipeline. Similarly, the profiling technique does not need to account for thread interleavings for the programs investigated in this work.
In addition to instructions defined in the ISA, a Fetch No-Op (FNOP) can also be issued by the processor. These occur deterministically [12, pp. 8–10]. FNOPs can significantly impact on energy consumption, particularly within loops. To account for FNOPs in both our SRA and profiling, the program’s CFG at ISA level is analyzed. An instruction buffer model is used to determine where FNOPs will occur in a basic block (BB). Further details on FNOPs modeling can be found in [14].
3 Mapping ISA Code to LLVM IR and LLVM IR Energy Characterization
Our mapping technique aims to link each LLVM IR instruction of a program with its corresponding machine specific ISA emitted instructions. Such a mapping can give powerful insights to the LLVM IR optimizer regarding code size, execution time and the energy consumption of a program. Furthermore, our LLVM mapping technique does not involve statistical analysis; instead, it is an on-the-fly technique that takes into consideration the compiler behavior and the
actual program’s CFG structure. The technique is fully portable and target agnostic. It requires only the adjustment of the LLVM mapping pass to the new architecture.
In this section we first formalize our generic mapping technique. We then specialize the technique to determine the energy characteristics of LLVM IR instructions. This specialization propagates ISA level energy models up to LLVM IR level, enabling energy consumption estimation of programs at that level. Finally, we instantiate and tune the mapping technique for the architecture under consideration, the Xcore.
3.1 Formal specification of the mapping
The main idea of the mapping technique is to monitor the back-end of a compiler to establish a $1: m$ relation between the optimized LLVM IR and the emitted ISA. The goal of this mapping is to associate a single LLVM IR instruction with all the ISA instructions that originated from it, whenever possible. Then, by aggregating the energy costs of these ISA instructions, we can assign an energy cost to their single corresponding LLVM IR instruction. The mapping technique also guarantees that there is no loss of energy between the two levels as each ISA instruction will be mapped to one LLVM IR instruction. We formalize the mapping as follows. For a program $P$, let
\[ \text{IRprog}_L = \{1, 2, ..., n\} \quad (2) \]
be the ID numbers of $P$’s LLVM IR instructions after the LLVM transformation and optimizations passes, with
\[ \text{IRprog} = \langle ir_1, ir_2, ..., ir_n \rangle \quad (3) \]
being the sequence of LLVM IR instructions for $P$. An architecture-specific compiler back-end $T_{arch}$ translates the IR program into ISA code:
\[ T_{arch}(\text{IRprog}) = \text{ISAprog} = \langle isa_1, isa_2, ..., isa_k \rangle \quad (4) \]
producing a sequence of machine instructions $\langle isa_1, isa_2, ..., isa_k \rangle$ that represents the program $P$ at ISA level. Let
\[ M(\text{IRprog}) = \langle (isa_1, m_1), (isa_2, m_2), ..., (isa_k, m_l) \rangle \quad (5) \]
where $m_1, m_2, ..., m_l \in \text{IRprog}_L$ be the mapping process that monitors $T_{arch}$ and creates a relation between the sequence of ISA instructions for $P$ and the IDs of the LLVM IR instructions, with the aim to associate an ISA instruction with the LLVM IR instruction it originated from, whenever this is possible. For ISA instructions that are not related to any LLVM IR instruction (ISA injected instructions) or whose origin LLVM IR instruction is ambiguous, the mapping process has to make an implementation-specific choice as to which LLVM IR instruction an ISA instruction should be associated with. This will preserve the $1:m$ relation and ensure
that such instructions are accounted at the LLVM IR level. The mapping function
\[
R(\text{ir}_i) = \{ \text{isa}_j | \text{ir}_i \in \text{IRprog} \land \text{isa}_j \in \text{ISAprog} \land (\text{isa}_j, i) \in M(\text{IRprog}) \}
\]
with the property \( \forall \text{ir}_n, \text{ir}_k \in \text{IRprog} \land n \neq k \) then \( R(\text{ir}_n) \cap R(\text{ir}_k) = \emptyset \) (6)
captures a 1 : m relation from IRprog to ISAprog instructions. The energy consumption of an LLVM IR instruction can be retrieved by
\[
E(\text{ir}_i) = \sum_{\text{isa}_j \in S} E(\text{isa}_j) \text{ where } \text{ir}_i \in \text{IRprog} \land \text{isa}_j \in \text{ISAprog} \land S = R(\text{ir}_i)
\]
as the sum of the energy consumed by all ISA instructions mapped to that LLVM IR instruction. Equation (7) can also be used to associate timing or code size information with LLVM IR instructions, by replacing the ISA instructions’ energy costings with the resource of interest costings.
### 3.2 Xcore mapping instantiation and tuning
In our case, the \( T_{arch} \) function is the XMOS tool chain lowering phase that translates the LLVM IR to Xcore-specific ISA. The real challenge is to create from scratch a mechanism that can monitor \( T_{arch} \) and create the mapping given by Equation (5) which will have the property of Equation (6). This would require an extensive knowledge of the back-end of the architecture under consideration and a vast engineering effort to take into account every possible transformation and optimization that happens between the optimized LLVM IR and the final ISA emitted code. Instead, we demonstrate a simple yet powerful technique that can provide sufficiently accurate results. An overview of the technique is given in Figure 1. We now describe the three mapping stages.
#### 3.2.1 Stage 1: LLVM IR annotation
The goal of this stage is to enable the property of Equation (6) that ensures a 1 : m relation between the LLVM IR and ISA code. To achieve this, our mapping implementation leverages the debug mechanism in the XMOS compiler tool chain. Symbols are created during compilation to assist with debugging. These symbols are propagated to all intermediate code layers and down to the ISA code. Debug symbols can express which programming language constructs generated a specific piece of machine code in a given executable module. In our case, these symbols are generated by the front-end of the XMOS compiler in standard DWARF format [15]. These are transformed to LLVM metadata [16] and attached to the LLVM IR. LLVM 2.7 and upwards uses this metadata format as the primary means of storing debug information.
During the lowering phase of compilation, LLVM IR code is transformed to a target ISA by the back-end of the compiler, with debug information stored alongside in the DWARF standard format. Tracking source code debug information
gives an $n:m$ relationship between instructions at the different layers, because several source code instructions can be translated to many LLVM IR instructions, and these again into many ISA instructions. This $n:m$ relation prevents the fine-grained energy mapping needed for accurate energy estimations.
To achieve a $1:m$ mapping between the optimized LLVM IR instructions and the ISA instructions using the debug mechanism, we created an LLVM pass that traverses the optimized LLVM IR and replaces source location information with LLVM IR location information, or adds new location information to LLVM IR instructions without any debug data. This LLVM pass runs after all optimization passes, just before emitting ISA code, because the optimized LLVM IR is closer in structure to the ISA code than the unoptimized version. An example output of this process is given on the left hand side of Figure 2. This represents a part of the LLVM IR CFG of a program after the LLVM optimizations, along with the unique debug location, $IR_{prog}$ in Equation (2), assigned to each LLVM IR instruction.
The XMOS compiler debug mechanism applies the following four rules to preserve the debug information through the different transformations and optimizations applied in the back-end:
1. If an instruction is eliminated, its debug location information is also eliminated.
2. If one instruction is transformed into another one, the debug location of the original instruction is assigned to the new instruction.
3. If multiple instructions are merged into one, the debug location of one of the initial instructions, the first one in our case, is assigned to the new instruction.
4. If one instruction is transformed into multiple ones, then all the new instructions are being assigned the debug location of their origin instruction.
These rules iteratively preserve the $1:m$ relationship between the LLVM IR instructions in $IR_{prog}$ and the final ISA in $ISA_{prog}$, with two exceptions. The first is when instructions are introduced at the ISA level and they do not correspond to any LLVM IR instruction (ISA injected instructions). In such cases the mapping process can assign to them the debug location of an adjacent ISA instruction in the same BB. This ensures that they are accounted for in
the mapped LLVM IR block. The second is when a transformation takes as an input multiple instructions and converts them to another set of multiple instructions in a single step. An example of such transformations are peephole optimizations. In such cases the handling of debug information depends on the compiler implementation. For the back-end under investigation, ISA instructions generated by such transformations are left without any debug information. To account for these instructions at the LLVM IR level, we use the same approach as for ISA injected instructions.
3.2.2 Stage 2: Mapping and LLVM IR Energy Characterization
Once the LLVM IR annotation has been performed for a program, the back-end lowering phase translates the LLVM IR code to target-specific ISA code. Then the mapping phase, which implements Equation (6), runs and maps LLVM IR instructions with the new debug locations to the emitted ISA instructions which carry the same debug location ID. Finally, the energy values for groups of ISA instructions are aggregated and then associated with their single corresponding LLVM IR instruction, as described by Equation (7).

An example mapping is given in Figure 2. On the left-hand side is a part of the LLVM IR CFG of a program, which represents the IRprog in Equation (3), along with the new debug location assigned to each LLVM IR instruction by the mapping pass and represented by Equation (2). The right-hand side shows the corresponding ISA CFG, together with the debug locations for each ISA instruction, given by Equation (5). The coloring of the instructions demonstrates the mapping between the two CFGs’ instructions using Equation (6). Now, one LLVM IR instruction is associated with many ISA instructions, but each ISA instruction is mapped to only one LLVM IR instruction. Some LLVM IR instructions are not mapped, because they are removed during the lowering phase of the compiler. This mapping also guarantees that all ISA instructions are mapped to the LLVM IR, so there is no loss of energy between the two levels.
This Xcore instantiation of the mapping technique, using the debug mechanism, can be ported to any architecture supported by the LLVM IR compiler for which an ISA-level energy model exists. Typically, these are deeply embedded processors, such as the one used here and the ARM Cortex M series, which are ideal for IoT applications.
3.2.3 Stage 3: Tuning and Basic-Block Energy Characterization
Without any further tuning, the mapping instantiation for the Xcore architecture provides an average deviation of 6% between the SRA prediction at the LLVM IR level and that at the ISA level. An additional tuning phase is introduced after the mapping, to account for specific architecture behavior and to facilitate our BB level energy analysis. In the case of the bound analysis, this improved the LLVM IR SRA accuracy, narrowing the gap between ISA and LLVM IR energy predictions to an average of 1% as demonstrated in our results in Section 5.1. This tuning had a similar positive effect on the accuracy of the LLVM IR profiling-based energy estimation.
As discussed in Section 2.3, FNOPs can be issued by the processor and this can be statically determined at the ISA level. This can not be represented in LLVM IR. Ignoring FNOPs can therefore lead to a significant underestimation of energy at the LLVM IR level. To account for FNOPs at the LLVM IR level, we treat them similarly to the ISA injected instructions; by assigning them the debug location of an adjacent ISA instruction in the same BB. Figure 2, provides an example of such FNOP treatment at debug location number 74.
To estimate energy at the LLVM BB level, the energy cost of each BB is needed. This can be obtained by accumulating the energy costs of all LLVM IR instructions in an LLVM IR BB. When estimating energy at the BB level, the position of the LLVM IR instructions in BBs is critical, and tuning may be needed to transfer mapped energy costs to different BBs to reflect more accurately where the energy is consumed during program execution. Phi-nodes, for example, benefit from such tuning.
Phi-nodes can be introduced at the start of a BB as a side effect of the Single Static Assignment (SSA) used for variables in the LLVM IR. A phi-node takes a list of pairs, where each pair contains a reference to the predecessor block together with the variable that is propagated from there to the current block. The number of pairs is equal to the number of predecessor blocks of the current block. A phi-node can create inaccuracies in the mapping when LLVM IR is lowered to ISA code that no longer supports SSA, because it can be hoisted out from its current block to the corresponding predecessor block at the ISA level. For blocks in loops this can lead to a significant estimation error. Such cases can be detected by examining the mapping. Similar inaccuracies can be introduced by branching LLVM IR instructions with multiple targets, if the ISA of the target processor supports only single-target branches.
Algorithm 1 detects cases where the ISA energy values mapped to phi-nodes in a looping BB are accumulated into the wrong LLVM IR BB. It then hoists these costs out to the appropriate LLVM IR predecessor BBs. The algorithm detects
ALGORITHM 1: phi-node tuning
input : IRprog for a program $P$ as described by Equation (3)
input : IRprogCFG, the CFG for IRprog, with the total energy cost for each BB
input : ISAprogCFG, the CFG for the ISAprog given by Equation (4) with BB total energy info
input : $M$, the $1:m$ mapping retrieved for $P$ using the mapping as described in this section
for each $ir_n \in$ IRprog do
if $ir_n$ is a phi-node then
ISAmap ← GetISAmap($ir_n$, $M$) // all the ISA instructions mapped to $ir_n$
irBBloopDepth ← GetInstrBBLoopDepth($ir_n$) // degree of nested loops for $ir_n$’s BB
FromIRBB ← GetCurrentIRBB (IRprogCFG, $ir_n$) // the $ir_n$’s BB
for each $isa_k \in$ ISAmap do
isaBBloopDepth ← GetInstrBBLoopDepth($isa_k$) // degree of nested loops for $isa_k$’s BB
if irBBloopDepth > isaBBloopDepth then
ISABB ← GetISABB (ISAprogCFG, $isa_k$) // the $isa_k$’s BB
ToIRBB ← FindIRBB (IRprogCFG, ISABB) // finds the IR predecessor BB of FromIRBB that matches ISABB by examining the mapping of their instructions
if ToIRBB not NULL then
ISAcost ← GetCost ($isa_k$) // the energy cost of $isa_k$ from our ISA energy model
RemoveCostFromBB (FromIRBB, ISAcost) // remove cost from initial block
AddCostToBB (ToIRBB, ISAcost) // add cost to the chosen predecessor block
end
end
end
end
end
the problematic cases by using the mapping and the BB loop depth. Then, by examining the mapping, function FindIRBB at Line 10 finds the LLVM IR predecessor BB that matches the ISA block holding the ISA phi-node generated instruction. The ISA's instruction energy cost is then added to the cost of the selected predecessor LLVM IR BB and subtracted from the phi-node's LLVM IR BB. Performing the mapping after the LLVM IR optimization passes and just before the lowering phase increases the possibility of similar CFG structures between the two levels. This improves the ability of FindIRBB to find the correct BB and therefore improves the results of the phi-node tuning.
An example of a phi-node adjustment is given in Figure 2 at debug location 72. Its corresponding ISA instruction is hoisted out from the loop BB, ISA BB3, and into ISA BB2. A similar hoisting is performed from LLVM BB2 and into LLVM BB1 by Algorithm 1, thus correctly assigning energy values to each LLVM IR block.
3.3 Limitations
Our mapping approach between the LLVM IR and the ISA guarantees that no energy is lost between the two levels, as all the ISA instruction energy costs are propagated to the LLVM IR level. Therefore, any inaccuracies introduced in our LLVM IR energy estimations from the mapping are a consequence of attributing ISA energy costs to the wrong LLVM IR BBs. This is because our LLVM IR estimation techniques work at a BB level. In that respect, two cases can affect the estimation accuracy.
In the first case, for instructions at the boundaries of LLVM IR BBs, their corresponding ISA instructions may cross these boundaries at the ISA level. The mapping will, however, still associate the energy costs of these ISA instructions with their original LLVM IR instruction, and thus with their original LLVM IR BB. If such LLVM IR instructions belong to a BB that is part of a loop, when the ISA instruction has been hoisted out of that loop, then, with no proper adjustment, an overestimation will occur due to the mapping. An example of such a case are the Phi-node instructions, described in Section 3.2.3, where Algorithm 1 is introduced to adjust their mapping. Such cases can be statically identified by examining the mapping. In the second case, a difference between the two CFG structures can occur when BBs are introduced/eliminated at the ISA level. If this makes the structures of the two CFGs significantly different, then the energy costs allocated to the LLVM IR BBs by the mapping can be inaccurate. Performing the mapping after the LLVM IR optimization passes and just before the lowering phase increases the possibility of having similar CFG structures between the two levels and therefore the accuracy of the mapping. The impact of the above issues is investigated in Section 5.
3.4 Discussion
The mapping technique uses an ISA resource model. This has significant benefits over a stand alone LLVM IR static energy model. Firstly, our mapping-based
approach benefits from the accuracy that ISA models can provide, because the ISA is closer to the hardware than LLVM IR. Secondly, the dynamic nature of the mapping technique can account for specific architecture behavior, such as the LLVM IR location to which the costs of the FNOPs should be attributed, and compiler specific behavior, such as code transformations. Static IR energy models that are created through statistical approaches are inherently limited in their ability to account for these.
Furthermore, since [13], the seminal approach of constructing ISA energy models, there are several well-defined ISA energy models [17, 18, 19, 20, 21]. These models could now be lifted to the compilers’ IR by our mapping. Our approach therefore benefits from a well understood process by which energy models can be created for deeply embedded systems, where predictability is provided at the ISA level.
4 Energy Estimation Methods used
4.1 Static Resource Analysis
Our IPET-based SRA is implemented in three stages detailed as follows:
1. **Low-Level Analysis:** This stage aims to model the dynamic behavior of the processor’s micro-architecture. For our energy consumption analysis, this is achieved through the ISA-level energy model detailed in Section 2.2, that captures the behavior of the Xcore processor with regard to its energy consumption characteristics. For the LLVM IR analysis an extra step is required to characterize the energy consumed by LLVM IR instructions as detailed in Section 3.2.
2. **Control Flow Analysis:** This stage aims to capture the dynamic behavior of the program and associates CFG BBs with the information needed for the computation step of the analysis. IPET requires the CFG and call graph of a program to be constructed at the same level as the analysis. At LLVM IR level, the compiler can generate them. At ISA level a tool was created to construct them. To detect BBs that belong to a loop or recursion, we adopted and extended the algorithm in [22]. The CFGs are annotated according to the needs of the IPET described in [23]. Finally, the annotated CFGs are used in the computation step to produce Integer Linear Programming (ILP) formulations and constraints.
3. **Computation:** The IPET adopted in our work to estimate the energy consumption of a program is based on [23]. To infer the energy consumption of a program, instead of using the time cost of a CFG BB, the BB’s energy cost is used. The minimum required user input to enable bounding of the problem is the loop bounds declaration. This is also standard practice in timing analysis [24]. Further constraints, such as denoting CFG infeasible paths, can be provided in the form of user source code annotations, to extract more accurate estimations. The annotation language used in this work can be found in [25].
4.2 Profiling-Based Energy Consumption Estimation
In contrast to SRA, given a specific set of input parameters, our profiling technique aims to provide the actual energy consumed by a program, rather than bounds. To achieve this, the technique collects LLVM IR BB execution counts. The technique is target-agnostic in the sense that the instrumentation code is inserted at the architecture-independent LLVM IR level and does not require the modification of a program’s object code to insert instrumentation instructions, unlike in other approaches [26]. The energy consumption estimations are also collected at the LLVM IR level. This is enabled by the energy characterization of the LLVM IR code using the mapping technique introduced in Section 3.
Figure 3 outlines the profiling-based energy consumption estimation process. The process is split in two phases: a profiling phase, which aims to collect BB execution traces, and an energy estimation phase that performs the LLVM IR energy characterization and combines it with the profiling information to obtain energy estimations. Both phases take as input the same LLVM IR, the one retrieved after all the optimization passes and just before emitting the target’s ISA code. Using the optimized LLVM IR allows us to benefit from a more accurate energy characterization via the mapping technique, since it is closer in structure to the ISA code than the unoptimized version. This also avoids possible negative impact on the LLVM optimizations’ abilities, resulting from the injected instrumentation code. The stages for each of the two phases are annotated with numbers in black boxes in Figure 3 and are explained next.
**Profiling Phase:**
1. **LLVM Instrumentation Pass:** A new LLVM pass is built into the LLVM compiler that runs after all the LLVM optimization passes and just before the ISA lowering. The pass injects each LLVM IR BB with instrumentation instructions. To implement the BB instrumentation we considered two choices. First, using BB execution counters and second using instructions that emit a unique ID, identifying the BB and its origin function, every time the BB is executed. The second option puts less stress on the limited memory size, typically available on deeply embedded devices, as there is no
need to keep global variables. Therefore, we chose to use the *print* instruction supported in the LLVM IR assembly language. These *print* instructions need to be translated by the compiler back-end to target-specific tracing functions. In the Xcore, *printf* real-time debugging is supported by the xTAG debug adapter [27], which emits the data to the host machine via buffering, with negligible impact on program execution time. The only requirement for other embedded devices to benefit from our profiler is the implementation of a target-specific instrumentation function to emit profiling data to the host machine, if not already in place. On most targets, this can be implemented using I/O ports, with very low impact on the program’s execution time.
2. **Post Processing**: The program is then executed and the BBs execution trace is collected. Based on the unique IDs emitted, the post-processing stage can associate execution counts with each BB of the optimized LLVM IR code.
### Energy Consumption Estimation Phase:
1. **BB Energy Characterization**: A clean copy of the optimized LLVM IR code, with no instrumentation instructions, is energy-characterized using the BB energy characterization mapping techniques introduced in Section 3. This ensures that no energy overheads appear in our energy consumption estimations due to instrumentation code.
2. **Energy Estimation**: This stage takes as input the BB energy-characterized LLVM IR and the BBs execution counts collected from the Profiling phase, and produces the program’s total energy consumption estimation. Having the LLVM IR BBs’ execution counts and the LLVM IR instruction energy costings, a fine-grained software energy characterization can be achieved, where we can attribute energy consumption to specific programming constructs, e.g. BBs, loops and functions.
### 4.3 Analysis of multi-threaded programs
In this paper we present the first steps towards energy consumption analysis of multi-threaded programs. Two concurrency patterns are considered: replicated threads with no inter-thread communication, working on different sets of data (task farms), and pipelines of communicating threads. For both cases we consider evenly distributed, balanced workloads.
There is a fundamental difference when statically predicting the case of interest (worst, best, average case) for time and for energy for multi-threaded programs. Generally, for time only the computations that contribute to the path forming the case of interest must be considered. For energy, all computations taking place during the case of interest must be considered. For instance, in an unbalanced task farm, the WCET will be equivalent to the longest running thread. To bound energy, the energy consumed by each thread needs to be aggregated. Thus, the static analysis needs to determine the number of active threads at each point in time in order to apply the energy model from Equation (1) and characterize the CFG of each thread. Then, IPET can be applied to each thread’s CFG, extracting energy consumption bounds. Aggregating these together will
give a loose upper bound on the program’s energy consumption, meaning that the safety of the bound cannot be guaranteed.
In our balanced task farm examples, all task threads are active in parallel for the duration of the test. Thus, the number of active threads is constant, giving a constant $N_t$, used to determine the pipeline occupancy scaling factor, $M$, in Equation (1). For balanced pipelined programs we consider the continuous, streaming data use case, so the same constant thread count property holds. In both cases, IPET can be performed on each thread’s CFG and the results aggregated to retrieve the total energy consumption. The energy model covers the core-local instructions used for thread communication. Although off-core communication uses the same instructions as core-local communication, an additional energy cost needs to be accounted for external-link usage. This cost was determined empirically for the development board used in Section 5.1.2.
For multi-threaded programs with synchronous communications, to retrieve a WCET, IPET can be applied on a global graph, connecting the CFGs of all threads along communication edges. The communication edges can be treated by the IPET as normal CFG edges and WCET can be extracted by solving the formulated problem [28]. This will return a single worst case path across the global graph. Bounding energy in this way is not possible, as parallel thread activity over time needs to be considered. Activity can be blocked if the threads’ workloads are unbalanced, due to the synchronous blocking message passing. In this case, statically determining the number of active threads at each point in time is hard.
Similar to SRA, profiling-based energy estimation does not need to infer the number of active threads at each execution stage, for our balanced task farms and pipelined test cases. Therefore, retrieving the BB execution counters is sufficient. The concurrency patterns addressed here represent typical embedded use cases. We demonstrate in Section 5.1.2 that for these use cases, SRA can provide sufficiently accurate information for design space exploration. More advanced concurrency analysis techniques, such as the ones employed in [29], could be combined with our techniques to scale our analysis to more complex concurrency patterns.
5 Experimental Evaluation
Two open source benchmark suites were used for evaluation. The first one, Mälardalen WCET benchmark suite [30], is specially designed for WCET analysis. The second, the BEEBS benchmark suite [31], is targeted at evaluating the energy consumption of embedded processors. The selected benchmarks were modified to work with our test harness and, in some cases, to make them more parametric to function input arguments. When necessary, benchmarks using floating point were modified to use integer values, since the Xcore does not support floating point operations. Some of the benchmarks were also extended to be multi-threaded task farms, where the same code runs on two or four threads.
Furthermore, a range of industrial benchmarks was selected to demonstrate the value of our estimation techniques to embedded developers.
Deeply embedded processors do not typically have hardware support for division or floating point operations, using software libraries instead. Software implementations are usually far less efficient than their hardware equivalent, both in terms of execution time and energy consumption. The effect of these software implementations on energy consumption should be known by developers, therefore we include software division and software-emulated floating point arithmetic benchmarks. A radix-4 software divider, Radix4Div [32], is used. A less efficient version, B.Radix4Div, is added for comparison; it omits an early return when the dividend is greater than 255. As a consequence, CFG paths become more balanced, with less variation between the possible execution paths. The effect of this on the energy consumption is discussed later in this section. For software floating point, single precision SFloatAdd32bit and SFloatSub32bit operations from [33] are analyzed.
To extend our analysis to multi-threaded communicating programs, we analyze two common signal processing tasks written for the Xcore, FIR and Biquad [34]. Both tasks are implemented as pipelines of seven threads. Such programs are the preferred form for Xcore, as spreading the computation across threads allows the voltage and frequency of the core to be lowered, significantly reducing energy consumption while retaining the same performance as the single threaded version.
A complete list of all the benchmarks’ attributes, can be found in [35]. Benchmarks were compiled with xcc version 12 [36] at optimization level O2; the default for most compilers. For hardware measurements, as in [5], a shunt resistor current sense and sampling circuit obtains power dissipation with sub-milliwatt precision and variation of less than 1%.
5.1 Static Resource Analysis Results
For the evaluation of our SRA estimations together with the mapping technique, 20 benchmarks were used. These cover a broad spectrum of language features and code complexity. A combination of good understanding of the underlying algorithms, profiling information and brute forcing of the benchmarks’ functions input space was necessary to identify tests covering the algorithmic worst case execution path for each benchmark with certainty.
Figure 4 presents the error margin of using the same ISA energy model with three energy estimation techniques compared to hardware energy measurements for our benchmarks. Simulation produces energy estimations based on instruction traces from ISS, ISA SRA uses the model for static analysis at the ISA level and LLVM IR SRA uses our mapping technique to apply the model and analysis at LLVM IR level.
In the case of LLVM IR SRA, the accuracy of the prediction is heavily dependent on the accuracy of the mapping techniques presented in Section 3. As shown in Figure 4, for all benchmarks the LLVM IR SRA results are within one percentage point error of ISA SRA results, except for the Base64 and levenshtein
benchmark with a further 4.3 and 2.0 percentage points error, respectively. In these cases the CFGs of the two levels were significantly different due to new BBs introduced from branches in the ISA level CFG. As discussed in Section 3.3, substantial differences between the two CFGs can reduce the effectiveness of our current tuning implementation.
Generally, for all results, a proportion of error is present in both forms of static analysis as well as simulation-based energy estimation. The error in the ISS-based estimation is a baseline for the best achievable accuracy in static analysis, as the ISS produces the most accurate execution statistics. For all the benchmarks, the ISA SRA results are over-approximating the trace-based energy estimations. This applies also to the LLVM IR SRA results with exception of the st benchmark. This over-approximation is a product of the bound analysis used, which is trying to select the most energy-costly CFG path based on the provided cost model.
The majority of SRA energy estimations are tightly overestimating the actual energy consumption measured on the hardware, up to 5.7% for ISA SRA and up to 7.4% for LLVM IR SRA. There are a number of cases for which the retrieved estimations underestimate the actual energy consumption (mac, levenshtein, st, p.fir_7t, p.biquad_7t). IPET is intended to provide bounds based on a given cost model. In our case it tries to select the worst case execution paths in terms of the energy consumption. However, energy consumption is data sensitive, i.e. the energy cost of executing an instruction varies, depending on (the circuit switching activity caused by) the operands used. Therefore, the observed underestimation is a consequence of using a data-insensitive energy model and analysis.
The SRA estimations seen in Figure 4 represent a loose upper bound on the benchmarks’ energy consumption. These bounds cannot be considered safe for use in mission critical applications. However, our experimental results show a low level of SRA underestimation, less than 4%, and therefore our SRA can still provide valuable guidance to the application programmer, e.g. to compare coding styles or algorithms.
Beyond the use of SRA predictions for bounding the energy consumption, a number of other use cases were investigated and are detailed next.
### 5.1.1 SRA alternative use cases
The modified B.Radix4Div benchmark avoids an early return when the dividend is greater than 255. Omitting this optimization is less efficient, but balances the CFG paths. The effect of this modification can be seen in Figure 5. The ISA level energy consumption lower and upper bounds (the best and worst case retrieved by IPET) are shown. In the optimized version, Radix4Div, the energy consumption across different test cases varies significantly, creating a large range between the upper and lower energy consumption bounds. Conversely, the un-optimized version, B.Radix4Div, shows a lower variation, thus narrowing the margin between the upper and lower bounds, but has a higher average energy consumption.
Fig. 5: The energy consumption bounds of the optimized and unoptimized version of Radix4Div benchmarks, captured by SRA.
Knowledge of such energy consumption behavior can be of value for applications like cryptography, where the power profile of systems can be monitored to reveal sensitive information in side channel attacks [37]. In these situations, SRA can help developers to design code with low energy consumption variation, so that information that could be leaked through power monitoring can be obfuscated.
### 5.1.2 Design Space Exploration using SRA
In this section we examine how ISA SRA can be used as an alternative to measurements or simulation for design space exploration of task farms and pipelined programs. We consider applications for which the worst-case execution path is actually the dominant execution path. Having a number of available threads, a number of cores and the ability to apply voltage and frequency scaling, provides a wide range of configuration options in the design phase, with multiple optimization targets. This can include optimizing for quality of service, time and energy,
or a combination of all three. For this experiment we used the XMOS XP-SKC-A16 [38] development board, which consists of two interconnected Xcores, with 16 threads available in total and supports voltage and frequency scaling.
The left-hand side of Figure 6 shows different configurations for the same program; on the right-hand side these different versions are compared in regards of savings, if any, achieved for time and energy. For energy, both the hardware measurement-based, and the SRA-predicted percentages of savings are shown in order to assess the ability of SRA to support sound energy-aware decisions. Our analysis can infer also the time figures but due to the time-deterministic nature of the architecture the predictions closely match the actual values and therefore we omit them from the graph.
First, SRA was applied to replicated non-communicating threads. The user can make energy-aware decisions on the number of threads to use, with respect to time and energy estimations retrieved by our analysis. As an example, consider four independent matrix multiplications on four pairs of equally sized matrices ($30 \times 30$). For all three versions we keep the number of cores, the core voltage and frequency constant, but we alter the number of threads and split the computation across them. The single thread version, $M_1$, has an execution time of $4 \times$ the time needed to execute one matrix multiplication. However, the two-thread version, $M_2$, halves the execution time and, as indicated by both SRA and actual measurements, decreases the energy by 21%, compared to $M_1$. The four-thread version, $M_3$, halves the execution time again and, as predicted by SRA, the energy consumption is decreased by 40% compared to the two-thread version, $M_2$. For the same case, $M_3$ vs $M_2$, the actual energy savings are 44%. Although there is a different estimation error between different numbers of active threads, the error range of 5% is small enough to allow comparisons between these different versions, by just using the energy estimations from SRA. The measured and the predicted values are strongly correlated and confirm that using more threads increases the power dissipation, but the reduction in execution time saves energy on the platform under investigation.
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>ID</th>
<th>Configuration</th>
<th>C</th>
<th>T</th>
<th>V</th>
<th>F</th>
</tr>
</thead>
<tbody>
<tr>
<td>MatMult (4 pairs of $30\times30$ matrices)</td>
<td>M1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>450</td>
<td></td>
</tr>
<tr>
<td></td>
<td>M2</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>490</td>
<td></td>
</tr>
<tr>
<td></td>
<td>M3</td>
<td>1</td>
<td>4</td>
<td>1</td>
<td>499</td>
<td></td>
</tr>
<tr>
<td>Biquad Filter</td>
<td>B1</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>450</td>
<td></td>
</tr>
<tr>
<td></td>
<td>B2</td>
<td>1</td>
<td>7</td>
<td>0.75</td>
<td>150</td>
<td></td>
</tr>
<tr>
<td></td>
<td>B3</td>
<td>2</td>
<td>7</td>
<td>0.7</td>
<td>75</td>
<td></td>
</tr>
</tbody>
</table>
C: Number of cores used
T: Number of threads used
V: Core(s) Voltage in Volts
F: Core(s) Frequency in MHz
Fig. 6: Design Space Exploration enabled by SRA.
Next, SRA was applied to streaming pipelines of communicating threads. There is a choice in how to spread the computation across threads to maximize throughput to either minimize execution time or lower the necessary device operating frequency and voltage while maintaining performance. Our SRA can take advantage of the fact that the energy model used is parametric to voltage and frequency, to statically identify the most energy-efficient configuration of the same program, among a number of options that deliver the same throughput. We demonstrate this on the Biquad benchmark.
The Biquad benchmark implements an equalizer; it takes a signal and attenuates or amplifies different frequency bands. The Biquad equaliser uses a cascade of biquad filters. Each biquad filter attenuates or amplifies one specific frequency range; the signal is sequentially passed through all filters, eventually attenuating or amplifying all bands. In a standard equalizer setting, a seven-bank filter is used, of which the low four banks are set to amplify, and the top three banks are set to attenuate. These seven banks are implemented in a seven-stage pipeline.
Figure 6, on the left-hand side shows the three different versions explored for the Biquad filter. B1 is the sequential version running at 450 MHz and 1V. The single-core parallel version, B2, uses 7 threads, one for each bank, and runs at 150 MHz and 0.75V. The multi-core parallel version, again using 7 threads, places 4 threads on the first core and 3 on the second core. It therefore allows for halving the core frequency to 75 MHz and a further reduction of the core voltage to 0.7V. All versions, B1, B2 and B3 deliver the same filter performance, therefore the percentage of time savings on the right hand side graph of Figure 6 is zero. In contrast, we can see a predicted energy saving on B2 vs B1 of 54% and on B3 vs B2 of 3%. The actual energy savings are 52% and 2%, respectively. The small error of our energy consumption estimations enables energy-aware decisions just by the use of SRA. In this case, version B2 is the best solution since, while maintaining the same performance, it halves the energy consumption. In comparison, the small additional energy savings realized by B3 may not warrant the use of a second core. These energy-aware decisions can not be achieved by only examining the execution time of each one of the three configurations. Similar results were achieved for the Fir benchmark.
In both of the above examples, we demonstrated that our SRA is sufficient to provide design space exploration guidance considering both time and energy, without the need of any simulation or hardware measurements. This has significant benefits since SRA is faster than simulation and less costly to deploy than hardware measurements.
5.2 Profiling-Based Analysis Results
To evaluate the profiling-based energy estimation technique together with the mapping technique, 30 benchmarks were used. For these benchmarks, Figure 7 presents the error margin of using the same ISA energy model with the ISS-based estimations and the profiling-based estimations, compared to hardware energy measurements, respectively. The average absolute error obtained for the profiling-based estimations is 3.1%, and 2.7% for the ISS-based estimations.
The ISS-based estimation is more reliable than profiling. This is because cycle-accurate ISS allows for a very precise energy consumption estimation for each particular program execution as the program is executed in simulation with a specific set of input parameters. The exact sequence of instructions can be recorded during simulation and then used to estimate energy consumption. In contrast, profiling is less precise as it operates further away from the hardware, at the LLVM IR level. Profiling estimation precision heavily depends on the quality of the mapping techniques introduced in Section 3.2, and on the quality of the profiling techniques used to collect execution counts of LLVM IR BBs, as described in Section 4.2. However, our profiling results demonstrate a high accuracy with an average error deviation of 1.8% from the ISS.
Fig. 7: Profiling- and ISS-based energy estimations against hardware measurements.
5.2.1 Profiling-Based Estimation Performance
ISS execution is often several orders of magnitude slower than hardware. The performance of an ISS is governed by the complexity of the program’s underlying algorithms. In contrast, the performance of our profiling is mainly governed by the program size, since retrieving the BB execution counts incurs a negligible execution time overhead when running on the actual platform, as discussed in Section 4.2. The bigger the program the more time will be needed for Stage 1, LLVM Instrumentation Pass in the Profiling phase and Stage 1, BB Energy Characterization, in the Energy Consumption Estimation phase, shown in Figure 3.
In the case of benchmarks with low algorithmic complexity and function inputs that will trigger a very short simulation time, no significant performance gains will be observed from using profiling over ISS estimation. For example, for our SFloatAdd benchmark, with a $O(1)$ complexity, the average profiling estimation performance observed has a negligible gain over the ISS estimation. On the other hand, increasing the complexity of the benchmarks’ underlying algorithms and using parameters which trigger longer simulation time, results in the profiler significantly outperforming the simulation. For example, when using $30 \times 30$
size matrices for our matrix multiplication benchmark, the profiling estimation achieves a 381 times speedup over the ISS estimation. The benchmark’s small size allowed for a fast profiling estimation, but the ISS estimation performance follows the $O(n^3)$ algorithmic complexity of the benchmark.
A further speedup can be achieved for the profiling-based method, when testing the same program with different inputs. If the optimized LLVM IR code obtained is the same across the different inputs, then there is no need to repeat the LLVM IR energy characterization stage. In such cases using the profiling energy estimation has clear performance advantages compared to the ISS-based energy estimation.
5.3 Discussion
Our SRA-based estimation at the LLVM IR level has a deviation in the range of 1% from the ISA SRA, and our profiling-based estimation has an average error deviation of 1.8% from the ISS. This shows that the tuning phase introduced in Section 3.2.3, mitigates the impact of the mapping limitations described in Section 3.3, and yields sufficiently accurate results for the architecture and compiler under consideration. Depending on the architecture and the compiler implementation, the tuning phase heuristics can be further improved to achieve the required level of accuracy.
6 Related Work
SRA is a methodology to determine usage bounds of a resource (usually time or energy or both) for a specific task when executed on a piece of hardware, without actually executing the task. This requires accurate modeling of the hardware in order to capture the dynamic functional and non-functional properties of task execution. Determining these properties accurately is known to be undecidable in general. Therefore, to extract safe values for the resource usage of a task, a sound approximation is needed [24, 39].
SRA has been mainly driven by the timing analysis community. Static cost analysis techniques based on setting up and solving recurrence equations date back to Wegbreit’s [40] seminal paper, and have been developed significantly in subsequent work [41, 42, 43, 44, 45]. Other classes of approaches to cost analysis use dependent types [46], SMT solvers [47], or size change abstraction [48]. Generally, for performing an accurate WCET static analysis, there are four essential components [24]:
1. Value analysis: mainly used to analyze the behavior of the data cache.
2. Control flow analysis: used to identify the dynamic behavior of a program.
3. Low-level analysis: attempts to retrieve timing costs for each atomic unit on a given hardware platform, such as an instruction or a BB in a CFG for a processor.
4. Calculation: uses the results from the two previous components to estimate the WCET. The most common techniques used for calculation of the WCET are the IPET, the path-based techniques and the tree-based methods [49].
Three of the above components, namely the control flow analysis, low-level analysis and calculation, are adopted in our work, as discussed in Section 4.1.
IPET is one of the most popular methods used for WCET analysis [50, 51, 52, 49, 28]. In this approach, the CFG of a program is expressed as an ILP system, where the objective function represents the program’s execution time. The problem then becomes a search for the WCET by maximizing the retrieved objective function under some constraints on the execution counts of the CFG’s BBs.
Although significant research has been conducted in static analysis for the execution time estimation of a program, there is little on energy consumption. One of the few approaches [53] seeks to statically infer the energy consumption of Java programs as functions of input data sizes, by specializing a generic resource analyzer [44, 54] to Java bytecode analysis [55]. However, a comparison of the results to actual measurements was not performed. Later, in [56], the same generic resource analyzer was instantiated to perform energy analysis of XC programs [57] at the ISA level based on ISA-level energy models and including a comparison to actual hardware measurements. However, the scope of this particular analysis approach was limited to a small set of simple benchmarks because information required for the analysis of more complex programs, such as program structure and types, is not available at the ISA level. The SRA presented in this paper does not rely on such information. A similar approach, using cost functions, was used in [58]. The analysis was performed at the LLVM IR level, using an early version of the mapping technique that we formalize and describe in full detail for the first time in this paper. Although the range of programs that could be analyzed was improved, compared to [56], the complexity of solving recurrence equations for analyzing larger programs proved a limiting factor.
In [2] the WCEC for a program was inferred by using the IPET first introduced in [50]. Although the authors manage to bound the WCEC on a simulated processor by maximizing the switching activity factor for each simulated component, they acknowledge the need to validate their estimation results against commercial embedded processors. Similarly, in [59] the authors attempt to perform static WCEC analysis for a simple embedded processor, the ARM Cortex M0+. This analysis is also based on IPET combined with a so-called absolute energy model, an energy model that is said to provide the “maximum energy consumption of each instruction”. The authors argue that they can retrieve a safe bound. However, this is demonstrated on a single benchmark, bubblesort, only. They also acknowledge that using an absolute energy model can lead to significant overestimation, making the bounds less useful. We choose to use a pseudo-random data characterized energy model, as empirical evidence shows that such models tend to be close to the actual worst case [60].
All of the reviewed previous works combined SRA techniques together with energy models to capture the WCEC path. Currently, there is no practical method to perform average case static analysis [11]. One of the most recent works towards average case SRA [61] demonstrates that compositionality combined with the capacity for tracking data distributions unlocks the average case analysis, but novel language features and hardware designs are required to support these properties. This situation motivated us to develop a dynamic profiling technique that captures the actual energy consumption of a program based on its input parameters.
There are two main requirements for CPU energy profiling. First, a technique is needed to instrument a program’s execution and collect data that represent the program’s dynamic behavior. Code instrumentation, simulation and hardware performance counters are some of the most popular techniques used to collect such data. The second requirement is a method of associating energy information with the various entities, events in the set of the collected instrumentation data. This is typically done either through an energy model, or by power-monitoring the program’s execution.
Energy modeling and profiling can be performed at various levels of abstraction. In [62], a gate-level power consumption model was created and combined with event-driven logic simulation to estimate the power consumption of programs. Modeling and profiling at such low design levels is not practical for most commercial embedded processors since their lower level circuit information is not available. Moreover, this estimation is quite slow and not practical for fine-grained energy characterization of software.
In [13] an ISA-level energy model was proposed which treated the hardware as a black-box and obtained energy consumption data through hardware measurements of large loops of individual instructions. Modeling at the ISA allowed for attributing energy costs to low-level software components such as ISA BBs. This led to further research that combined ISA energy models with instruction set simulators and profilers to extract energy estimations [17, 18, 19, 20, 21]. Our energy model is also based on [13], but significantly extended to a multi-threaded version for the Xcore, which takes into account both inter-instruction and inter-thread effects.
For more complex processors or for system-level energy consumption estimation, energy modeling and profiling at the ISA level is impractical. In such cases, performance counter-based statistical energy modeling and estimation is preferable. In several works [63, 64, 65], the authors used performance counters to characterize the processor energy consumption based on the conditions affecting these counters, such as cache misses and prefetches. Then, by combining this energy characterization with performance counters execution statistics, they predict the energy consumption of an application. An alternative to performance counters is the use of an external multi-meter to directly measure a system’s energy profile [66].
In [67], energy characterization of LLVM IR code is performed by linear regression analysis. This is combined with instrumentation and execution on a
target host machine to estimate the performance and energy requirements in embedded software. Transferring the LLVM IR energy model to a new platform requires performing the regression analysis again. The mapping technique we present here does not involve any regression analysis and it is fully portable. It requires only the adjustment of the LLVM mapping pass to the new architecture. Furthermore, our LLVM IR mapping technique provides an on-the-fly energy characterization that takes into consideration the compiler behavior including optimization and transformation passes and other architecture-specific aspects. The instrumentation technique of [67] is also based on collecting execution BB counts, but this is done by executing programs on a host machine rather than the actual platform. However, compiling and executing on a higher-end PC, rather than the target deeply embedded device, could yield an execution profile significantly different from the one that would be obtained on the target machine. Our profiling technique collects execution counts on the target machine, and maps them back to their corresponding LLVM IR BB.
In [68], a scheme is proposed that enables the compiler to exploit both task and data parallelism and automatically map an application to an embedded multi-processor containing voltage islands. The scheme is based on the workload of each processor, using both hardware parallelism and voltage scaling to reduce energy consumption without increasing the overall execution time. Per-core frequency and voltage configurations can be provided to appropriately design Xcore-based systems. Using our profiling technique and our LLVM IR energy characterization, accurate workload estimations can be achieved at the LLVM IR level. These could be utilized by the optimization scheme introduced in [68] to enable the LLVM compiler to achieve similar energy consumption savings.
Profiling has previously been used successfully to enable energy-aware compilation. A combination of code analysis and profiling techniques can enable the compiler to build power-aware flow graphs [69]. Such a graph has its basic blocks annotated with the hardware resource requirements and the execution counts. The power-aware flow graphs can then be used to identify code regions where several of the processor’s functional units can be turned off during execution to reduce the static power dissipation. [70] demonstrate a framework that enables the compiler to support a number of energy-related optimizations for parallel design patterns. A series of pragmas were introduced to identify specific parallel design patterns and guide the compiler to apply power optimizations. These optimizations were enabled by utilizing power profiling and code instrumentation feedback provided by a simulator.
Our profiler provides energy consumption information directly into the compiler’s optimizer. Therefore it can enable feedback-directed compilation that targets energy-specific optimizations and design space exploration for deeply embedded systems.
7 Conclusion and Future Work
This work focuses on providing energy consumption estimation techniques that can enable energy transparency in the software stack of deeply embedded processors, typically used in IoT applications. A novel target-agnostic mapping technique is introduced to allow energy characterization of the LLVM tool chain intermediate representation, namely the LLVM IR. This is a significant step beyond existing ISA-level energy estimation techniques. Our mapping technique can give powerful insights to the LLVM IR optimizer regarding execution time and the energy consumption of a program. This enables programmers to investigate how optimizations can affect their program’s energy consumption, or even help introduce new energy-specific optimizations in future.
For energy consumption bounds an IPET-based SRA was developed. The analysis was introduced at both ISA and LLVM IR levels. The results demonstrated that the mapping technique enables SRA at the LLVM IR level with a small accuracy loss in the range of only 1%, compared to SRA at ISA level. SRA-based energy estimation was also applied to a set of multi-threaded programs for the first time to our knowledge. This is a significant step beyond existing work that examines single-thread programs. As shown in Section 5.1.2, such an analysis can provide significant guidance for time-energy design space exploration between different numbers of threads and cores.
To estimate the actual energy consumption of a program under specific input parameters, a target-agnostic profiling technique was developed. The technique is enabled by the LLVM IR energy characterization utilizing our mapping. It is designed to ensure that the instrumentation code required for profiling does not lead to energy overheads. Experimental evaluation shows an average absolute error of 3.2% compared to hardware measurements. Our profiling technique is more flexible and significantly more efficient than ISS-based estimation. It can attribute energy consumption to software components, such as BBs and functions, in contrast to hardware measurements. The high accuracy and performance of our profiler can enable feedback-directed optimization for energy consumption. LLVM IR energy consumption estimations of each compilation can be taken into consideration iteratively in subsequent compilations. Each new compilation will be able to make more energy-aware decisions.
The techniques introduced in this paper are focused on deeply embedded architectures that favor predictability over performance. Such architectures are the backbone of IoT applications. Enabling energy-aware software development for such architectures will help to tackle the energy challenge that IoT faces. We acknowledge that some of our techniques, mainly SRA-based estimation, work best with predictable architectures. This is also true for WCET analysis. In fact, static analysis is inherently limited in that sense. Thus, in future work we intend to examine the portability of our profiling-based techniques to more complex processors.
Future work aims to analyze more complex concurrent programs, such as distinct non-communicating threads, or pipelines of threads with unbalanced workloads. We anticipate that our LLVM IR profiling technique will scale better
to these cases than SRA. As the core-count of the analyzed system grows, more in-depth exploration of energy saving techniques such as per-core DVFS could be considered both at the model level and SRA or profiling levels.
Acknowledgments
The research leading to these results has received funding from the European Union Seventh Framework Programme (FP7/2007-2013) under grant agreement no. 318337, ENTRA: Whole-Systems Energy Transparency, and from the ARTEMIS Joint Undertaking under grant agreement no. 621429 (project EMC2).
References
|
{"Source-Url": "https://research-information.bristol.ac.uk/files/114575630/Kyriakos_Georgiou_Energy_Transparency_for_Deeply_Embedded_Programs.pdf", "len_cl100k_base": 15941, "olmocr-version": "0.1.50", "pdf-total-pages": 34, "total-fallback-pages": 0, "total-input-tokens": 82266, "total-output-tokens": 21882, "length": "2e13", "weborganizer": {"__label__adult": 0.0006146430969238281, "__label__art_design": 0.0007128715515136719, "__label__crime_law": 0.0005044937133789062, "__label__education_jobs": 0.0007481575012207031, "__label__entertainment": 0.00013768672943115234, "__label__fashion_beauty": 0.0002982616424560547, "__label__finance_business": 0.00048422813415527344, "__label__food_dining": 0.0005693435668945312, "__label__games": 0.0018758773803710935, "__label__hardware": 0.01497650146484375, "__label__health": 0.0009050369262695312, "__label__history": 0.0006985664367675781, "__label__home_hobbies": 0.00023615360260009768, "__label__industrial": 0.0015001296997070312, "__label__literature": 0.0003399848937988281, "__label__politics": 0.0005950927734375, "__label__religion": 0.0009093284606933594, "__label__science_tech": 0.2734375, "__label__social_life": 7.283687591552734e-05, "__label__software": 0.0079345703125, "__label__software_dev": 0.68994140625, "__label__sports_fitness": 0.0005626678466796875, "__label__transportation": 0.0017604827880859375, "__label__travel": 0.0003840923309326172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 92395, 0.0303]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 92395, 0.54421]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 92395, 0.88165]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2672, false], [2672, 6009, null], [6009, 9014, null], [9014, 11995, null], [11995, 15288, null], [15288, 18164, null], [18164, 20848, null], [20848, 23737, null], [23737, 26035, null], [26035, 28162, null], [28162, 31380, null], [31380, 32767, null], [32767, 35734, null], [35734, 38560, null], [38560, 40842, null], [40842, 43945, null], [43945, 46977, null], [46977, 50108, null], [50108, 52303, null], [52303, 54314, null], [54314, 57197, null], [57197, 60499, null], [60499, 62739, null], [62739, 65384, null], [65384, 68616, null], [68616, 71872, null], [71872, 74932, null], [74932, 78233, null], [78233, 81211, null], [81211, 84709, null], [84709, 88058, null], [88058, 91536, null], [91536, 92395, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2672, true], [2672, 6009, null], [6009, 9014, null], [9014, 11995, null], [11995, 15288, null], [15288, 18164, null], [18164, 20848, null], [20848, 23737, null], [23737, 26035, null], [26035, 28162, null], [28162, 31380, null], [31380, 32767, null], [32767, 35734, null], [35734, 38560, null], [38560, 40842, null], [40842, 43945, null], [43945, 46977, null], [46977, 50108, null], [50108, 52303, null], [52303, 54314, null], [54314, 57197, null], [57197, 60499, null], [60499, 62739, null], [62739, 65384, null], [65384, 68616, null], [68616, 71872, null], [71872, 74932, null], [74932, 78233, null], [78233, 81211, null], [81211, 84709, null], [84709, 88058, null], [88058, 91536, null], [91536, 92395, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 92395, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 92395, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2672, 2], [2672, 6009, 3], [6009, 9014, 4], [9014, 11995, 5], [11995, 15288, 6], [15288, 18164, 7], [18164, 20848, 8], [20848, 23737, 9], [23737, 26035, 10], [26035, 28162, 11], [28162, 31380, 12], [31380, 32767, 13], [32767, 35734, 14], [35734, 38560, 15], [38560, 40842, 16], [40842, 43945, 17], [43945, 46977, 18], [46977, 50108, 19], [50108, 52303, 20], [52303, 54314, 21], [54314, 57197, 22], [57197, 60499, 23], [60499, 62739, 24], [62739, 65384, 25], [65384, 68616, 26], [68616, 71872, 27], [71872, 74932, 28], [74932, 78233, 29], [78233, 81211, 30], [81211, 84709, 31], [84709, 88058, 32], [88058, 91536, 33], [91536, 92395, 34]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 92395, 0.02676]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
0315a0331b45b2c9d1a1fc5c7d123853ba76948e
|
[REMOVED]
|
{"Source-Url": "https://inria.hal.science/hal-01109766/file/misirBusinessManagement2014.pdf", "len_cl100k_base": 8267, "olmocr-version": "0.1.49", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 40779, "total-output-tokens": 9987, "length": "2e13", "weborganizer": {"__label__adult": 0.0003380775451660156, "__label__art_design": 0.0006494522094726562, "__label__crime_law": 0.0005340576171875, "__label__education_jobs": 0.003749847412109375, "__label__entertainment": 0.0001691579818725586, "__label__fashion_beauty": 0.00024509429931640625, "__label__finance_business": 0.001739501953125, "__label__food_dining": 0.00048422813415527344, "__label__games": 0.0010099411010742188, "__label__hardware": 0.001064300537109375, "__label__health": 0.0007300376892089844, "__label__history": 0.0005235671997070312, "__label__home_hobbies": 0.00017952919006347656, "__label__industrial": 0.0009684562683105468, "__label__literature": 0.0006461143493652344, "__label__politics": 0.00033020973205566406, "__label__religion": 0.00044918060302734375, "__label__science_tech": 0.430419921875, "__label__social_life": 0.0001852512359619141, "__label__software": 0.039337158203125, "__label__software_dev": 0.51513671875, "__label__sports_fitness": 0.0002970695495605469, "__label__transportation": 0.0006194114685058594, "__label__travel": 0.00021064281463623047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44786, 0.02448]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44786, 0.42802]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44786, 0.89989]], "google_gemma-3-12b-it_contains_pii": [[0, 974, false], [974, 3667, null], [3667, 5406, null], [5406, 8285, null], [8285, 11431, null], [11431, 13587, null], [13587, 15234, null], [15234, 18052, null], [18052, 20924, null], [20924, 24213, null], [24213, 28095, null], [28095, 31118, null], [31118, 33117, null], [33117, 34910, null], [34910, 38219, null], [38219, 41122, null], [41122, 44786, null]], "google_gemma-3-12b-it_is_public_document": [[0, 974, true], [974, 3667, null], [3667, 5406, null], [5406, 8285, null], [8285, 11431, null], [11431, 13587, null], [13587, 15234, null], [15234, 18052, null], [18052, 20924, null], [20924, 24213, null], [24213, 28095, null], [28095, 31118, null], [31118, 33117, null], [33117, 34910, null], [34910, 38219, null], [38219, 41122, null], [41122, 44786, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44786, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44786, null]], "pdf_page_numbers": [[0, 974, 1], [974, 3667, 2], [3667, 5406, 3], [5406, 8285, 4], [8285, 11431, 5], [11431, 13587, 6], [13587, 15234, 7], [15234, 18052, 8], [18052, 20924, 9], [20924, 24213, 10], [24213, 28095, 11], [28095, 31118, 12], [31118, 33117, 13], [33117, 34910, 14], [34910, 38219, 15], [38219, 41122, 16], [41122, 44786, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44786, 0.21023]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
8b90f6af80d073442728b4d9178f973ea563409c
|
Simplified Electronic Notation for Sensor Reporting (SENSR) 1.0(beta)
Version 1.0(beta)
OMG Document Number: dtc/2020-07-02 (this document)
USE OF SPECIFICATION - TERMS, CONDITIONS & NOTICES
The material in this document details an Object Management Group specification in accordance with the terms, conditions and notices set forth below. This document does not represent a commitment to implement any portion of this specification in any company’s products. The information contained in this document is subject to change without notice.
LICENSES
The companies listed above have granted to the Object Management Group, Inc. (OMG) a nonexclusive, royalty-free, paid up, worldwide license to copy and distribute this document and to modify this document and distribute copies of the modified version. Each of the copyright holders listed above has agreed that no person shall be deemed to have infringed the copyright in the included material of any such copyright holder by reason of having used the specification set forth herein or having conformed any computer software to the specification. Subject to all of the terms and conditions below, the owners of the copyright in this specification hereby grant you a fully-paid up, non-exclusive, nontransferable, perpetual, worldwide license (without the right to sublicense), to use this specification to create and distribute software and special purpose specifications that are based upon this specification, and to use, copy, and distribute this specification as provided under the Copyright Act; provided that: (1) both the copyright notice identified above and this permission notice appear on any copies of this specification; (2) the use of the specifications is for informational purposes and will not be copied or posted on any network computer or broadcast in any media and will not be otherwise resold or transferred for commercial purposes; and (3) no modifications are made to this specification. This limited permission automatically terminates without notice if you breach any of these terms or conditions. Upon termination, you will destroy immediately any copies of the specifications in your possession or control.
PATENTS
The attention of adopters is directed to the possibility that compliance with or adoption of OMG specifications may require use of an invention covered by patent rights. OMG shall not be responsible for identifying patents for which a license may be required by any OMG specification, or for conducting legal inquiries into the legal validity or scope of those patents that are brought to its attention. OMG specifications are prospective and advisory only. Prospective users are responsible for protecting themselves against liability for infringement of patents.
GENERAL USE RESTRICTIONS
Any unauthorized use of this specification may violate copyright laws, trademark laws, and communications regulations and statutes. This document contains information which is protected by copyright. All Rights Reserved. No part of this work covered by copyright herein may be reproduced or used in any form or by any means—graphic, electronic, or mechanical, including photocopying, recording, taping, or information storage and retrieval systems—without permission of the copyright owner.
DISCLAIMER OF WARRANTY
WHILE THIS PUBLICATION IS BELIEVED TO BE ACCURATE, IT IS PROVIDED "AS IS" AND MAY CON- TAIN ERRORS OR MISPRINTS. THE OBJECT MANAGEMENT GROUP AND THE COMPANIES LISTED ABOVE MAKE NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO THIS PUB- LICATION, INCLUDING BUT NOT LIMITED TO ANY WARRANTY OF TITLE OR OWNERSHIP, IMPLIED WARRANTY OF MERCHANTABILITY OR WARRANTY OF FITNESS FOR A PARTICULAR PURPOSE OR USE. IN NO EVENT SHALL THE OBJECT MANAGEMENT GROUP OR ANY OF THE COMPANIES LISTED ABOVE BE LIABLE FOR ERRORS CONTAINED HEREIN OR FOR DIRECT, INDIRECT, INCIDENTAL, SPECIAL, CONSEQUENTIAL, RELIANCE OR COVER DAMAGES, INCLUDING LOSS OF PROFITS, REVENUE, DATA OR USE, INCURRED BY ANY USER OR ANY THIRD PARTY IN CONNECTION WITH THE FURNISH- ING, PERFORMANCE, OR USE OF THIS MATERIAL, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. The entire risk as to the quality and performance of software developed using this specification is borne by you. This disclaimer of warranty constitutes an essential part of the license granted to you to use this specification.
RESTRICTED RIGHTS LEGEND
Use, duplication or disclosure by the U.S. Government is subject to the restrictions set forth in subparagraph (c) (1) (ii) of The Rights in Technical Data and Computer Software Clause at DFARS 252.227-7013 or in subparagraph (c)(1) and (2) of the Commercial Computer Software - Restricted Rights clauses at 48 C.F.R. 52.227-19 or as specified in 48 C.F.R. 227-7202-2 of the DoD F.A.R. Supplement and its successors, or as specified in 48 C.F.R. 12.212 of the Federal Acquisition Regulations and its successors, as applicable. The specification copyright owners are as indicated above and may be contacted through the Object Management Group, 109 Highland Avenue, Needham, MA 02494, U.S.A.
TRADEMARKS
IMM®, MDA®, Model Driven Architecture®, UML®, UML Cube logo®, OMG Logo®, CORBA® and XMI® are registered trademarks of the Object Management Group, Inc., and Object Management Group™, OMG™, Unified Modeling Language™, Model Driven Architecture Logo™, Model Driven Architecture Diagram™, CORBA logos™, XMI Logo™, CWM™, CWM Logo™, IIOP™, MOF™, OMG Interface Definition Language (IDL)™, and OMG SysML™ are trademarks of the Object Management Group. All other products or company names mentioned are used for identification purposes only, and may be trademarks of their respective owners.
COMPLIANCE
The copyright holders listed above acknowledge that the Object Management Group (acting itself or through its de- signees) is and shall at all times be the sole entity that may authorize developers, suppliers and sellers of computer software to use certification marks, trademarks or other special designations to indicate compliance with these materi- als. Software developed under the terms of this license may claim compliance or conformance with this specification if and only if the software compliance is of a nature fully matching the applicable compliance points as stated in the specification. Software developed only partially matching the applicable compliance points may claim only that the software was based on this specification, but may not claim compliance or conformance with this specification. In the event that testing suites are implemented or approved by Object Management Group, Inc., software developed using this specification may claim compliance or conformance with the specification only if the software satisfactorily completes the testing suites.
OMG’s Issue Reporting Procedure
All OMG specifications are subject to continuous review and improvement. As part of this process we encourage readers to report any ambiguities, inconsistencies, or inaccuracies they may find by completing the Issue Reporting Form listed on the main web page, under Documents, Report a Bug/Issue (https://www.omg.org/report_issue.)
## Contents
Preface ........................................... v
1 Scope ........................................ 1
2 Conformance ................................... 5
2.1 Basic Conformance ............................. 5
2.2 Extended Conformance ......................... 5
3 References .................................... 6
3.1 Normative References .......................... 6
4 Terms and Definitions .......................... 7
5 Symbols ......................................... 8
6 Additional Information .......................... 9
6.1 How to read this Specification ................ 9
6.2 Acknowledgments ................................ 9
7 Core Packages .................................. 10
7.1 Base .......................................... 10
7.1.1 Container ................................ 10
7.1.2 DataElement (Abstract) .................... 11
7.1.3 DataSheet ................................ 11
7.1.4 Quantity .................................. 12
7.1.5 Stream .................................... 12
7.1.6 Union ...................................... 12
7.2 Syntax ........................................ 13
7.2.1 Constant .................................. 13
7.2.2 FixedSize ................................ 14
7.2.3 SyntaxBase (Abstract) ...................... 14
7.2.4 VariableSize ............................... 14
7.3 Semantics .................................... 14
7.3.1 Audio ...................................... 14
7.3.2 Bitfield ................................... 15
7.3.3 Char ....................................... 15
<table>
<thead>
<tr>
<th>Section</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>7.3.4 Enumeration</td>
<td>15</td>
</tr>
<tr>
<td>7.3.5 EnumValue</td>
<td>16</td>
</tr>
<tr>
<td>7.3.6 FixedPoint</td>
<td>16</td>
</tr>
<tr>
<td>7.3.7 FloatingPoint</td>
<td>16</td>
</tr>
<tr>
<td>7.3.8 Ignore</td>
<td>16</td>
</tr>
<tr>
<td>7.3.9 Image</td>
<td>17</td>
</tr>
<tr>
<td>7.3.10 Integer</td>
<td>17</td>
</tr>
<tr>
<td>7.3.11 Numeric</td>
<td>17</td>
</tr>
<tr>
<td>7.3.12 SemanticBase (Abstract)</td>
<td>17</td>
</tr>
<tr>
<td>7.3.13 String</td>
<td>17</td>
</tr>
<tr>
<td>7.3.14 Text</td>
<td>18</td>
</tr>
<tr>
<td>7.3.15 Video</td>
<td>18</td>
</tr>
<tr>
<td>7.4 Units</td>
<td>18</td>
</tr>
<tr>
<td>7.4.1 Exponent</td>
<td>18</td>
</tr>
<tr>
<td>7.4.2 Multiply</td>
<td>19</td>
</tr>
<tr>
<td>7.4.3 Scaled</td>
<td>19</td>
</tr>
<tr>
<td>7.4.4 Simple (Abstract)</td>
<td>20</td>
</tr>
<tr>
<td>7.4.5 Unit (Abstract)</td>
<td>20</td>
</tr>
<tr>
<td>7.5 FoundationalUnits</td>
<td>20</td>
</tr>
<tr>
<td>7.5.1 Amount</td>
<td>20</td>
</tr>
<tr>
<td>7.5.2 Current</td>
<td>21</td>
</tr>
<tr>
<td>7.5.3 Length</td>
<td>21</td>
</tr>
<tr>
<td>7.5.4 Light</td>
<td>21</td>
</tr>
<tr>
<td>7.5.5 Mass</td>
<td>21</td>
</tr>
<tr>
<td>7.5.6 Temperature</td>
<td>21</td>
</tr>
<tr>
<td>7.5.7 Time</td>
<td>21</td>
</tr>
<tr>
<td>8 UnitsLibrary (informative)</td>
<td>22</td>
</tr>
<tr>
<td>8.1 CompoundUnits</td>
<td>22</td>
</tr>
<tr>
<td>8.2 SIUnits</td>
<td>23</td>
</tr>
<tr>
<td>8.3 CompoundSIUnits</td>
<td>23</td>
</tr>
<tr>
<td>8.4 USCustomary</td>
<td>23</td>
</tr>
<tr>
<td>9 Examples (informative)</td>
<td>26</td>
</tr>
<tr>
<td>9.1 Example 1</td>
<td>26</td>
</tr>
<tr>
<td>9.2 Example 2</td>
<td>27</td>
</tr>
<tr>
<td>9.3 Example 3</td>
<td>29</td>
</tr>
<tr>
<td>10 Simplified Electronic Notation for Sensor Reporting (SENSR) 1.0(beta)</td>
<td>iv</td>
</tr>
</tbody>
</table>
Preface
About the Object Management Group
Founded in 1989, the Object Management Group, Inc. (OMG) is an open membership, not-for-profit computer industry standards consortium that produces and maintains computer industry specifications for interoperable, portable, and reusable enterprise applications in distributed, heterogeneous environments. Membership includes Information Technology vendors, end users, government agencies, and academia. OMG member companies write, adopt, and maintain its specifications following a mature, open process. OMG’s specifications implement the Model Driven Architecture® (MDA®), maximizing ROI through a full-lifecycle approach to enterprise integration that covers multiple operating systems, programming languages, middleware and networking infrastructures, and software development environments. OMG’s specifications include: UML® (Unified Modeling Language™); CORBA® (Common Object Request Broker Architecture); CWM™ (Common Warehouse Metamodel); and industry-specific standards for dozens of vertical markets. More information on the OMG is available at https://www.omg.org/.
OMG Specifications
As noted, OMG specifications address middleware, modeling and vertical domain frameworks. All OMG Specifications are available from the OMG website at: https://www.omg.org/spec
All of OMG’s formal specifications may be downloaded without charge from our website. (Products implementing OMG specifications are available from individual suppliers.) Copies of specifications, available in PostScript and PDF format, may be obtained from the Specifications Catalog cited above or by contacting the Object Management Group, Inc. at:
OMG Headquarters
109 Highland Avenue
Suite 300
Needham, MA 02494
USA
Tel: +1-781-444-0404
Fax: +1-781-444-0320
Email: pubs@omg.org
Certain OMG specifications are also available as ISO standards. Please consult http://www.iso.org
Typographical Conventions
The type styles shown below are used in this document to distinguish programming statements from ordinary English. However, these conventions are not used in tables or section headings where no distinction is necessary.
Times/Times New Roman - 10 pt Standard body text
Helvetica/Arial - 10 pt Bold OMG Interface Definition Language (OMG IDL) and syntax elements
Courier - 10 pt Bold Programming language elements
Helvetica/Arial - 10 pt Exceptions
NOTE: Terms that appear in italics are defined in the glossary. Italic text also represents the name of a document, specification, or other publication.
Issues
The reader is encouraged to report any technical or editing issues/problems with this specification to: https://www.omg.org/report_issue.htm.
1 Scope
Currently, manufacturers of hardware sensors producing data rely on arcane data sheets to describe the format of data supplied by their sensors. Each manufacturer has defined their own data sheet format, and each consumer of the data needs to interpret the data sheet for implementation in their own system. Errors and ambiguities can, and are likely to, occur in these situations.
In response to the experiences of the members of the Industrial Internet Consortium (IIC) [4], particularly those involved with the implementation of the IIC Testbeds initiative, this submission describes a metamodel for describing the form of serialized data streams emitted by sensors, and describing how that data should be interpreted by a client to derive the intended meaning of the data. The intent is that a manufacturer’s sensor products can be characterized by a model expressed in the proposed metamodel. This submission does not concern itself with the transport, networking, or wire protocol for transmitting the data from the sensor to the client.
This submission specifies a metamodel appropriate for modeling the syntax of the data streamed, as well as a mechanism for authoring a guideline for interpretation of that data. The model of a sensor’s data will then be provided by the manufacturer as a document called an Electronic Data Sheet (EDS). The EDS will be a machine consumable document such that it can be generated by the manufacturer and parsed by the consumer. The method for delivering an EDS document is outside the scope of this submission.
The EDS is analogous to the current hardware data sheets offered by manufacturers, but improves on the current state of the art by being highly structured, appropriate for machine consumption, and in a standardized form. An illustration of how the EDS may be used is as follows:
- Equipment is required to offer sensor data to one or more unknown consumers.
- A consumer wishing to receive the data will access the EDS for the sensor product. The delivery of the EDS may occur at any time prior to configuration of the consumer.
- Guided by the EDS, the consumer is adapted to parse the data provided by the sensor. This configuration may occur at any time prior to communication with the sensor.
- The consumers and the hardware will communicate over a pre-determined protocol, such as Bluetooth, mDNS + TCP/IP, or other to be determined channels.
- The consumer begins to receive data from the sending hardware, and can interpret the data in the way that is intended.
The intent is that manufacturers can use the metamodel to specify an EDS to provide a precise model of the data their equipment is producing, and consumers can faithfully refer to a common standard to understand the EDS, and information needed to interpret the data stream. This knowledge can be used to pre-configure a sensor client prior to deployment. There is also the possibility of creating a dynamic configuration engine that parses EDS documents and produces appropriate parsers and interpreters of data streams at run time. This allows manufacturers to provide a precise description of the output of their hardware, confident that future consumers of the data produced by that hardware can properly interpret the data stream.
An example of a bit stream that should be able to be defined is shown in Listing 1.1 at the end of this section. This listing was provided by Bosch as an example of an existing data stream descriptor for an existing sensor, and appears in Section 6.8.1 under Evaluation Criteria of the SENSR RFP[SENSR RFP].
The scope of the SENSR specification includes:
- Provide a metamodel that enables the unambiguous definitions of data types
- Describe an appropriate format to express EDS documents, where the EDS is a representation of a use of the metamodel
• Provide a mechanism to ensure unique identifiers for each encoding organization offering EDS documents.
The SENS R specification is not intended to:
• Define a new communication mechanism
• Restrict the kinds of hardware sensors that can provide data
• Restrict the kinds of consumers that can interpret data
[FileInfo]
FileName=Temperature_Sensor_EDS.eds
FileVersion=1
FileRevision=0
Description=Temperature Sensor
CreationTime=08:00AM
CreationDate=21-08-2018
CreatedBy=A. Cordes, BOSCH
ModificationTime=08:00AM
ModificationDate=21-08-2018
ModifiedBy=A. Cordes, BOSCH
[DeviceInfo]
ManufacturerID=0x02A6
[Payload_Value_1]
Length=16
Offset=0x00
Scale=1
Name=Sensor ID
Info=0x3815
Unit=n
[Payload_Value_2]
Length=8
Offset=0x00
Scale=1
Name=Counter
Unit=n
[Payload_Value_3]
Length=8
Offset=0x00
Scale=1
Name=Unused
Unit=n
[Payload_Value_4]
Length=2
Offset=0x00
Scale=1
Name=Telegram Version
Unit=n
[Payload_Value_5]
Length=1
Offset=0x00
Scale=1
Name=Unused
Info=Value is constant 0
Unit=n
[Payload_Value_6]
Length=1
Offset=0x00
Scale=1
Name=Payload Encryption
Unit=n
[Payload_Value_7]
Length=1
Offset=0x00
Scale=1
Name=Battery Status
Unit=n
[Payload_Value_8]
Length=16
Offset=0
Scale=1
Name=Temperature
format=signend8.8
Unit=C
[Payload_Value_9]
Length=8
Offset=0
Scale=1
Name=Temperature_max1h
format=signed8
Unit=C
[Payload_Value_10]
Length=8
Offset=0
Scale=1
Name=Temperature_min1h
format=signed8
Unit=C
[Payload_Value_11]
Length=8
Offset=0
Scale=1
Name=Temperature_max24h
format=signed8
Unit=C
[Payload_Value_12]
Listing 1.1: Example Bitstream
2 Conformance
2.1 Basic Conformance
All conformant products must comply with these conformance points:
- **Implement the Base package.** The Base package defines each abstract base class for the Syntax, Semantics, and Unit class families, the DataElement class, and the DataSheet class. It provides the initial set of relationships.
- **Implement the Syntax package.** The Syntax package defines the bit layout in a data stream.
- **Implement the Semantics package.** The Semantics package defines the basic data kinds that consumers can expect to encounter.
- **Implement the Units package.** The Units package defines a comprehensive way to describe physical units in a measurement-system-independent manner, and then impose a measurement-system on the dimensioned descriptors.
2.2 Extended Conformance
Products compliant with Extended Conformance must comply with all points of Basic Conformance, and in addition provide a suitably useful data types library that offers either US Customary or Metric compliant units, a suite of syntax and semantic types to handle the most common types such as a Boolean (single bit) type, and both 8 and 16 bit integer types.
3 References
3.1 Normative References
The following normative documents contain provisions which, through reference in this text, constitute provisions of this specification. For dated references, subsequent amendments to, or revisions of, any of these publications do not apply.
4 Terms and Definitions
For the purposes of this specification, the following terms and definitions apply.
Complete MOF (CMOF)
The CMOF, or Complete MOF, Model is the model used to specify other metamodels such as UML2.
Electronic Data Sheet (EDS)
An Electronic Data Sheet is an electronically transmitted document that describes a component, generally a hardware component in electrical engineering. That component can be as low level as a single analog device (resistor, diode, capacitor), or a complex device such as an environmental sensor. The data sheet describes how to integrate that device into a larger system.
Essential MOF (EMOF)
Essential MOF is the subset of MOF that most closely corresponds to the facilities found in object-oriented programming languages and in XML. It provides a straightforward framework for mapping MOF models to implementations such as JMI and XMI for simple metamodels. A primary goal of EMOF is to allow simple metamodels to be defined using simple concepts while supporting extensions (by the usual class extension mechanism in MOF) for more sophisticated metamodeling using CMOF.
Industrial Internet Consortium (IIC)
"The Industrial Internet Consortium was founded in March 2014 to bring together the organizations and technologies necessary to accelerate the growth of the industrial internet by identifying, assembling, testing and promoting best practices. Members work collaboratively to speed the commercial use of advanced technologies. Membership includes small and large technology innovators, vertical market leaders, researchers, universities and government organizations." [https://www.iiconsortium.org/](https://www.iiconsortium.org/)
Metamodel
A metamodel is a model that acts as the schema for a family of models.
Meta-Object Facility (MOF)
The Meta Object Facility (MOF), an OMG specification, provides a metadata management framework, and a set of metadata services to enable the development and interoperability of model and metadata-driven systems. Examples of systems that use MOF include modeling and development tools, data warehouse systems, metadata repositories etc.
Model
A model is a formal specification of the function, structure and/or behavior of an application or system.
XML Metadata Interchange (XMI)
XMI is a widely used interchange format for sharing objects using XML. XMI is a comprehensive solution that build on sharing data with XML. XMI is applicable to a wide variety of objects: analysis (UML), software (Java, C++), components (EJB, IDL, CORBA Component Model), and databases (CWM).
5Symbols
The following symbols and/or abbreviations are used throughout this specification.
None.
6 Additional Information
(informative)
6.1 How to read this Specification
This specification presents a metamodel for describing Electronic Data Sheets suitable for use by manufacturers of devices that sense and report on observed phenomena. Clauses 1 to 6 provide compliance rules, terms definitions and reference information. Clause 7 provides the description of the metamodel for SENSR. Clause 8 provides an informative example of how to use SENSR to build a library of Units. Clause 9 provides informative examples of how to define EDSs in SENSR, with equivalent XML representations. Clause 10 provides an informative example of a PSM for a Bluetooth LE implementation.
All clauses of this document are normative unless explicitly marked “(informative)”. The marking “(informative)” of a particular clause applies also to all contained sub-clauses of that clause.
6.2 Acknowledgments
- Axel Cordes and team members of Bosch Software Innovations reviewed this submission
- Peter Denno, NIST, provided review and feedback
- Jason McC. Smith, Elemental Reasoning, prepared the final submission
7 Core Packages
7.1 Base
SENSR’s Base package defines the fundamental concepts of SENSR. The DataSheet is composed of DataElements, and DataElements have three parts to their definition: Syntax, Semantics, and optionally Units.
Users of this metamodel are expected to create their own types from one of the four provided subtypes of DataElement, depending on the representation in the sensor’s data.

7.1.1 Container
A Container wraps an ordered collection of DataElements into a single entity. This is useful in cases where, for example, a triplet of Distance measurements comprise a CartesianCoordinate, or it is necessary to break down a Numeric type into the individual components such as Sign, Exponent, and Mantissa.
**Generalizations**
DataElement
Associations (Required)
elements : DataElement [1..*] {ordered}
The elements attribute points to an ordered list of DataElement instances, such that the container acts as a wrapper providing a syntactic ordering of subelements. The subelements can be any DataElement subtype, another Container, a Quantity, a Union, or even a Stream. In the last case, the semantics are such that when the Stream’s data is ended, however that is achieved, the next element in the Container’s sequence is expected.
7.1.2 DataElement (Abstract)
A DataElement models a unit of data of the DataSheet’s streamElements, such that a consumer of the DataSheet can understand that portion of the data stream. A DataElement contains physical layout (Syntax), a descriptor of the kind of expected data (Semantics), and an optional Units that explains how to interpret the data as an observation of a physical phenomenon.
Attributes (Required)
name : String
The name for the DataElement, this is vendor defined
Associations (Required)
description : SemanticBase [1]
The instance pointed to by the description association is of type SemanticBase. This class family provides a DataElement with a way of describing the kind of data it will define, thus guiding interpretation.
7.1.3 DataSheet
DataSheet is the top level modeling element in SENSR. It is the electronic equivalent of a traditional manufacturer’s data sheet for electronic devices. It provides guidance for implementors on how to interpret a data stream, and is composed of DataElement instances.
Attributes (Required)
author : String
Initial author of the Data Sheet.
creationDateTime : String
Date and timestamp of the initial creation of this DataSheet. Format is ISO 8601 compliant, and assumes UTC timezone: YYYYMMDDThhmmZ.
modificationDateTime : String
Date and timestamp of the last modification of this DataSheet. Format is ISO 8601 compliant, and assumes UTC timezone: YYYYMMDDThhmmZ.
modifyingAuthor : String
Author who last modified this DataSheet.
name : String
The name of the DataSheet, provided by the vendor. Each vendor is likely to have their own naming convention, such as the make of the sensor whose output stream is being modeled.
vendorID : String
The identifier for a specific vendor. This vendorID is unique to a vendor, and requires registration with a central organization.
version : String
Version is defined in x.y.z format, where x is major version, y is revision, and z is patch, and each is a monotonically increasing integer starting at 0, and reset when the number to the left is incremented.
Associations (Required)
streamElements : DataElement [1..*] {ordered}
An ordered sequence of DataElements that make up the bit stream.
7.1.4 Quantity
A Quantity is a ‘simple’ value, such as a number, a string, a flag, or a bitmask. It has a fixed data size (in bits), a known semantics, and optionally a units signifier.
**Generalizations**
- **DataElement**
**Attributes (Optional)**
- **base : Integer [0..1]**
The numeric base of the number being represented. Defaults to 10 unless otherwise specified.
- **relativeZeroPoint : String [0..1]**
If a value for relativeZeroPoint is provided, it is to be interpreted as establishing this Quantity as representing a relative measure. For instance, assume a home thermostat is reporting temperature in degrees Celsius as a fixed point number using a relatively small number of bits. Since it is unlikely the thermostat will need to report values below 15C, or above 35C, it sets a relative zero point of 25, and is able to use its bit space to more precisely measure the +/- 10C it is most concerned with. This value is provided as a String, to allow it to be independent of the syntax, description, and units associations.
**Associations (Required)**
- **syntax : SyntaxBase [1]**
An association to an instance of SyntaxBase, this defines the layout of the bits for this Quantity.
**Associations (Optional)**
- **units : Unit [0..1]**
An optional association, units provide dimensionality to a measure.
7.1.5 Stream
A Stream has no particular end to its data. Unlike a Quantity, which has a specific bit layout, or a Container, which has a specific ordered list of DataElements, or a Union, which has a fixed size with alternate semantics, a Stream has no predefined length.
**Generalizations**
- **DataElement**
**Attributes (Required)**
- **eos : String**
End of Stream signifier. For simple value streams, a String value should suffice. For more complex streams, such as video or audio, it may be better to use the reference attribute to point to an external specification, and leave this attribute blank.
7.1.6 Union
A Union, named after a similar data structure in the C programming language family, offers alternative semantics for the same syntax field. Two or more DataElements are pointed to with the understanding that only one DataElement can occupy the relevant bits in the data stream. As such, the DataElements in the collection of choices usually have the same syntactic length. However, if the Union points to a VariableSize instance for its Syntax, then at least one of the DataElements pointed to by the Union will have a unique Syntax element. Often, which semantics are used to interpret the bit field is based on a conditional expression or value of a flag in the stream.
**Generalizations**
DataElement
Associations (Required)
choices : DataElement [2..*]
Two or more choices to be selected from. Each choice must have the same Syntax length.
7.2 Syntax
The Syntax package lets authors of DataSheets define the 'physical' layout of bits at the most basic level. This version of the specification provides the FixedSize class, a provision that satisfies most needs. By providing an abstract base class, however, we leave open the opportunity for future possibilities.
![Syntax Package Class Diagram]
Figure 7.2: Syntax Package Class Diagram
7.2.1 Constant
A Constant data element has not only a fixed size, but a fixed value. The value String attribute gives the value in the expected format indicated by the Semantics that accompany the data element.
Generalizations
FixedSize
Attributes (Required)
value : String
The value of the Constant held by the data element.
7.2.2 FixedSize
The FixedSize class is expected to be the most commonly used Syntax class. It is used to define the number of bits that a Quantity DataElement will take up in the datastream.
**Generalizations**
SyntaxBase
**Attributes (Required)**
- **bits** : int
A simple count of the bits used for a Quantity.
7.2.3 SyntaxBase (Abstract)
SyntaxBase provides a common interface for describing the physical layout of bits within a bitstream.
**Attributes (Required)**
- **name** : String
The name of the Syntax being defined.
7.2.4 VariableSize
A VariableSize Syntax informs the DataElement that the number of bits used by it may change due to other considerations. This is useful with a Union DataElement subtype.
**Generalizations**
SyntaxBase
**Attributes (Required)**
- **max** : int
Maximum number of bits that will be occupied by this Syntax element.
- **min** : int
Smallest number of bits that will be occupied by this Syntax element.
7.3 Semantics
The Semantic package defines an extensible system for describing the kind of data being expressed by a DataElement. The included descriptors range from the usual text and numeric data, to more complicated audio-visual data kinds. The Semantic classes do not describe the physical layout of the data (which is handled by the Syntax package), or how to interpret the data with respect to the physical world (which is handled by the Units package). The reference attribute in the DataElement class is used to point to an authoritative external source for guidance, where applicable. It is not embedded here, because the external source will necessarily depend on the syntax layout and, potentially, the physical units.
7.3.1 Audio
Describes an audio stream.
**Generalizations**
SemanticBase
7.3.2 Bitfield
A Bitfield describes a fixed length vector of single bits. This is commonly used to collect boolean flags into a common space. (Note that the field can be a single bit long, in which case it is just a flag.)
Generalizations
SemanticBase
7.3.3 Char
Describes a single character. Encoding is handled by an appropriate reference.
Generalizations
Text
7.3.4 Enumeration
Describes an enumeration, a fixed set of values that are the only valid values for the DataElement.
Generalizations
Bitfield
Associations (Required)
values : EnumValue [1..*]
A set of EnumValue objects that describe the allowed values for this Enumeration.
7.3.5 EnumValue
A single value for an Enumeration kind. It has a name to refer to it by, and a value. The value is an Integer, interpreted from the Bitfield that it specializes as big-endian base 2 values. Note that this is not to specify that the data must be big-endian or base 2, but that for the purposes of mapping the bits to the enumerated value, there will be a specific bit pattern that is to be interpreted in that matter.
Attributes (Required)
mapValue : Integer
The Integer value that corresponds to the bit pattern of the Enumeration to map to this EnumValue. The bit pattern in the base Bitfield will be interpreted as big-endian base 2 to form this value.
name : String
The name of this particular enumeration value.
value : String
The value of the EnumValue. This is represented as a String, which is to be interpreted as the type specified by the type attribute.
Associations (Required)
type : SemanticBase [1]
Guidance on how to interpret the value attribute. If, for example, this points to a String instance, then the String value of the value attribute is to be taken literally. If this attribute points to an Integer instance, then "1" would be the integer 1, "20" would be interpreted as the integer 20, and so on.
7.3.6 FixedPoint
A fixed point number, having a scale value that converts the integer to a fixed decimal position.
Generalizations
Numeric
Attributes (Required)
scale : int
The scaling factor by which to divide the integer.
7.3.7 FloatingPoint
A floating point number. Floating point representation can be quite complicated. Typically, FloatingPoint objects will be used in a DataElement that points to an established reference such as IEEE 754.
Generalizations
Numeric
7.3.8 Ignore
Some sections of a bit stream are unused, and are to be ignored. Use this Semantic kind to indicate that a consumer should simply skip these bits.
Generalizations
SemanticBase
7.3.9 Image
Describes an image. Except for simple bitmaps, this is likely going to be pointing to an established specification using DataElement::reference.
Generalizations
SemanticBase
7.3.10 Integer
An integer. Equivalent to a fixed point number with a scaling factor of 1.
Generalizations
FixedPoint
Constraints
scale : [scale = 1]
An integer is a fixed point with a scaling factor of 1.
7.3.11 Numeric
Any single-dimensional numeric value.
Generalizations
SemanticBase
Attributes (Required)
base : int
Base of the numeric type.
isSigned : boolean
Flag to indicate if the numeric type is signed. Default is true.
7.3.12 SemanticBase (Abstract)
SemanticBase is the base abstract class for all semantic classes. It supplies only a name attribute for the kind to be described.
Attributes (Required)
name : String
The name of the semantic kind being described.
reference : String
URI to find reference material on the DataElement. Examples could be a link to the IEEE 745 floating point specification, UTF-8 for strings, etc.
7.3.13 String
A string, a collection of characters. Encoding is handled by an appropriate reference.
Generalizations
Text
7.3.14 Text
Any kind of textual data.
Generalizations
SemanticBase
7.3.15 Video
A video stream. Almost certainly this will use DataElement::reference to point to an established specification.
Generalizations
SemanticBase
7.4 Units
Units provide a dimensionality to a number. They give a rigorous interpretation guide for measurements of physical phenomena, as well as provide a concrete representation space such as SI, US Customary, or Imperial measurements.
Users of SENSR are given four options for defining a Unit:
- Simple, an abstract base class for units that have a single dimensionality such as SI units or Imperial units
- Scaled, which scales another Unit by a fixed amount, such as 1000 grams in a kilogram, or 12 inches in a foot
- Multiply which combines dissimilar Units into a complex dimensioned Unit
- Exponent, which provides a compact way of expressing higher dimensionality of a single Unit.
Complex units such as those for measuring velocity, density, and force, can be built using the above mechanisms. Conversions from one unit system to another can be accomplished by judicious use of the Scaled class.
7.4.1 Exponent
The Exponent class raises a Unit to a given power. The power is floating point, to accommodate fractal cases, and is signed to provide a mechanism for division.
Generalizations
Unit
Attributes (Required)
- power : float
The exponent to raise the Unit to. It is a signed number, so it can be used naturally for division via a negative exponent. It is a floating point to handle fractal dimensionalities.
Associations (Required)
- base : Unit [1]
The base attribute points to a defined Unit which is to be raised to a given exponential power. Any base Unit can be used, but the most common will be subtypes of Simple.
7.4.2 Multiply
The Multiply class uses $\text{op1}$ as the first multiplicand, and $\text{op2}$ as the second.
**Generalizations**
- Unit
**Associations (Required)**
- $\text{op1} : \text{Unit}[1]$
- The first Unit to be referenced.
- $\text{op2} : \text{Unit}[1]$
- The second Unit to be referenced.
7.4.3 Scaled
The Scaled class takes a base Unit and provides a scaling factor, the magnitude, to create a new unit that is a scale conversion of the same dimensionality. An example would be a gram as 0.001 of a kilogram.
**Generalizations**
- Unit
**Attributes (Required)**
- magnitude : float
- Value to scale Base unit by to create this Scaled unit.
**Associations (Required)**
- $\text{base} : \text{Unit}[1]$
- The Base unit kind that this Scaled unit is built off of.
7.4.4 Simple (Abstract)
Simple is the core class for most Units that will ultimately be created using SENSJR. It is abstract, and has seven normative subclasses, defined in Clause 7.5.
Generalizations
Unit
7.4.5 Unit (Abstract)
Unit is the base class for an entire family of descriptors for the units that physical observations are to be measured in.
Attributes (Required)
- name : String
Name of the Unit
7.5 FoundationalUnits
The FoundationalUnits package provides a core set of Units that can be composed into highly complex multi-dimensioned Units. The seven foundational units were chosen to correspond to the seven basic units of the SI system. From these, any physical phenomena should be describable. These Units are 'pure' in the sense that they do not have a specific measure, and do not map to a specific measuring system. They are therefore suitable to be mapped to any system, such as SI (or metric), Imperial, or US Customary.
```
package FoundationalUnits {
FoundationalUnits
}
```
Figure 7.5: Simple Units Class Diagram
7.5.1 Amount
Amount describes a quantity. This can be the quantity of a substance, such as a chemical, or the number of birds in a flock, or how many dozen eggs are in stock. If none of the other six FoundationalUnits correspond to what you are measuring, use Amount as your starting point.
Generalizations
Simple
7.5.2 Current
Current describes the rate of net flow of electric charge past a specific spatial point.
Generalizations
Simple
7.5.3 Length
Length describes a unit of physical linear measure.
Generalizations
Simple
7.5.4 Light
Light defines a unit for luminous intensity.
Generalizations
Simple
7.5.5 Mass
Mass is a descriptor for a unit of the physical property which is a measure of its resistance to acceleration.
Generalizations
Simple
7.5.6 Temperature
Temperature is a descriptor of the thermodynamic temperature of a system, a measure of the mean kinetic energy of the components of the system.
Generalizations
Simple
7.5.7 Time
Time describes a unit of, well, time.
Generalizations
Simple
8 UnitsLibrary (informative)
8.1 CompoundUnits
SENSR does not offer normative units, nor does it offer normative compound dimensional units. At the most abstract, SENSR provides 'pure' units in the FoundationalUnits package which are then filled in to form a basic unit set.
Compound Units combine these Foundational Units into more complex forms, such as velocity (Length / Time), acceleration (Length / Time Squared), area (Length Squared), and volume (Length Cubed).
This is accomplished through the Unit::Multiply and Unit::Exponent classes. In general, use the Exponent class to raise a Foundational Unit to the proper power, including negative powers, and then Multiply to combine like terms into a single Compound Unit. Common examples are included in Figure 8.1.

Figure 8.1: Compound Units Object Diagram
8.2 **SIUnits**
The International System of units (SI), commonly known as the metric system, is arguably the most common and important unit system in technical environments. It is not, however, the only unit system. Instead of creating a normative SI Unit library, SENSR offers vendors and consumers a way to jointly describe SI Units in a natural way.

<table>
<thead>
<tr>
<th>Ampere : Current</th>
<th>name = "ampere"</th>
</tr>
</thead>
<tbody>
<tr>
<td>Candela : Light</td>
<td>name = "candela"</td>
</tr>
<tr>
<td>Kelvin : Temperature</td>
<td>name = "kelvin"</td>
</tr>
<tr>
<td>Kilogram : Mass</td>
<td>name = "kilogram"</td>
</tr>
<tr>
<td>Meter : Length</td>
<td>name = "meter"</td>
</tr>
<tr>
<td>Mole : Amount</td>
<td>name = "mole"</td>
</tr>
<tr>
<td>Second : Time</td>
<td>name = "second"</td>
</tr>
</tbody>
</table>
**Figure 8.2: SI Units Object Diagram**
8.3 **CompoundSIUnits**
This library provides examples of how to use the SI Units and the techniques from the Compound Units to create the common and useful forms seen in industry. Any physical phenomenon that can be measured using SI Units can be modeled in this manner. Common examples are shown in Figure 8.3.
8.4 **USCustomary**
An example of how the seven Simple Units can be used to create instances corresponding to the US Customary unit system. Examples of Scaled units and compound units are provided.
Figure 8.3: Compound SI Units Object Diagram
Figure 8.4: US Customary Units Object Diagram
- **Dozen**: Amount
- name = "dozen"
- **Ampere**: Current
- name = "ampere"
- **Foot**: Length
- name = "foot"
- **Fahrenheit**: Temperature
- name = "fahrenheit"
- **Mile**: Scaled
- base = Foot
- magnitude = 5280.0
- name = "mile"
- **Candela**: Light
- name = "candela"
- **Pound**: Mass
- name = "pound"
- **MPH**: Multiply
- name = "mph"
- op1 = Mile
- op2 = PerHour
- **Hour**: Time
- name = "hour"
- **PerHour**: Exponent
- base = Hour
- name = "perHour"
- power = -1.0
9 Examples (informative)
9.1 Example 1
A simple example showing a DataSheet describing two DataElements. The first is a 32-bit IEEE 754 unsigned floating point number that represents frequency (Hz) in the SI unit system. The second is similarly a 32-bit IEEE 754 unsigned floating point number, but it represents acceleration in the SI unit system.
Listing 9.1 shows a fully expanded form of this data, with redundancy but clarity.
```xml
<?xml version='1.0' encoding='UTF-8'?>
<xmi:XMI xmlns:xmi='http://www.omg.org/spec/XMI/20131001'
xmlns:sensr='http://www.omg.org/spec/SENSR/20191001'>
<!--
frequency: 32-bit IEEE 754 Hz (1/sec)
acceleration: 32-bit IEEE 754 (m/sec^2)
-->
<sensr:DataSheet>
<name xmi:type="String">Example1</name>
<vendorID xmi:type="String">0</vendorID>
<sensr:Quantity>
<name xmi:type="String">frequency</name>
<syntax xmi:type="sensr:FixedSize">32bit</syntax>
<unit xmi:type="sensr:Exponent">perSec</unit>
<description xmi:type="FloatingPoint">
IEEE754-1
isSigned=false
base=10
</description>
</sensr:Quantity>
<sensr:Quantity>
<name xmi:type="String">acceleration</name>
<syntax xmi:type="sensr:FixedSize">32bit</syntax>
<unit xmi:type="sensr:Multiply">acceleration</unit>
</sensr:Quantity>
</sensr:DataSheet>
Simplified Electronic Notation for Sensor Reporting (SENSR) 1.0(beta)
9.2 Example 2
This is an equivalent example to Example 1, but instead of explicit instances, it shares instances where possible. You can see the reduction in size in Listing 9.2. The redundancy is eliminated, with a slight reduction in clarity.
```xml
<?xml version='1.0' encoding='UTF-8'?>
<xmi:XMI xmlns:xmi='http://www.omg.org/spec/XMI/20131001'
xmlns:sensr='http://www.omg.org/spec/SENSR/20191001'>
<!--
frequency: 32-bit IEEE 754 Hz (1/sec)
acceleration: 32-bit IEEE 754 (m/sec^2)
-->
<sensr:DataSheet>
<name xmi:type="String">Example2</name>
<vendorID xmi:type="String">0</vendorID>
<sensr:Quantity>
<name xmi:type="String">frequency</name>
<syntax xmi:type="sensr:FixedSize" xmi:id="32bit">32-bit</syntax>
<unit xmi:type="sensr:Exponent">
<power xmi:type="float">-1.0</power>
<base xmi:type="sensr:Time" xmi:id="Second">Second</base>
</unit>
<description xmi:type="FloatingPoint">IEEE754</description>
</sensr:Quantity>
</sensr:DataSheet>
</xmi:XMI>
```
Listing 9.1: ..//Example 1
Figure 9.1: Example 1 Object Diagram
9.3 Example 3
This is an example of three identical data types being reported in succession. Each is a signed 8-bit integer, reporting acceleration in SI units across the x, y, and z axes.
The corresponding XML file can be found in Listing 9.3. You can see how the xmi:id and xmi:idref mechanism can be used to reduce the size of the XML file by referring to pre-existing elements in the file. This allows a user of SENSR to achieve both a self-contained file, and compactness.
```xml
<?xml version='1.0' encoding='UTF-8'?>
<xmi:XMI xmlns:xmi='http://www.omg.org/spec/XMI/20131001'
xmns:sensr='http://www.omg.org/spec/SENSR/20191001'>
<!-- vectored acceleration:
acceleration: 8-bit signed int (m/sec^2)
acceleration: 8-bit signed int (m/sec^2)
acceleration: 8-bit signed int (m/sec^2) -->
<sensr:DataSheet>
<name xmi:type="String">VectoredAcceleration</name>
<vendorID xmi:type="String">0</vendorID>
<sensr:Composite>
<name xmi:type="String">vectored_acceleration</name>
<sensr:Quantity>
<name>x</name>
<reference xmi:type="String"/>
<syntax xmi:type="sensr:FixedSize" xmi:id="8bit">
<name xmi:type="String">8-bit</name>
</syntax>
<unit xmi:type="sensr:Multiply">
<op1 xmi:type="sensr:Length" xmi:id="Meter">
<name>Meter</name>
</op1>
<op2 xmi:type="sensr:Exponent">
<power xmi:type="float">-2.0</power>
<base xmi:idref="Second"/>
</op2>
</unit>
</sensr:Quantity>
</sensr:Composite>
</sensr:DataSheet>
</xmi:XMI>
```
Listing 9.2: //Example 2
Figure 9.2: Example 2 Object Diagram
Listing 9.3: ..//Example 3
Figure 9.3: Example 3 Object Diagram
10 PSM (Bluetooth LE) (informative)
Bosch has created a Bluetooth LE (BLE) Advertising implementation, and provided example data being transmitted. The following PSM is a description of the model of the example data, and is presented in both XML and JSON formats suitable for machine reading and configuration. The UML object diagram in Figure 10 is a match for the example Listing 1.1 from Section 1. Listing 10.1 defines this model in XML. Note that the xmlns directive is pointing to a speculative URI. The correct URI will be generated upon adoption of this specification. The JSON representation requires a slight change, in that to reference JSON elements, one must use the name of the element in the JSON tree. To do this requires adding a ‘type’ field to each node to indicate which SENSR class it is an instance of. This is shown in Listing 10.2.
```xml
<?xml version="1.0" encoding="UTF-8"?>
<DataSheet id="TemperatureSensorEDS" name="Temperature Sensor" version="1.0">
<Element name="Centigrade" syntax="Fixed8" units="Centigrade">
<Value name="Temperature_max24h" type="Fixed8" scale=32768 isSigned=true value="3815" />
<Value name="Temperature_min24h" type="Fixed8" scale=32768 isSigned=true value="0" />
<Value name="Temperature_max1h" type="Fixed8" scale=32768 isSigned=true value="0" />
<Value name="Temperature_min1h" type="Fixed8" scale=32768 isSigned=true value="0" />
<Value name="Battery Status" type="Fixed8" scale=32768 isSigned=true value="0" />
<Value name="Counter" type="Fixed8" scale=32768 isSigned=true value="0" />
<Value name="Sensor ID" type="Fixed16" scale=32768 isSigned=true value="0" />
<Value name="Telegram Version" type="Int16" scale=32768 isSigned=true value="0" />
<Value name="Payload Encryption" type="Int8" scale=32768 isSigned=true value="0" />
<Value name="Payload Encryption" type="Int8" scale=32768 isSigned=true value="0" />
<Value name="Payload Encryption" type="Int8" scale=32768 isSigned=true value="0" />
<Value name="Payload Encryption" type="Int8" scale=32768 isSigned=true value="0" />
<Value name="Payload Encryption" type="Int8" scale=32768 isSigned=true value="0" />
<Value name="Payload Encryption" type="Int8" scale=32768 isSigned=true value="0" />
</Element>
<Elements>
<Payload_Value_1 name="SensorID" type="Int16" syntax="Fixed16" units n bits="16" value="0" />
<Payload_Value_2 name="Battery Status" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_3 name="Counter" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_4 name="Telegram Version" type="Int16" syntax="Fixed16" units n bits="16" value="0" />
<Payload_Value_5 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_6 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_7 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_8 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_9 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_10 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_11 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
<Payload_Value_12 name="Payload Encryption" type="Int8" syntax="Fixed8" units n bits="8" value="0" />
</Elements>
</DataSheet>
</xmi:XMI>
```
Figure 10.1: PSM Example
Listing 10.1: PSM XML
{"TemperatureSensorEDS": {
"type": "DataSheet",
"name": "Temperature Sensor",
"version": "1.0",
"author": "A. Cordes, BOSCH",
"creationDateTime": "20180821T0800Z"
}}
"modifyingAuthor": "A._Cordes, BOSCH",
"modificationDateTime": "20180821T0800Z",
"Integer": {
"type": "Integer",
"isSigned": "true"
},
"Flags":{
"type": "Bitfield",
"name": "Flags"
},
"Unused": {
"type": "Ignore"
},
"Fixed8_8": {
"type": "FixedPoint",
"name": "Fixed8_8",
"base": "10",
"scale": "32768"
},
"Fixed16": {
"type": "FixedSize",
"name": "Int16",
"bits": "16"
},
"Fixed8": {
"type": "FixedSize",
"name": "Int8",
"bits": "8"
},
"Fixed2": {
"type": "FixedSize",
"name": "Int2",
"bits": "2"
},
"Fixed1": {
"type": "FixedSize",
"name": "Flag",
"bits": "1"
},
"Centigrade": {
"type": "Temperature",
"name": "Centigrade"
},
"n": {
"type": "Amount"
},
"Zero": {
"type": "Constant",
"name": "Zero",
"bits": "1",
"value": "0"
},
"SensorID": {
"type": "Constant"
"name": "SensorID",
"bits": "16",
"value": "3815"
},
"Data": {
"type": "Container",
"elements": {
"Payload_Value_1": {
"type": "Quantity",
"name": "SensorID",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#SensorID"},
"units": {"$ref": "/#n"}
},
"Payload_Value_2": {
"type": "Quantity",
"name": "Counter",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#Fixed8"},
"units": {"$ref": "/#n"}
},
"Payload_Value_3": {
"type": "Quantity",
"name": "Unused",
"description": {"$ref": "/#Unused"},
"syntax": {"$ref": "/#Fixed8"},
"units": {"$ref": "/#n"}
},
"Payload_Value_4": {
"type": "Quantity",
"name": "Telegram Version",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#Fixed2"},
"units": {"$ref": "/#n"}
},
"Payload_Value_5": {
"type": "Quantity",
"name": "Unused",
"description": {"$ref": "/#Unused"},
"syntax": {"$ref": "/#Zero"},
"units": {"$ref": "/#n"}
},
"Payload_Value_6": {
"type": "Quantity",
"name": "Payload Encryption",
"description": {"$ref": "/#Flags"},
"syntax": {"$ref": "/#Fixed1"},
"units": {"$ref": "/#n"}
},
"Payload_Value_7": {
"type": "Quantity",
"name": "Battery Status",
"description": {"$ref": "/#Flags"},
"syntax": {"$ref": "/#Fixed1"},
"units": {"$ref": "/#n"}
}
}
"Payload_Value_8": {
"type": "Quantity",
"name": "Temperature",
"description": {"$ref": "/#Fixed8_8"},
"syntax": {"$ref": "/#Fixed16"},
"units": {"$ref": "/#Centigrade"}
},
"Payload_Value_9": {
"type": "Quantity",
"name": "Temperature_max1h",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#Fixed8"},
"units": {"$ref": "/#Centigrade"}
},
"Payload_Value_10": {
"type": "Quantity",
"name": "Temperature_min1h",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#Fixed8"},
"units": {"$ref": "/#Centigrade"}
},
"Payload_Value_11": {
"type": "Quantity",
"name": "Temperature_max24h",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#Fixed8"},
"units": {"$ref": "/#Centigrade"}
},
"Payload_Value_12": {
"type": "Quantity",
"name": "Temperature_min24h",
"description": {"$ref": "/#Integer"},
"syntax": {"$ref": "/#Fixed8"},
"units": {"$ref": "/#Centigrade"}
}
}
Listing 10.2: PSM JSON
|
{"Source-Url": "https://www.omg.org/spec/SENSR/1.0/Beta1/PDF", "len_cl100k_base": 13761, "olmocr-version": "0.1.53", "pdf-total-pages": 43, "total-fallback-pages": 0, "total-input-tokens": 78458, "total-output-tokens": 16294, "length": "2e13", "weborganizer": {"__label__adult": 0.0003724098205566406, "__label__art_design": 0.0008301734924316406, "__label__crime_law": 0.0005450248718261719, "__label__education_jobs": 0.0008063316345214844, "__label__entertainment": 0.0001329183578491211, "__label__fashion_beauty": 0.00024020671844482425, "__label__finance_business": 0.0016384124755859375, "__label__food_dining": 0.0003402233123779297, "__label__games": 0.0007066726684570312, "__label__hardware": 0.0161590576171875, "__label__health": 0.00032973289489746094, "__label__history": 0.0003769397735595703, "__label__home_hobbies": 0.0001856088638305664, "__label__industrial": 0.004299163818359375, "__label__literature": 0.0002884864807128906, "__label__politics": 0.00042724609375, "__label__religion": 0.0006546974182128906, "__label__science_tech": 0.2137451171875, "__label__social_life": 6.341934204101562e-05, "__label__software": 0.039093017578125, "__label__software_dev": 0.7177734375, "__label__sports_fitness": 0.00025272369384765625, "__label__transportation": 0.0007123947143554688, "__label__travel": 0.0001885890960693359}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56209, 0.04654]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56209, 0.48634]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56209, 0.76674]], "google_gemma-3-12b-it_contains_pii": [[0, 226, false], [226, 3365, null], [3365, 7228, null], [7228, 8927, null], [8927, 10653, null], [10653, 13336, null], [13336, 17162, null], [17162, 18086, null], [18086, 18694, null], [18694, 18725, null], [18725, 19896, null], [19896, 20821, null], [20821, 23399, null], [23399, 23499, null], [23499, 24600, null], [24600, 25411, null], [25411, 28151, null], [28151, 30806, null], [30806, 31699, null], [31699, 33487, null], [33487, 34139, null], [34139, 36061, null], [36061, 37238, null], [37238, 39018, null], [39018, 39814, null], [39814, 41176, null], [41176, 41883, null], [41883, 42727, null], [42727, 44014, null], [44014, 44059, null], [44059, 44625, null], [44625, 46140, null], [46140, 47214, null], [47214, 47251, null], [47251, 48890, null], [48890, 48927, null], [48927, 48954, null], [48954, 48991, null], [48991, 52726, null], [52726, 52935, null], [52935, 53756, null], [53756, 55249, null], [55249, 56209, null]], "google_gemma-3-12b-it_is_public_document": [[0, 226, true], [226, 3365, null], [3365, 7228, null], [7228, 8927, null], [8927, 10653, null], [10653, 13336, null], [13336, 17162, null], [17162, 18086, null], [18086, 18694, null], [18694, 18725, null], [18725, 19896, null], [19896, 20821, null], [20821, 23399, null], [23399, 23499, null], [23499, 24600, null], [24600, 25411, null], [25411, 28151, null], [28151, 30806, null], [30806, 31699, null], [31699, 33487, null], [33487, 34139, null], [34139, 36061, null], [36061, 37238, null], [37238, 39018, null], [39018, 39814, null], [39814, 41176, null], [41176, 41883, null], [41883, 42727, null], [42727, 44014, null], [44014, 44059, null], [44059, 44625, null], [44625, 46140, null], [46140, 47214, null], [47214, 47251, null], [47251, 48890, null], [48890, 48927, null], [48927, 48954, null], [48954, 48991, null], [48991, 52726, null], [52726, 52935, null], [52935, 53756, null], [53756, 55249, null], [55249, 56209, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56209, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56209, null]], "pdf_page_numbers": [[0, 226, 1], [226, 3365, 2], [3365, 7228, 3], [7228, 8927, 4], [8927, 10653, 5], [10653, 13336, 6], [13336, 17162, 7], [17162, 18086, 8], [18086, 18694, 9], [18694, 18725, 10], [18725, 19896, 11], [19896, 20821, 12], [20821, 23399, 13], [23399, 23499, 14], [23499, 24600, 15], [24600, 25411, 16], [25411, 28151, 17], [28151, 30806, 18], [30806, 31699, 19], [31699, 33487, 20], [33487, 34139, 21], [34139, 36061, 22], [36061, 37238, 23], [37238, 39018, 24], [39018, 39814, 25], [39814, 41176, 26], [41176, 41883, 27], [41883, 42727, 28], [42727, 44014, 29], [44014, 44059, 30], [44059, 44625, 31], [44625, 46140, 32], [46140, 47214, 33], [47214, 47251, 34], [47251, 48890, 35], [48890, 48927, 36], [48927, 48954, 37], [48954, 48991, 38], [48991, 52726, 39], [52726, 52935, 40], [52935, 53756, 41], [53756, 55249, 42], [55249, 56209, 43]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56209, 0.05198]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
2c9df1ff191239e53c0c82efce7e47d78364c412
|
Formal Analysis of Sequence Diagram with Combined Fragments
Hui Shen, Mark Robinson and Jianwei Niu
Department of Computer Science, University of Texas at San Antonio, San Antonio, Texas, U.S.A.
Keywords: Modeling, Model Checking, Sequence Diagram, Concurrency & Communication.
Abstract: The Combined Fragments of UML Sequence Diagram permit various types of control flow among messages (e.g., interleaving and branching) to express an aggregation of multiple traces encompassing complex and concurrent behaviors. However, Combined Fragments increase the difficulty of Sequence Diagram comprehension and analysis. To alleviate this problem, we introduce an approach to formally describe Sequence Diagrams with Combined Fragments in terms of the input language of the model checker NuSMV. This approach permits the verification of desired properties against Sequence Diagrams.
1 INTRODUCTION
In software development process, models enable software engineers to detect errors during early stage so as to improve the system quality. Scenario-based models have been widely employed for the description of interactions among environmental actors (e.g., human beings) and the components (aka Lifeline) of the software systems through the exchange of messages. UML Sequence Diagrams, which graphically depict scenarios, serve as well-accepted and intuitive media among software engineers and tool builders. UML 2 provides many major structural control constructs, including Combined Fragments and Interaction Use, to allow multiple, complex scenarios to be aggregated in a single Sequence Diagram. However, Combined Fragments introduce concurrent behaviors, making analysis of the Sequence Diagrams difficult for the following reasons.
Combined Fragments permit different types of control flow, such as interleaving and branching, increasing a Sequence Diagram’s expressiveness. Further, the Combined Fragments can also be nested to provide more complex control flows. These make it difficult to predict what behavior are represented. For example, if a Combined Fragment presenting branching behavior is nested within a Combined Fragment presenting iteration behavior, different choices may be made in different iterations. The semantics of Sequence Diagram with Combined Fragments is not formally defined compared to their precise syntax descriptions (Object Management Group, 2011), making it hard to derive the traces from Sequence Diagrams. Thus, subtle errors from concurrency can easily be introduced to Sequence Diagrams to evade discovery via manual inspection.
To address these problems, we introduce an automated technique to facilitate the verification of Sequence Diagrams by leveraging the analytical powers of model checking. Working towards similar goals, many researchers have verified different scenario-based models, including Sequence Diagram, Message Sequence Chart (MSC), and Live Sequence Chart (LSC). However, the previous work does not consider all the aspects of Combined Fragments. Our approach supports all the features of Combined Fragments, including all 12 Interaction Operators, nested Combined Fragments, both asynchronous and synchronous Messages, and Interaction Constraints.
We devise an approach to codify the semantics of Sequence Diagrams and Combined Fragments in the input language of NuSMV by deconstructing Sequence Diagrams and Combined Fragments to obtain fine-grained syntactic constructs (see section 2 and 3). We formally describe each Combined Fragment in terms of NuSMV (Cimatti et al., 2000) modules (see section 4). The model checking mechanism can explore all possible traces specified in the Sequence Diagram, verifying if the desired properties are satisfied. We have developed a tool suite to implement all of the techniques and have validated our technique by analyzing and discovering violations in two design examples taken from an insurance industry software application (see section 5). We have also created an Occurrence Specification Trace Diagram generator that automatically produces Sequence Diagram visualiza-
tions from NuSMV-produced counterexamples. This automation will increase the accessibility of our approach by allowing software engineers to remain focused in the realm of Sequence Diagrams.
2 UML 2 SEQUENCE DIAGRAM
In this section, we outline the syntax and semantics of a Sequence Diagram with Combined Fragments provided by OMG (Object Management Group, 2011). As the first step of defining a Sequence Diagram using NuSMV modules, we precisely define the semantics of Sequence Diagram with Combined Fragments, forming the basis of expressing the semantics in term of NuSMV models. We begin with the basic Sequence Diagram, then discuss the structured control constructs, including Combined Fragments and Interaction Use.
2.1 Basic Sequence Diagram
We refer to a Sequence Diagram without Combined Fragments as a basic Sequence Diagram (see figure 1a for an example with annotated syntactic constructs). A Lifeline is a vertical line representing a participating object. A horizontal line between Lifelines is a Message. A Message is the specification of an occurrence of a message type within the Sequence Diagram, while a message type is the signature of the form ⟨message name, source Lifeline, target Lifeline⟩. Within a Sequence Diagram, a message type can occur multiple times, which are associated with multiple Messages. Each Message is sent from its source Lifeline blocks until it receives the target Lifeline’s response (Object Management Group, 2011; Kugler et al., 2005)
1. Each OS can execute only once, i.e., each OS is unique within a Sequence Diagram.
2. On each Lifeline, OSs execute in their graphical order from top to bottom.
3. For a single Message, the sending OS must take place before the receiving OS does.
4. In a Sequence Diagram, only one object can execute an OS at a time, i.e., OSs on different Lifelines are interleaved.
Messages are of two types: asynchronous and synchronous. The source Lifeline can continue to send or receive other Messages after an asynchronous Message is sent. If a synchronous Message is sent, the source Lifeline blocks until it receives the target Lifeline’s response (Object Management Group, 2011).
2.2 Combined Fragment
Both Combined Fragments and Interaction Use are structured control constructs introduced in UML 2. A Combined Fragment (CF) is a solid-outline rectangle, which consists of an Interaction Operator and one or more Interaction Operands. Figure 1b shows example CFs with annotated syntactic constructs. A CF can enclose all, or part of, Lifelines in a Sequence Diagram. The Interaction Operands are separated by dashed horizontal lines. The Interaction Operator is shown in a pentagon in the upper left corner of the rectangle. OSs, CFs, and Interaction Operands are collectively called Interaction Fragments. An Interaction Operand may contain a boolean expression which is called an Interaction Constraint or Constraint. An Interaction Constraint is shown in a square bracket covering the Lifeline where the first OS will happen. BEU, HEU and CEU are defined in Section 3. An Interaction Use construct allows one Sequence Diagram to refer to another Sequence Diagram. The referring Sequence Diagram copies the contents of the referenced Sequence Diagram.
We identify three independent semantic rules general to all CFs, in the sense that these rules do not constrain each other.
1. OSs and CFs, are combined using Weak Sequencing (defined below). On a single Lifeline, a CF’s preceding Interaction Fragment must complete the execution prior to the CF’s execution, and the CF’s succeeding Interaction Fragment must execute subsequently.
2. Within a CF, the order of the OSs and CFs within each Operand is maintained if the Constraint of the Operand evaluates to \text{True}; otherwise, the Operand is excluded.
3. The CF does not execute when the Constraints of all the Operands evaluate to \text{False}. Thus, the CF’s preceding Interaction Fragment and succeeding Interaction Fragment are ordered by Weak Sequencing.
2.3 Interaction Operator
The semantics of each CF Operator determines the execution order of all the Operands. Each Operator has its specific semantic implications regarding the execution of the OSs enclosed by the CF on the covered Lifelines. The Operators are summarized as follows:
- **Alternatives**: one of the Operands whose Interaction Constraints evaluate to \text{True} is nondeterministically chosen to execute.
- **Option**: its sole Operand executes if the Interaction Constraint is \text{True}.
- **Break**: its sole Operand executes if the Interaction Constraint evaluates to \text{True}. Otherwise, the remainder of the enclosing Interaction Fragment executes.
- **Parallel**: the OSs on a Lifeline within different Operands may be interleaved, but the ordering imposed by each Operand must be maintained separately.
- **Critical Region**: the OSs on a Lifeline within its sole Operand must not be interleaved with any other OSs on the same Lifeline.
- **Loop**: its sole Operand will execute for at least the minimum count (lower bound) and no more than the maximum count (upper bound) as long as the Interaction Constraint is \text{True}.
- **Assertion**: the OSs on a Lifeline within its sole Operand must occur immediately after the preceding OSs.
- **Negative**: its Operand represents forbidden traces.
- **Strict Sequencing**: in any Operand except the first one, OSs cannot execute until the previous Operand completes.
- **Weak Sequencing**: on a Lifeline, the OSs within an Operand cannot execute until the OSs in the previous Operand complete, the OSs from different Operands on different Lifelines may take place in any order (cf. Strict Sequencing).
**Consider**: any message types other than what is specified within the CF is ignored. **Ignore**: the specified message types are ignored within the CF.
The semantics of the \text{seq} Sequence Diagram is defined by two sets of traces, one containing a set of valid traces, denoted as \text{Val(seq)}), and the other containing a set of invalid traces, denoted as \text{Inval(seq)}.
The intersection of these two sets is empty, i.e., \text{Val(seq)} \cap \text{Inval(seq)} = \emptyset.
3 SEQUENCE DIAGRAM DECONSTRUCTION
To facilitate codifying the semantics of Sequence Diagrams and nested CFs in NuSMV models, we show how to deconstruct a Sequence Diagram and CFs to obtain fine-grained syntactic constructs. Eichner et al. have defined the Maximal Independent Set in (Eichner et al., 2005) to deconstruct a Sequence Diagram into fragments, each of which covers multiple Lifelines. Their proposed semantics defines that entering a CF has to be done synchronously by all the Lifelines, i.e., each CF is connected with adjacent OSs and CFs using Strict Sequencing. Recall that CFs can be nested within other CFs. OSs and CFs directly enclosed in the same CF or Sequence Diagram are combined using Weak Sequencing, constraining their orders with respect to each individual Lifeline only (Object Management Group, 2011). To express the semantics of Weak Sequencing, we further deconstruct a Sequence Diagram into syntactic constructs on each Lifeline, which also helps us to define the semantics of nested CFs.
We project every CF \( c_{fm} \) onto each of its covered Lifelines \( l_i \) to obtain a **compositional execution unit** (CEU), which is denoted by \( c_{fm} \uparrow l_i \). (The shaded rectangle on Lifeline \( L1 \) in figure 1b shows an example).
**Definition 1.** A CEU is given by a three tuple \( \langle l_i, \)
oper, setEU), where $l_i$ is the Lifeline, onto which we project the CF, $oper$ is the Interaction Operator of the CF, and $setEU$ is the set of execution units, one for each $Operand op_n$ enclosed in the CF on Lifeline $l_i$.
Every $Operand op_n$ of CF $cf_m$ is projected onto each of its covered Lifelines $l_i$ to obtain an execution unit (EU) while projecting $cf_m$ onto $l_i$, denoted by $op_n \砾 l_i$. If the projected Interaction Operand contains a nested CF, a hierarchical execution unit (HEU) is obtained; otherwise a basic execution unit (BEU) is obtained, i.e., an EU is a BEU if it does not contain any other EUs. (The lower shaded rectangle on Lifeline $L2$ in figure 1b shows an example of a BEU and the shaded rectangle on Lifeline $L3$ shows an example of an HEU).
**Definition 2.** A BEU $u$ is given by a pair, $(E_u, cond)$, in which $E_u$ is a finite set of OSs on Lifeline $l_i$ enclosed in Operand $op_n$, which are ordered by the locations associated with them, and $cond$ is the Interaction Constraint of the Operand; $cond$ is True when there is no Interaction Constraint.
**Definition 3.** An HEU is given by $(setCEU, setBEU, cond_l)$, where $setCEU$ is the set of CEUs directly enclosed in the HEU, i.e., the CEUs nested within any element of $setCEU$ are not considered. $setBEU$ is the set of BEUs that are directly enclosed in the HEU.
Projecting a Sequence Diagram onto each enclosing Lifeline also obtains an EU whose Constraint is True. The EU is an HEU if the Sequence Diagram contains CFs, otherwise, it is a BEU. In an HEU, we also group the OSs between two adjacent CEUs or prior to the first CEU or after the last CEU on the same level into BEUs, which inherit the parent HEU’s Constraint, $cond_l$. (The upper shaded rectangle on Lifeline $L2$ in figure 1b shows an example). The constituent BEUs(s) and CEU(s) within an HEU execute sequentially, complying with their graphical order, as do the OSs in the BEU.
4 VERIFYING SEQUENCE DIAGRAMS VIA NUSMV
In this section, we develop techniques to translate Sequence Diagrams into the input language of NuSMV. The NuSMV model preserves the structure of the Sequence Diagrams (e.g., Lifelines and CFs), which makes it easier to demonstrate that the semantics of the original notation is maintained.
4.1 NuSMV Overview
NuSMV is a model checking tool, which exhaustively explores all executions of a finite model to determine if a temporal logic property holds. For a property that does not hold, a counterexample is produced showing an error trace. A NuSMV model consists of one main module and may include other modules with formal parameters. An instance of a module can be created using the $VAR$ declaration within main module or other module to create a modular hierarchy. To access variables of instance modules, the instance name with . (DOT) can be used to follow by the variable name. The composition of multiple modules can be parallel or interleaving.
NuSMV variables must be of finite types, declared inside each module. The initial states are defined by using an $init$ statement of the form $init(x) := EXP$, which defines the value or set of values $x$ can assume initially. Transitions are defined by using the $next$ statements of the form $next(x) := EXP$, which defines the value or set of values that $x$ can assume in the following state. All the transitions in a module execute concurrently in each step. Derived variables (i.e., macros) are defined by using $DEFINE$ statements of the form $x := EXP$ and they are replaced by $EXP$ in each state. The system’s invariant is represented with the $INVAR$ statement, which is a boolean expression satisfied by each state.
4.2 Mapping Overview
We base the mapping of a Sequence Diagram to the input language of NuSMV on syntactic deconstruction. A Sequence Diagram is represented as the main module. We map the Lifelines into respective NuSMV modules, which are instantiated and declared in the main module. Recall that a CF is projected onto each of its covered Lifelines to obtain a CEU. Accordingly, its Operand on each of the covered Lifelines forms an EU. Both CEUs and EUs are represented as NuSMV modules.
Each CEU is declared as a module instance, which we call a submodule in its Lifeline module. To enforce that multiple CEUs at the same level on each Lifeline adhere to their graphical order, we define a derived variable, $flag_final$, for each CEU module, to indicate whether the CEU completes its execution (the CF semantic rule 1). A CEU is composed of one or more EUs, each of which is instantiated as a submodule inside the CEU module. The execution order of multiple EUs (i.e., the transfer of control among them) is determined by the Interaction Operator that composes them into the CEU (the translation of each Operator is discussed later in this section). In the case that a Sequence Diagram contains nested CFs (i.e., a CEU consisting of an EU that encloses other CEUs), we map each enclosed CEU as a submodule
of the containing EU’s module. This procedure is recursively applied until all CEUs and EUs are mapped accordingly.
The semantic rules for a basic Sequence Diagram defined in section 2.1 are codified using NuSMV modules for Lifelines or EUs, and an INVAR statement. Within Lifeline or EU modules, a directly enclosed OS is represented as a boolean variable, which initializes to False (note that a CEU module does not contain OS variables). Once an OS occurs, its value is set to True and then to False in all the following states. This value transition expresses the fact that an OS can occur only once in the Sequence Diagram (the semantic rule 1). To record the execution history of OSs, we introduce an enumerated variable, state, for each Lifeline and EU module, expressing that respective OSs have taken place (the semantic rule 2). A CEU module contains one boolean variable, cond, for each of its EUs to represent the Interaction Constraint of the EU.
To express the interleaving semantics among Lifelines, we introduce an INVAR statement in the main module to assert that at most one OS on one of the Lifelines can take place in each step (the semantic rule 4). A boolean variable chosen is used for each Lifeline to restrict that: (1) a Lifeline is chosen only if it is enabled, i.e., there is an OS that is ready to take place on the Lifeline, represented by the derived variable enabled; (2) either only one Lifeline can be chosen to execute an OS in each step if Lifelines are enabled (i.e., before all OSs on the Lifelines have occurred); or no Lifeline can be chosen when all Lifelines are not enabled and all chosen variables remain False thereafter. A sending OS is enabled to execute if and only if the OSs prior to it on the same Lifeline have already occurred. A receiving OS is enabled to execute if and only if the OSs prior to it on the same Lifeline and the sending OS of the same Message have already occurred (the semantic rules 2 and 3). To execute the OSs enclosed in CFs, the variable chosen for each Lifeline is passed to the CEU and EU modules on that Lifeline as a parameter.
4.3 Basic Sequence Diagram with Asynchronous Messages
In this subsection, we illustrate our mapping strategy with an example basic Sequence Diagram as shown in figure 1a. Figure 2 shows the NuSMV description of the example, which contains a main module for the Sequence Diagram. We map the three Lifelines to three modules, which are instantiated as submodules \( l_1 \), \( L_1 \), \( l_2 \), and \( L_2 \) in the main module. We show the implementation of module \( L_2 \) here. Module \( L_2 \) takes modules \( L_1 \), \( L_3 \) as parameters. Three OSs on Lifeline \( L_2 \) are defined as boolean variables \( OS_{r1} \), \( OS_{s2} \), and \( OS_{r3} \) in the VAR section. We define each OS as \( OS_{s3} \) or \( OS_{rx} \), where \( s \) and \( r \) denote they are sending or receiving OSs, and \( x \) is the corresponding Message name. The enumerated variable state has four values, including an initial value \( sin init \) and three values to record the execution of the three respective OSs. A derived variable enabled for each OS represents the enabling condition of the OS by using the variable state in the DEFINE section. For instance, \( r3\_enabled \) for OS \( r3 \) is True if and only if the sending OS of Message \( m3 \) and the preceding OS, \( OS_{s2} \), on Lifeline \( L_2 \) have occurred, i.e., state on Lifelines \( L_2 \) and \( L_3 \) set to \( s2 \) and \( s3 \) respectively. The Lifeline \( L_2 \) can be enabled if and only if one of \( r1 \), \( s2 \), and \( r3 \) is enabled. The variable \( flag\_final \) checks whether the last OS, \( r_3 \), on \( L_2 \) takes place (i.e., state sets to \( r3 \)). If so, all OSs in module \( L_2 \) have occurred. The ASIGN section defines the transition relation of module \( L_2 \). For example, \( OS_{r3} \) is set to False initially. When it is chosen and enabled, it is set to True. It is set to False in the subsequent states to represent that an OS can execute exactly once. \( OS_{r1} \) and \( OS_{s2} \) take the same transition as \( OS_{r3} \). Variable state is set to \( r1 \) in the same state where \( OS_{r1} \) occurs.
4.4 Basic Sequence Diagram with Synchronous Messages
Sequence Diagram with synchronous Messages restricts that the sending Lifeline blocks until a reply Message is received. We introduce a boolean variable, isBlock, for each Lifeline to capture this semantic aspect. All OSs on a Lifeline include isBlock as an enabling condition, thus preventing the OSs from occurring while isBlock is True.
4.5 Combined Fragments
A CF enclosing multiple Lifelines is projected onto all the Lifelines to obtain a collection of CEUs, one for each Lifeline. A CEU contains a collection of EUs, one for each Operand on the same Lifeline. To preserve the structure of the Sequence Diagram during translation, we map a CF to NuSMV submodules, one for each Lifeline module, while the EUs are mapped to NuSMV sub-submodules of their parent CEU submodule separately. We implement the Interaction Constraint for each Operand with a boolean variable cond. We do not control the value of cond until the Operand is entered, representing the fact that a condition may change during the execution of the Sequence Diagram. If cond evaluates to True, the
MODULE main
VAR
L_L1 : L1(L_L2, L_L3);
L_L2 : L2(L_L1, L_L3);
L_L3 : L3(L_L1, L_L2);
INVAR
{(l_L1.chosen -> l_L1.enabled)
& (l_L2.chosen -> l_L2.enabled)
& (l_L3.chosen -> l_L3.enabled)
& ((l_L1.chosen & l_L2.chosen & !l_L3.chosen)
| (l_L1.chosen & !l_L2.chosen & !l_L3.chosen)
| (l_L1.chosen & l_L2.chosen & !l_L3.chosen)
| (l_L1.chosen & !l_L2.chosen & l_L3.chosen)
| (!l_L1.chosen & !l_L2.chosen & !l_L3.chosen))
MODULE L2(L1, L3)
VAR
OS_r1 : boolean;
OS_s2 : boolean;
OS_r3 : boolean;
state : {sinit, r1, s2, r3};
chosen : boolean;
DEFINE
r1_enabled := state=sinit & L1.state=s1;
r2_enabled := state=r1;
r3_enabled := state=s2 & L3.state=s3;
enabled := r1_enabled & r2_enabled & r3_enabled;
ASSIGN
init(state) := sinit;
next(state) := case
state=sinit & next(OS_r1) := r1;
state=r1 & next(OS_s2) := s2;
state=s2 & next(OS_r3) := r3;
1 := state;
esac;
....
init(OS_r3) := FALSE;
next(OS_r3) := case
chosen & r3_enabled := TRUE;
OS_r3 := FALSE;
1 := OS_r3;
esac;
Figure 2: Basic sequence diagram to NuSMV.
Operand is entered, otherwise, the Operand is skipped (the CF semantic rule 2). Afterwards, the value of cond stays the same. While there is no Constraint in an Operand, cond is defined as constant True. An extra variable op_eva for each Operand indicates its respective execution status, including “not ready” (the OSs that may happen prior to the Operand on the Lifeline have taken place) by enumeration element 1, “ready but not enabled” (the Constraint evaluates to False) by enumeration element 0, and “start” (Constraint evaluates to True) by enumeration element 1. cond is evaluated when op_eva evaluates to either 0 or 1. Both cond and op_eva for each Operand are instantiated and declared in the CEU module on the Lifeline where the Interaction Constraint of the Operand is located. The value of op_eva is passed to other CEUs of the same CF as parameters, which is further passed to all the EUs of the same Operand to coordinate multiple EUs. From the deconstruction of Sequence Diagrams and CFs (see section 3), we define the OSs as boolean variables in the respective EUs that directly enclose them, instead of the CEUs; OSs that are not enclosed in any CF are declared as boolean variables in their Lifeline module.
4.5.1 Concurrency
In a Parallel CF, the Operands are interleaved, which is captured using a strategy similar to the implementation of interleaved Lifelines modules. We introduce a boolean variable chosen for each EU module to indicate whether the EU is chosen to execute. We add an INVAR statement for each CEU to assert that (1) either only one EU module is chosen to execute or no EUs are enabled (i.e., all EUs have completed execution or their Constraints evaluate to False), and (2) an EU module can be chosen only if it is enabled (i.e., an OS within the EU is enabled to execute). All INVAR statements are combined using logical conjunctions to form a global invariant in the main module.
Figure 1b shows an example Sequence Diagram, in which a Parallel contains a Critical Region. The implementation of its main module and the modules of Lifeline L2 and its CEU of the Parallel are shown in figure 3. In the module of Lifeline L2, the Parallel’s CEU module is initialized as a module instance. Two EUs of the Parallel’s Operands are initialized as two module instances within its CEU module.
In the Parallel, the Interaction Constraint of its Operand, op1, is located on L2. Thus, cond1 for op1 is initialized and declared in the Parallel’s CEU module on L2. It is set to the value of the evaluation step and remains that value in the following steps. Variable op1_eva is initialized to -1, and then is set depending on the value of cond1 when entering the CEU, i.e., it is set to 1 if cond1 evaluates to True or 0 otherwise. In each EU module of the Parallel, a variable chosen is used to denoted whether the EU is chosen to execute.
4.5.2 Atomic Execution
A Critical Region has a sole Operand while each CEU module having a single EU submodule. We use a boolean variable, isCritical, for each EU of the Critical Region’s Operand, to restrict the OSs within the EU from interleaving with other OSs on the same Lifeline. Variable isCritical is initialized to False in each EU module of the Critical Region’s Operand. It is set to True if the EU starts to execute OSs and stays True until the EU finishes execution. Once the EU completes, isCritical is set to False. The negation of
**IsCritical** of an EU is considered as an enabling condition for each variable of other OSs, which may interfere the EU, on the same Lifeline. See figure 1b for an example. On Lifeline L3, the sending OS of Message m6 takes the negation of **IsCritical** for the EU on Lifeline L3 as an enabling condition.
### 4.5.3 Branching
Collectively, we call Alternatives, Option, and Break branching constructs.
In an Alternatives CF, each Operand must have an explicit or an implicit an “else” Constraint. An implicit Constraint always evaluates to True. The “else” Constraint is the negation of the disjunction of all other Constraints in the enclosing Alternatives. The chosen Operand’s Constraint must evaluate to True. If none of the Operands whose Constraints evaluate to True, the Alternatives is excluded. For each Operand, a boolean variable **exe** indicates the execution status of the applicable Operand, i.e., **exe** is set to True if the Operand is chosen to execute.
The variable **exe** for each Operand is initialized and declared in the CEP module on the Lifeline where the Operand’s Constraint is located. The Constraint under INV AR restricts that an Operand’s **exe** can be set to True only if the Operand’s **cond** evaluates to True. It also restricts that at most one Operand can be chosen to execute, i.e., at most one **exe** can be set to True at a time, or all Operand Constraints evaluate to False. The use of **exe** guarantees that all the enclosed Lifelines choose the same Operand’s EU module to execute to avoid inconsistent choices (e.g., Lifeline L1 chooses Operand 1’s EU whereas Lifeline L2 chooses Operand 2’s EU). The **cond** of the chosen Operand stays True and those of the unchosen Operands are set to False and stay False.
The NuSMV representation of Option and Break can be derived from the one of Alternatives. The details of translation are described in (Shen et al., 2011).
### 4.5.4 Iteration
The Loop represents its sole Operand’s iterations, which are connected by Weak Sequencing. To restrict the number of iterations, the Operand’s Constraint may include a lower bound, **minint**, and an upper bound, **maxint**, i.e., a Loop iterates at least the **minint** number of times and at most the **maxint** number of times. If the Constraint evaluates to False after the **minint** number of iterations, the Loop will terminate.
Bounded Loop, whose **maxint** is given, can be translated to NuSMV modules. To keep each OS and Constraint within different iterations of a Loop
---
**Figure 3:** NuSMV module for Parallel.
unique, one way to implement an OS or a Constraint is defining an array to rename the OS or the Constraint of each iteration. For each Lifeline, We use \( n \) to represent the current iteration number. In this way, an OS within the Loop’s Operand, \( OS_{r1} \), and Constraint \( cond \) in iteration \( n \) can be represented as \( OS_{r1}[n] \) and \( cond[n] \) respectively. For example, if a Loop iterates at most three iterations, \( OS_{r1} \) in different iterations are defined as \( OS_{r1}[1], OS_{r1}[2] \) and \( OS_{r1}[3] \). The graphical order of the OSs within the same iteration is maintained, and the OSs among iterations execute sequentially along a Lifeline, i.e., OSs in iteration \( n \) take place before OSs in iteration \( n+1 \).
We need to evaluate the Interaction Constraint of its sole Operand after minimum number of iterations. If \( n \leq minint \), the Loop executes. If \( minint < n \leq maxint \), the Loop executes only if \( cond[n] \) evaluates to True. Otherwise, the Loop terminates and the values of the Constraint of remaining iterations (i.e., from \( cond[n+1] \) to \( cond[\text{maxint}] \)) is set to False. The Loop no longer executes when its iteration reaches \( \text{maxint} \).
4.5.5 Assertion
An Assertion represents that, on each Lifeline, a set of traces of its Operand are the only valid traces following the Assertion’s preceding OSs. The mapping strategy of the Assertion is very similar to the one of the Critical Region. For each Lifeline, a boolean variable \( in\text{Assertion} \) is initialized and declared in the EU module of the Assertion’s Operand, restricting the OSs within the EU from interleaving with other OSs on the same Lifeline if the OSs prior to the CEU of the Assertion finish execution. The variable \( in\text{Assertion} \) is False initially, and is set to True when the OSs in the set of \( \text{pre}(\text{CEU}) \) have executed. Function \( \text{pre}(\text{CEU}) \) returns the set of OSs which may happen right before the CEU of the Assertion. If the EU of the Assertion’s Operand completes execution, \( in\text{Assertion} \) is set to False and other OSs may execute. For each Lifeline, the negation of \( in\text{Assertion} \) is used as an enabling condition for each variable of other OSs, which may interleave the EU of the Assertion’s Operand.
4.5.6 Negation
We translate the Operand of a Negative into NuSMV modules, deriving all possible invalid traces.
4.5.7 Weak Sequencing and Strict Sequencing
The semantics of a Weak Sequencing enforces the total order among EUs of Operands on the same Lifeline. In any EU module of an Operand (except the first one), the first OS takes the variable \( \text{flag\_final} \) of the EU of the preceding Operand on the same Lifeline as an enabling condition, i.e., the EU cannot execute before the preceding one completes. Figure 4 is an example of Weak Sequencing. In the EU module of the second Operand on Lifeline \( L2 \), the first OS, \( r4 \), takes \( \text{flag\_final} \) of the EU occurring immediately before this EU (i.e., the EU of the first Operand) as an enabling condition.
The semantics of a Strict Sequencing enforces the total order between adjacent Operands. An EU module of an Operand (other than the first one) within a Strict Sequencing takes variable \( \text{flag\_final} \) of every EU module within the preceding Operand as enabling conditions of the first OS. It asserts that all EUs cannot execute until its preceding Operand completes execution. We can alter the Interaction Operator of the CF in figure 4 to strict to make it as an example of Strict Sequencing. Comparing to the example of Weak Sequencing, OS \( r4 \) also takes the variable \( \text{flag\_final} \) of the EUs of the first Operand on Lifelines \( L1 \) and \( L3 \) as enabling conditions additionally.
4.5.8 Ignore and Consider
Ignore and Consider make it possible to execute the Messages not explicitly appear in the CF. To map an Ignore (Consider) into NuSMV modules, we can explore all the traces of OSs in which Messages are ignored (not considered). We assume the signature of any Message of ignored (considered) types is given, i.e., the Lifelines where the sending OS and receiving OS of a Message occur are known. The Messages of ignored types can occur and interfere with the OSs appearing in the CF. In an Ignore, the OSs appearing in the CF are translated as usual. Each OS of any ignored Message is mapped to a boolean variable in the EU module on the Lifeline where it is located. An OS of the ignored Messages can be enabled if it has not executed and the control is in the EU module. To record the status of each ignored Message’s OS, an enumeration type variable \( os\_\text{chosen} \) is introduced, which is initially \(-1\). It is set to 0 if the OS is chosen to execute and is set to and stays \( f \) in the following steps. In each EU module of the Ignore,
the OSs of ignored Messages and other OSs are interleaved, which is captured by INV AR statements using the same strategy as the implementation of Parallel.
A Consider specifies a list of message types which should be considered within the CF. It is equivalent to ignore other message types, i.e., the message types not in the list cannot appear in the CF, but they may occur. If a message type is considered but does not appear in the CF, the Messages of the type cannot occur within the CF. For example, if a Consider CF considers message type q, v, and w, but only Messages of message type q and v appear in the CF. Thus, Messages of message type w cannot occur within the CF.
In a Consider, each OS of the considered Messages can be defined as a boolean variable in the EU module on the Lifeline where it is located. If the OS does not appear in the Consider, it is defined as a derived variable, whose value is False to indicate the OS will never occur. For other known but not considered Messages, their OSs are defined in the same way as the OSs of the ignored Messages.
We also provide the mapping of Interaction Use, Coregion, and General Ordering to the NuSMV modules. Due to space limitation, please refer to (Shen et al., 2011) for the details of translation.
5 TOOL SUITE
IMPLEMENTATION AND EVALUATION
As a proof-of-concept, we have developed a tool suite, implementing the techniques described in this paper. Figure 5 is a data flow diagram, illustrating the architecture of our tool suite.

The software engineer uses MagicDraw to create a Sequence Diagram, which can be converted to a textual representation in terms of XML using our MagicDraw plugin. The Sequence Diagram Translation tool takes the XML representation as input, parses it into a syntax tree, and transforms it into a NuSMV model. NuSMV model checker takes as input the generated NuSMV model and a temporal logic formula that is specified by the software engineer. If there are no property violations, the software engineer receives a positive response. If property violations exist, NuSMV generates a counterexample which is then passed to our Occurrence Specification Trace Diagram Generator (OSTDG) tool. The output from the OSTDG is an easy-to-read Sequence Diagram visualization of the counterexample to help the software engineer locate the property violation faster. Thus, the software engineer may transparently verify a Sequence Diagrams using NuSMV, staying solely within the notation realm of Sequence Diagrams.
We evaluate our technique with a case study of ISIS (Insurance Services Information System), a web application currently used by the specialty insurance industry. Our evaluation uses two Sequence Diagram examples from the design documentation of ISIS. We check the example on a Linux machine with a 3.00GHz, 8 cores, CPU and 32GB of RAM. One example executed in 19 minutes 49 seconds with 3,825 reachable states out of total 3.71e+012 states, while the other example executed in 18 minutes 14 seconds with 192 reachable states out of total 4.95e+012 states. Please refer to (Shen et al., 2011) for more details of the case study and our tool suite.
6 RELATED WORK
Verification of scenario-based notation is well-accepted as an important and challenging problem. To the best of our knowledge, our technique is the first to support all CFs and the nested CFs. Lima et al. provide a tool to translate UML 2 Sequence Diagrams into PROMELA-based models and verify using SPIN, with counterexample visualizations (Lima et al., 2009). Their translation does not support Critical Region, Strict Sequencing, Negative, Assertion, Consider, Ignore, synchronous Messages and Interaction Constraint. Van Amstel et al. present four complementary approaches for analyzing UML 1.5 Sequence Diagrams, which do not support CFs (Van Amstel et al., 2007). They model check Sequence Diagrams using SPIN. Alawneh et al. introduce a unified paradigm to verify and validate prominent UML 2 diagrams, including Sequence Diagrams, using NuSMV (Alawneh et al., 2006). Their approach supports Alternatives and Parallel.
To model check MSCs, Alur et al. (Alur and Yan-
nakakis, 1999; Alur et al., 2005) formalize MSC using automata. They examine different cases of MSC verification of temporal properties and present techniques for iteratively specifying requirements (Alur et al., 2003). They focus on MSC Graph, which is an aggregation of MSCs. We extend their work to encompass more complicated aggregations using CFs. Peled et al. perform intensive research on the verification of MSCs (Muscholl et al., 1998; Gunter et al., 2001), in particular, they present an extension of the High-Level MSC (Peled, 2000). They specify MSC properties in temporal logic and check for safety and liveness properties. Leue et al. translate the MSC specification, especially branching and iteration of High-Level MSC, into PROMELA to verify MSCs using the XSPIN tool (Leue and Ladkin, 1996). As Sequence Diagrams have similar expressive features, our technique can be extended to work with their approach. Kugler et al. improve the technique of smart play-out, which is used to model check LSCs to avoid violations over computations (Kugler et al., 2009). Walkinshaw and Bogdanov (Walkinshaw and Bogdanov, 2008) detail an inference technique to constrain a finite-state model with LTL. These constraints reduce the number of traces required as input to a model checker for discovery of safety counter examples. Our work can automatically model check each Sequence Diagram of a system against LTL properties separately, which helps to alleviate the state explosion problem.
Micskei and Waeselynck survey comprehensively formal semantics proposed for Sequence Diagrams by 13 groups and present the different semantic options (Micskei and Waeselynck, 2011). In these groups, Knapp and Wuttke present an operational semantics for a translation of an Interaction into automata, which is used to model check UML state machines with SPIN or UPPAAL (Knapp and Wuttke, 2006). Their approach does not support all CFs and the interpretation of automata restricts the specification of Interaction Constraints. Haugen et al. present the formal semantics of UML 2 Sequence Diagram through an approach named STAIRS (Haugen et al., 2005). STAIRS provides a trace-based representation for a subset of CFs, focusing on the refinement for Interactions. To relate state-based behaviors with scenario-based descriptions, Bontemps et al. formally study the problem of scenario checking, synthesis, and verification of the LSC (Bontemps et al., 2005). Their work focuses on providing an algorithm and proving the complexity for each problem. Uchitel et al. (Uchitel et al., 2003) synthesize a behavioral specification in the form of a Finite Sequential Process, which can be checked using their labeled transition system analyzer. With the semantic definition of Uchitel et al., Damas et al. synthesize a labeled transition system model from both positive and negative scenarios, expressed in MSC (Damas et al., 2005).
7 CONCLUSIONS
In this paper, we present an approach to transform Sequence Diagrams and all CFs into NuSMV models. This enables software engineers to verify if a Sequence Diagram satisfies desired properties and visualize counterexamples as Sequence Diagrams to help user locate violations. We supplement our technique with a proof-of-concept tool suite and perform an evaluation using a case study of an industry web application. We believe our approach can be adapted to model check MSCs and High-Level MSCs.
ACKNOWLEDGEMENTS
Jianwei Niu is supported in part by NSF award CNS-0964710.
REFERENCES
|
{"Source-Url": "http://www.scitepress.org/papers/2012/40768/40768.pdf", "len_cl100k_base": 9559, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 40588, "total-output-tokens": 11573, "length": "2e13", "weborganizer": {"__label__adult": 0.0003142356872558594, "__label__art_design": 0.0005550384521484375, "__label__crime_law": 0.0003294944763183594, "__label__education_jobs": 0.0011587142944335938, "__label__entertainment": 7.730722427368164e-05, "__label__fashion_beauty": 0.00015974044799804688, "__label__finance_business": 0.00028228759765625, "__label__food_dining": 0.00029087066650390625, "__label__games": 0.0006122589111328125, "__label__hardware": 0.00079345703125, "__label__health": 0.0004169940948486328, "__label__history": 0.00028967857360839844, "__label__home_hobbies": 0.00010055303573608398, "__label__industrial": 0.0005054473876953125, "__label__literature": 0.00029850006103515625, "__label__politics": 0.000247955322265625, "__label__religion": 0.0004477500915527344, "__label__science_tech": 0.050445556640625, "__label__social_life": 8.946657180786133e-05, "__label__software": 0.00820159912109375, "__label__software_dev": 0.93359375, "__label__sports_fitness": 0.00027680397033691406, "__label__transportation": 0.0005350112915039062, "__label__travel": 0.00019419193267822263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45085, 0.04222]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45085, 0.58175]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45085, 0.86675]], "google_gemma-3-12b-it_contains_pii": [[0, 4078, false], [4078, 7705, null], [7705, 11607, null], [11607, 16607, null], [16607, 21967, null], [21967, 26403, null], [26403, 28978, null], [28978, 33913, null], [33913, 38115, null], [38115, 43018, null], [43018, 45085, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4078, true], [4078, 7705, null], [7705, 11607, null], [11607, 16607, null], [16607, 21967, null], [21967, 26403, null], [26403, 28978, null], [28978, 33913, null], [33913, 38115, null], [38115, 43018, null], [43018, 45085, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45085, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45085, null]], "pdf_page_numbers": [[0, 4078, 1], [4078, 7705, 2], [7705, 11607, 3], [11607, 16607, 4], [16607, 21967, 5], [21967, 26403, 6], [26403, 28978, 7], [28978, 33913, 8], [33913, 38115, 9], [38115, 43018, 10], [43018, 45085, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45085, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
0144d63919ba7f74bb6976b29d001d743e42aa19
|
NumaMMA: NUMA MeMory Analyzer
François Trahay, Manuel Selva, Lionel Morel, Kevin Marquet
To cite this version:
HAL Id: cea-01854072
https://hal-cea.archives-ouvertes.fr/cea-01854072v2
Submitted on 14 Dec 2018
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
NumaMMA: NUMA MeMory Analyzer
François Trahay
SAMOVAR, CNRS, Télécom SudParis, Université Paris-Saclay
Evry, France
francois.trahay@telecom-sudparis.eu
Manuel Selva
Univ. Grenoble Alpes, CNRS, Inria, Grenoble INP, LIG
Grenoble, France
manuel.selva@inria.fr
Lionel Morel
Univ Grenoble Alpes, CEA, List
Grenoble, France
lionel.morel@cea.fr
Kevin Marquet
Univ Lyon, INSA Lyon, Inria, CITI
Villeurbanne, France
kevin.marquet@insa-lyon.fr
ABSTRACT
Non Uniform Memory Access (NUMA) architectures are nowadays common for running High-Performance Computing (HPC) applications. In such architectures, several distinct physical memories are assembled to create a single shared memory. Nevertheless, because there are several physical memories, access times to these memories are not uniform depending on the location of the core performing the memory request and on the location of the target memory. Hence, threads and data placement are crucial to efficiently exploit such architectures. To help in taking decision about this placement, profiling tools are needed. In this work, we propose NUMA MeMory Analyzer (NumaMMA), a new profiling tool for understanding the memory access patterns of HPC applications. NumaMMA combines efficient collection of memory traces using hardware mechanisms with original visualization means allowing to see how memory access patterns evolve over time. The information reported by NumaMMA allows to understand the nature of these access patterns inside each object allocated by the application. We show how NumaMMA can help understanding the memory patterns of several HPC applications in order to optimize them and get speedups up to 28% over the standard non optimized version.
CCS CONCEPTS
• General and reference → Performance; • Software and its engineering → Software performance;
KEYWORDS
Performance analysis, NUMA architectures, Data and threads placement, Memory sampling
1 INTRODUCTION
Because symmetric memory architectures do not scale up with the number of cores, modern multicore architectures have non-uniform memory access (NUMA) properties: a given core accesses some memory banks faster than other banks. Typically, one finds two levels of addressable memory: one core may access a local memory really fast, or access a remote memory via an interconnect at some extra cost in time. A set of cores together with its local memory is named a NUMA node.
From the programs’ perspective, this type of hardware requires to decide the locality of data and threads. Clearly, as many memory accesses as possible should be local to decrease there latency. But applications may comprise a large number of threads and many dependencies between threads. This is particularly true for High-Performance Computing (HPC) applications. It is often not possible to avoid remote memory accesses when threads are sharing data as it would be highly inefficient to execute all threads on the same core, or even on cores on the same NUMA node.
As the number of threads and the amount of shared data increases, deciding the placement of data and threads also requires to take into account contentions that may appear on shared resources. When such contentions occur, it has been shown that interleaving memory pages on all the NUMA nodes is an efficient solution [16].
Recent results also show that NUMA architectures are asymmetric [21]: accesses from a core on a node A to a bank on node B may have performances completely different from accesses from a core on node B to a bank on node A. Moreover, the documentation of processors actually lacks details about this kind of characteristics and the programmer is thus left with trying out different combinations and infer system-level performance characteristics for application.
NUMA architectures are very complex indeed and they differ very much from one another. They have different numbers of nodes, different memory latencies, bandwidths and sizes, different symmetry models. As programmers are not likely to know those architectural details, we cannot expect them to port applications from one architecture to another and take the full benefits of the new architecture in terms of performance. On the other hand, hardware platforms are generic and cannot be expected to take specific applications needs into account. Hence, tools should be provided to help the programmer decide the locality of data and threads.
In the context of HPC, most applications have similar memory access patterns from one execution to another. Thus, by analyzing the memory access pattern of an application, a developer can figure out how data and threads should be placed on a given NUMA system in order to maximize local memory access and to reduce the memory contention on the NUMA
nodes. Determining the memory access pattern of an application can be done by analyzing its source code. However, this task may be tedious for large applications, and it is hard to grasp the impact of each memory object on the performance: some objects are rarely accessed and improving their locality is worthless, while some objects are accessed often and their placement have a significant impact on the overall performance of an application. Thus, memory profiling tools are needed to help understanding these pattern, and to guide the decision of locality of data and threads.
In this paper, we propose NUMA MeMory Analyzer (NumaMMA), a tool allowing to understand in details the memory access patterns of an application. NumaMMA first uses hardware capabilities to gather a memory trace. This trace is then processed offline in order to assess the cost of memory accesses to every object of the application and to know how threads access different parts of these objects. Understanding memory access patterns inside objects is crucial in the context of HPC applications because they often only access to few very large objects a huge number of time. We then make the following contributions:
- we propose an open-source tool\(^1\) able to report how memory access patterns inside objects evolve over time;
- we combine this reporting with an efficient trace collection mechanism based on hardware sampling;
- we provide developers with original visualization means of these memory access patterns;
- we show that this information can be used for defining a placement strategy that improves the performance of applications by up to 28%.
The remainder of the paper is organized as follows. Section 2 details related work. Section 3 then explains the contributions we make. Section 4 evaluates experimentally NumaMMA. Section 5 concludes and gives perspectives on this work.
## 2 RELATED WORK
With the increasing number and complexity of NUMA machines, the placement of thread and data in these machines has gained strong focus in the last decades. When targeting NUMA machines, threads and data placement must first limit the number of remote memory accesses. Second, it must ensure there is no contention on shared resources such as the interconnect network allowing any core to access any memory bank. Threads and data placement is generally handled either explicitly by the programmer at the application level or automatically at runtime by the operating system potentialley with help from the compiler. To help the programmer understand the memory access patterns of applications and then optimize them, many profiling tools have been proposed.
We now quickly review runtime approaches before presenting in details existing NUMA profiling tools. For a complete survey of solutions that have been proposed for the threads and data placement problem, the reader should refer to the recent work of Diener et al. [14].
\(^1\)https://github.com/numamma/numamma
### 2.1 Runtime Placement
Runtime mechanisms for placing threads and data are required in contexts where applications are not known. In this case, the operating system [3, 9, 11, 12, 15, 18], or the runtime system between the operating system and applications [7, 8], is responsible for deciding where to allocate data in memory and on which core to execute which thread.
General purpose operating systems provides two main global policies regarding memory allocation. By default, Linux allocates all the memory pages of an application in the NUMA node where the first thread accessing it is running. This is the first-touch policy. Linux also offers the interleaved policy, where all the pages of an application are allocated in a round-robin fashion among all NUMA nodes. While being effective in some situations, these two global policies are not efficient at all for applications having complex memory access patterns. In particular, the memory access patterns of an application may not be the same for different objects and thus a global policy cannot be efficient. Also, these memory access patterns may evolve over time. As a result, the placement of a memory page may become misfit. The Solaris operating system offers the next-touch policy [3] that takes a memory page already allocated and migrates it in order to improve its locality with the thread that uses it. Integration of this next-touch policy into the Linux kernel has also been proposed [18, 20]. Starting from version 3.8 released in 2013, the Linux kernel also provides NUMA memory balancing [1]. This feature relies on periodically unmapping pages and later trapping a page fault to detect which thread access which memory.
Solutions have been proposed to improve the basic policies provided by standard operating systems. Several of the proposed solutions rely on hardware performance counters [8, 11, 15], or on custom hardware extensions [9] that are used to sample memory accesses. This sampling provides an insight about memory access patterns of the application. Based on this profiling information, pages and threads are then moved to increase memory locality and to avoid contention on the interconnect. Other solutions rely on the compiler providing information that can be used to infer memory access patterns before deciding where the data should be allocated [12]. Finally, some solutions rely on the knowledge of the affinity between OpenMP threads to improve the locality of threads and data: the threads that belong to the same OpenMP team are likely to access the same memory regions, and grouping them improves the locality [7].
All these solutions rely on runtime heuristics. The quantity of information that can be processed is thus limited so as to limit the overhead on the application’s performance. This is a major difference with our approach where profiling is performed offline: we can build much more precise performance metrics that can be used to take better placement decisions.
### 2.2 Offline Placement
Over the years, many works have focused on collecting memory traces in order to analyze them offline. These solutions differ in the way they collect memory access information, in
the way they process this information and in the way they use it ultimately.
2.2.1 Collecting Memory Traces. Multiple solutions have been proposed for collecting memory traces. Memory accesses can be captured by simulating the execution of an application [10]. However, the simulating time is prohibitive, which prevents from using this approach on most applications.
Another solution consists in instrumenting the application binary with tools like Pin [24] so that each instruction that reads or writes data is recorded [5, 13, 28, 30]. While the overhead caused by the instrumentation is reduced compared to the simulation approach, it still causes the application to run up to 20 times slower than the non-instrumented version. This prevents from using this solution on large applications.
A third approach is to leverage the memory sampling capabilities provided by the hardware. Modern processors implement hardware-based monitoring systems (such as Intel PEBS, or AMD IBS) that periodically save information about the instruction being executed. This mechanism can be used for collecting the memory addresses that are accessed [17, 19, 22, 23, 25–27, 31]. Since only some of the instructions are collected, this approach is less precise than instrumentation but more efficient. Also, the collection of a single sample is more efficient than instrumentation because it is done by the hardware. Collecting a sample with Intel PEBS only requires 200 to 300 nanoseconds [2]. The impact on the application performance is thus small. This approach is thus applicable on large applications. Also, compared to the approach based on binary instrumentation, hardware-based sampling allows to record the the level in the memory hierarchy (L1, L2, ...) that served an access along with the latency of the access.
2.2.2 Existing Tools for Thread and Data Placement. Molina da Cruz et al. propose an automatic placement tool [10]. This tool relies on simulation to trace all memory accesses. It then builds a complete graph representing the amount of communication between threads. A partitioning algorithm is then applied on the graph to know which threads should be put close together.
Song et al. proposed an automatic solution, for thread placement only, using binary instrumentation to collect traces [30]. Their solution also builds a graph representing the amount of communication between threads. It then applies a partitioning algorithm on this graph to decide where threads should be placed. Numalize [13] also relies on binary instrumentation to perform automatic threads and data placement. For threads placement, Numalize uses a graph representing the amount of communication between threads. Partitioning is done using that graph. For data placement, Numalize computes high level metrics at application level. Compared to other solutions, Numalize is the only one taking the time dimension into account. Said differently, Numalize computes threads and data placement for different execution phases of the application. Tabarnac [5] is another tool relying on binary instrumentation. Tabarnac offers visual representations allowing to inspect how threads access internal pages of large objects. These representations are global to the entire execution of the application, they do not include time information. RTHMS [28] uses binary instrumentation for collecting memory access patterns on objects on a machine whose memory is heterogeneous such as the Intel Knight Landing architecture. In such machines, objects are either allocated on the fast but small memory, or on the slow but large memory. RTHMS then analyzes the collected data in order to decide where to allocate the objects, based on their expected impact on performance computed from the number of accesses, the life span and the read/write frequency.
Because simulation and binary instrumentation have a huge impact on performance, many tools have been proposed that rely on hardware sampling mechanisms [17, 19, 22, 23, 25–27, 31]. The work by Marathe et al. [25, 26], targeting Intel Itanium architectures, proposes an automatic page placement that allocates pages on the NUMA node where they are most used or on the node that will minimize the total cost of all its accesses. Memphis [27] and MemProf [19], both targeting AMD processors, provide NUMA related information to the programmer in a data-centric view, that is using objects of the application. For each object in the application, they report the total number and costs of remote memory accesses. No information about the distribution of accesses inside an object is reported. MemAxes [17], one of the most advanced visualization tool for pinpointing NUMA effects, focuses on providing information related to the application along with standard metrics on memory accesses. This is done with the help of the programmer who must instrument her application to give information to the tool. Also, similarly to Memphis and MemProf, MemAxes does not provide any visual information about the distribution of accesses inside large objects. Finally, HPCToolkit [22, 23] also reports information about NUMA effects over the application. Its main contributions are global metrics allowing to identify whether or not changing the data placement could lead to performance benefits along with a data-centric reporting of memory accesses. HPCToolkit also reports some information about memory accesses inside large objects. Nevertheless, this information only contains the minimum and maximum addresses inside the object accessed by each thread.
3 NUMAMMA
In this section, we present NumaMMA, a memory profiler that captures the memory access pattern of threads on objects in memory. The approach consists in executing an application offline, retrieving useful information about memory accesses, and providing this information to the application developer. She can then use this information to optimize the placement of threads and data.
During the profiled execution of the application, NumaMMA collects information on the dynamic allocations as well as on global variables. NumaMMA uses the sampling features provided by the hardware to collect samples of the memory accesses performed by the application threads. Relying on hardware memory sampling allows to capture the application behavior without prohibitive overhead.
After the execution of the application, NumaMMA searches for the memory object accessed by each collected sample and computes statistics on each object. Once all the samples are processed, NumaMMA reports statistics on the memory objects most accessed by the application. These statistics can be used by the application developer in order to tune the placement of the threads and data.
In this section, we first describe how memory access samples are gathered. Second, we describe how information on memory objects is collected. Then, we describe how samples are matched with memory objects and which statistics are computed. Finally, we describe how NumaMMA reports information about memory accesses to the user.
3.1 Collecting Samples
Modern processors implement sampling mechanisms able to collect information on executed instructions with a low overhead. Intel provides Precise Event-Based Sampling (PEBS) while AMD provides Instruction Based Sampling (IBS). When sampling, the CPU periodically records information on the instruction that is being executed in a dedicated memory location and notifies the software through an interrupt. With PEBS, it is possible to configure the hardware to only sample memory reads and/or memory writes. To limit the overhead of the sampling, it is also possible with PEBS to collect several samples before notifying the software.
During the profiled execution of the application, NumaMMA uses numap [29] for collecting memory samples. Note that numap currently only supports Intel PEBS, but it could be extended to other sampling mechanisms such as AMD IBS. Also note that Intel micro architectures prior to Sandy Bridge (2011) only support the sampling of read accesses. The precision of the information gathered through sampling will thus depend on the profiling capabilities offered by the hardware platform used. Each memory sample is composed of:
- the type of the access, that is read or write;
- the identifier of the thread that executes the access;
- the time at which the sample has been taken;
- the address accessed by the instruction;
- which part of the memory hierarchy was accessed, that is L1/L2/L3 cache or local memory or memory located on a remote NUMA node;
- the cost of the memory access, that is the latency.
NumaMMA records samples in a dedicated memory buffer. When this buffer is full, the recording of samples is stopped. Thus, NumaMMA needs to collect and flush the sample buffer regularly so as not to lose samples. To that end, when the application calls an allocation function (such as malloc or free), NumaMMA stops recording samples, copies the collected samples to an other location that will be analyzed post-mortem, and resumes recording samples. However, samples may still be lost if the application does not call allocation functions regularly. To mitigate the loss of samples, NumaMMA can also set an alarm to periodically collect samples. The usage and impact of this parameter is discussed in Section 4.
3.2 Identifying Memory Objects
In order to find the memory object accessed by a sample, NumaMMA collects information on dynamic allocations as well as on static objects, that is global variables. For each memory object, NumaMMA stores the base address of the object and its size, the allocation timestamp, and the de-allocation timestamp. Memory objects are stored in a binary tree ordered by the object address.
Dynamic allocations are tracked by overloading the main memory allocation functions: malloc(), realloc(), calloc and free(). When the application allocates an object, NumaMMA intercepts the function call using the LD_PRELOAD mechanism, and stores information on the allocated objects. For dynamic objects, NumaMMA also collects information on the allocation call sites, that is the function and the line at which the object was allocated.
NumaMMA collects information on static objects at the application start up. It reads the list of symbols in the ELF file, and searches for global variables and the corresponding size and offset. NumaMMA then determines at which address the ELF file is loaded in order to compute the address of the variable in the current address space. This computing step is required for code compiled in a position independent way.
3.3 Processing Samples
After the execution of the application, the collected samples are processed in order to identify the memory object corresponding to each sample. To do so, NumaMMA browses the binary tree that contains the memory objects and searches for an object whose address range includes the address reported in the sample.
Because of the dynamic allocation, several memory objects may match an address. This happens when the application allocates with malloc an object o1, free it, and allocates another object o2. In this case, malloc may allocate o2 at the same address addr as o1. Thus, when searching for the object that corresponds to address addr, NumaMMA will identify both o1 and o2. Thus, NumaMMA also compares the timestamp of the sample with the allocation and free dates for o1 and o2. Also, this implies that nodes of the binary tree recording memory objects are lists of objects (all allocated at the same address) and not a single object.
Once the memory object that matches a sample is identified, NumaMMA updates the following counters associated to the object:
- the number of read/write accesses;
- the number of read/write accesses to/from a remote NUMA node;
- the total read/write accesses cost.
These counters are computed both globally and in a per-thread basis. Since multiple threads may access different portions of a single object, and we are particularly interested in understanding how, NumaMMA also computes these counters for each memory page, 4 KiB by default or 2 MiB when using huge pages.
3.4 Reporting Memory Access Information
After all the samples are processed, NumaMMA outputs several results. All the outputs of NumaMMA can be either global, that is including read and write accesses, or specific to read or to write accesses. First, NumaMMA prints the list of memory objects along with their accumulated counters. By default, the list is sorted by the total number of accesses, but this can be changed to sort by the total memory cost. Also, NumaMMA groups in this list the objects that have been allocated at the same call site. There counters are summed and they are reported as a single object. This choice is motivated by the fact that changing the allocation at the callsite line will change the placement of all the objects allocated at this callsite. This list of objects provides application developers with useful information on which objects are the most likely to affect the performance of the application.
For each object, NumaMMA textually reports the number of detected memory accesses per page and per thread. This information can also be reported in a graphical way using a communication matrix, as shown in Figure 1. This matrix shows which thread accesses to which memory page. The color indicates the number of accesses. In this example, thread #0 mainly accesses pages from 0 to 1000 and from 4200 to 5100, while thread #1 mostly access pages 1000 to 1800 and from 5100 to 6000. From this graph it is clear that threads only access specific sub-parts of the main_flt_mem object. Using this information, we may decide to place the threads that work on the same memory pages on the same NUMA node. Memory pages could also be bound to NUMA nodes according to the thread access pattern.
NumaMMA also textually reports, for each object, the list of samples that were matched with the object. This provides more detailed information on an object, including the time dimension. Figure 2 shows how NumaMMA can report this information graphically. This plot shows the memory accesses of the threads during the execution of the application. The horizontal axis represents the time and the vertical one represents the offset in the memory object. Each point corresponds to a single memory access sample, and the color represents the thread accessing the object. By adding a temporal dimension, this view completes the information provided by the one shown in Figure 1. We clearly see that the two different sub-parts of the main_flt_mem object accessed by each thread are accessed in different stages of the application. If for any reason, the upper part of the data is allocated on a different NUMA node that the lower part, then we can use the timing information to migrate the four threads on the node where the upper part is just before starting the second execution stage.
4 EVALUATION
In this section, we evaluate and show how NumaMMA can help understanding memory access patterns to improve performance. We demonstrate this on applications from the NAS Parallel Benchmarks and on Streamcluster from PARSEC. We used two NUMA machines:
- Intel32 has 2 Intel Xeon E5-2630 v3 processors with 8 cores/16 threads in each (total: 16 cores/32 threads), running at 2.4GHz. The machine is equipped with 2 NUMA nodes connected through QPI and 32GB of RAM. It runs Linux 4.11, glibc version 2.24, and GCC 6.3;
- Amd48 has 4 AMD Opteron 6174 processors with 12 cores in each (total: 48 cores) running at 2.2GHz. The machine is equipped with 8 NUMA nodes (2 nodes per processor) connected through HyperTransport 3.0, and 128GB of RAM. It runs Linux 4.10, glibc version 2.25, and GCC 6.3.
The applications were compiled with the –O3 flag and were not stripped so that NumaMMA can find the list of global variables in the application. The NAS Parallel Benchmarks use the GNU OpenMP shipped with GCC 6.3. Streamcluster was compiled with the –g flag so that NumaMMA can identify the file and line of each memory object using the debugging information.
4.1 NAS Parallel Benchmarks
The NAS Parallel Benchmarks (NPB) [4] is a suite of HPC kernels. We run the OpenMP implementation of NPB 3.3, class C, on the Intel32 machine.
4.1.1 NumaMMA Overhead. We first run NPB kernels with and without NumaMMA in order to assess the overhead of NumaMMA. The NAS kernels are executed with 32 threads...
and we use hwloc [6] and GOMP_CPU_AFFINITY so that consecutive threads are located close to each other in the machine topology. We run the kernels with two different settings:
- **NumaMMA_2k**: sampling rate of 2000. We record a memory sample every 2000 memory accesses, and the alarm system is disabled, that is samples are collected when the application calls an allocation function;
- **NumaMMA_10k**: sampling rate of 10000, and alarm period of 100 milliseconds, that is samples are collected when the application calls an allocation function and every 100 milliseconds. The collection on the alarm is done in every cases, independently of the number of calls to allocation functions.
To evaluate the overhead of NumaMMA on the application run time, we compare the execution time of NAS Parallel Benchmark kernels when run with and without NumaMMA. The results of this experiment are reported in Table 1. The results show that NumaMMA has little effect on three kernels (LU, IS, SP). Two kernels (UA and MG) are more affected by NumaMMA. Nevertheless the overhead is less than 12% in all cases. This remains low compared to other techniques that rely on software mechanisms such as dynamic binary translation to track memory accesses [5, 13, 30] or simulation [10]. This maximum overhead of 12% is not prohibitive as it only affect the debugging phase of the application development.
The overhead has three main causes:
- the overhead of sampling instructions which is influenced by the sampling rate;
- the cost of copying samples which is influenced by the number of collected samples and thus by the sampling rate;
- the overhead of intercepting dynamic allocation calls which is influenced by the number of memory allocations.
The two first causes of overhead are closely related. More samples will be copied if the sampling rate is high. Also, the overhead resulting from these two causes is proportional to the number of memory access instructions performed by the application compared to the total number of instructions. The overhead of intercepting dynamic allocation is not significant in the NPB kernels because there are very few such allocations.
### 4.1.2 **NumaMMA Accuracy**
Table 2 reports the number of samples that were collected by NumaMMA, as well as the number of samples that correspond to an address on the stack when run with **NumaMMA_2k**. The results show that **NumaMMA_10k** collects millions of samples, while **NumaMMA_2k** captures up to a million samples. This difference is caused by their respective configuration. In **NumaMMA_2k**, the CPUs

<table>
<thead>
<tr>
<th>Kernel</th>
<th>NumaMMA_2k</th>
<th>NumaMMA_10k</th>
</tr>
</thead>
<tbody>
<tr>
<td>time(s)</td>
<td>time(s)</td>
<td>ovhd(%)</td>
</tr>
<tr>
<td>BT.C</td>
<td>81.3</td>
<td>82.3</td>
</tr>
<tr>
<td>CG.C</td>
<td>21.6</td>
<td>23.3</td>
</tr>
<tr>
<td>EPC</td>
<td>10</td>
<td>10.5</td>
</tr>
<tr>
<td>FT.C</td>
<td>19.6</td>
<td>20.2</td>
</tr>
<tr>
<td>IS.C</td>
<td>1.5</td>
<td>1.48</td>
</tr>
<tr>
<td>LU.C</td>
<td>61.8</td>
<td>58</td>
</tr>
<tr>
<td>MG.C</td>
<td>10.4</td>
<td>11.3</td>
</tr>
<tr>
<td>SPC</td>
<td>168.6</td>
<td>169.8</td>
</tr>
<tr>
<td>UAC</td>
<td>86.6</td>
<td>93.5</td>
</tr>
</tbody>
</table>
**Table 1**: Overhead of NumaMMA, depending on sampling frequency, on NPB kernels class C. The overhead is below 12% in all cases.
<table>
<thead>
<tr>
<th>Kernel</th>
<th>NumaMMA_10k</th>
<th>NumaMMA_2k</th>
</tr>
</thead>
<tbody>
<tr>
<td>nsamples (million)</td>
<td>nsamples (million)</td>
<td>nstack (million)</td>
</tr>
<tr>
<td>BT.C</td>
<td>172</td>
<td>0.7</td>
</tr>
<tr>
<td>CG.C</td>
<td>41</td>
<td>0.7</td>
</tr>
<tr>
<td>EPC</td>
<td>19</td>
<td>0.6</td>
</tr>
<tr>
<td>FT.C</td>
<td>39</td>
<td>0.5</td>
</tr>
<tr>
<td>IS.C</td>
<td>3</td>
<td>0.18</td>
</tr>
<tr>
<td>LU.C</td>
<td>110</td>
<td>0.65</td>
</tr>
<tr>
<td>MG.C</td>
<td>22</td>
<td>0.8</td>
</tr>
<tr>
<td>SPC</td>
<td>334</td>
<td>0.5</td>
</tr>
<tr>
<td>UAC</td>
<td>171</td>
<td>0.6</td>
</tr>
</tbody>
</table>
**Table 2**: Number of samples collected on NPB. **NumaMMA_2k** gives a “high definition” partial view of the application memory access pattern while **NumaMMA_10k** gives a “low definition” complete view of the application memory access patterns.
capture samples frequently, and the sample buffer quickly becomes full. When this happens, the sampling of memory accesses is stopped. Thus, NumaMMA 2k gives a “high definition” partial view of the application memory access patterns. We could have used a sampling rate of 2000 along with an alarm to have a complete high definition view of the application at the price of an higher overhead. Nevertheless, as shown in the next section, we are able to understand LU patterns and then optimize it using NumaMMA 2k. NumaMMA 10k is configured to capture samples less often, but the alarm every 100 ms empties the sample buffer frequently to reduce the number of lost samples. This gives a “low definition” complete view of the application memory access patterns.
The results reported in Table 2 also show that a part of the collected samples correspond to memory addresses on the stack of the application threads. For these stack accesses, nothing should be done because the default operating system first touch policy ensures local accesses. Kernels making mostly stack accesses, EP and IS, could not benefit from memory optimization while all the others may be optimized.
4.1.3 Analysis And Optimization of LU. Based on the data collected with NumaMMA 2k, NumaMMA identifies that LU threads access mainly three objects:
- **cvar** which size is 558 MiB and which represents 58% of the samples;
- **cexact** which size is 520 bytes and which represents 23% of the samples;
- **cjac** which size is 20 MiB and which represents 10% of the samples.
cexact is a small object with a size smaller than one pages for which NumaMMA reports accesses that are randomly distributed across all the threads. We conclude that little can be done to improve the allocation strategy for this object.
Regarding cvar and cjac, these are composed of many memory pages. We now use NumaMMA graphical representations to observe and try to understand how threads access these two objects. The access patterns of cvar and cjac are reported respectively in Figure 3 and Figure 4. These figures report the access patterns over a short period of time compared to the total execution time of the kernel. Figure 3 represents 0.88% of the total execution time (58 seconds) while Figure 4 represents 0.1%. The reported patterns are repeated over all the iterations of the application and the figures are thus sufficient to understand the memory behavior of the whole. In Figure 3 we clearly see patterns evolving over time while the access behavior is constant in Figure 4. The main characteristic of all the patterns for both objects is the presence of colored horizontal lines. We also notice that the color order of these lines corresponds to the order of thread identifiers and that it is repeated several time. This means that threads are accessing only sub-parts of the cvar and cjac objects in a cyclic fashion. Because the height of the observed cycles are different for the two objects, it suggests that the optimal memory placement policy is different for the two variables:
- for cvar the placement must take into consideration the fact that the memory accesses are uniformly distributed to all threads on blocks of 160 MiB;
- for cjac the placement must take into consideration the fact that the memory accesses are uniformly distributed to all threads on blocks of 5 MiB.
To assess the effect of memory placement in LU, we run the application on AmpaB and we apply several binding policies for cvar and cjac. Since cvar and cjac are global variables, NUMA allocation functions cannot be used. Thus, we create a library that loads at the application startup and applies binding policies using mbind. In the following, a block distribution of size N MiB means that pages are allocated by blocks of N MiB. The pages of the first N MiB are allocated on the first NUMA node, the ones of the second N MiB on the second node, etc. When the last node has been reached, the block distribution starts again from the first node.
We implemented 4 allocation policies for the cvar and cjac objects:
- **first-touch**: the pages of the two objects are allocated with Linux default first-touch policy;
- **interleaved**: the pages of the two objects are allocated to all the NUMA nodes in an interleaved fashion;
- **block-native**: the pages of the two objects are allocated to all the NUMA nodes using a block distribution which size is the object size divided by the number of NUMA nodes, that is 8 in our case. This policy naively relies on the assumption that the work will be distributed among
The pages of all other objects are allocated according to the beginning of each iteration.
<table>
<thead>
<tr>
<th>policy</th>
<th>execution time(s)</th>
<th>speedup</th>
</tr>
</thead>
<tbody>
<tr>
<td>first-touch</td>
<td>102.53</td>
<td>1</td>
</tr>
<tr>
<td>interleaved</td>
<td>106.86</td>
<td>0.96</td>
</tr>
<tr>
<td>block-naive</td>
<td>109.88</td>
<td>0.93</td>
</tr>
<tr>
<td>NumaMMA</td>
<td>81.05</td>
<td>1.27</td>
</tr>
</tbody>
</table>
Table 3: Performance improvement on NPB LU. By allocating cvar and cjac in the way suggested by NumaMMA, we have a speedup of 27% over Linux default first-touch policy.
threads with the biggest possible blocks, such as in an OpenMP loop with static scheduling;
- NumaMMA: the pages of cvar and cjac are allocated according to the objects access patterns as identified previously. cvar pages are allocated with a 20 MiB block distribution such that the 160 MiB blocks are spread over the 8 NUMA nodes. For cjac we use a 2 MiB block distribution. Ideally, the 5 MiB blocks would be spread over the 8 NUMA nodes leading to a block size of 0.625 MiB, but due to the use of huge pages, the granularity for data placement is 2 MiB.
The pages of all other objects are allocated according to the first-touch policy used by default by the operating system.
The results we obtained on LU are reported in Table 3. The NumaMMA enabled policy results in a significant 27% gain while the classic interleaved as well as the naive block distribution slow the kernel down.
It is worth mentioning that while NumaMMA is not yet available for AMD architectures, we have been able to use it to optimize the LU kernel on the AMD48 machine by profiling it on the 1x1x32 machine. This has been made possible because of the way NPB kernels are implemented. In these OpenMP kernels, the loops that process the objects such as cvar and cjac are evenly distributed over the OpenMP threads. This means that the pattern observed for a particular number threads can be extrapolated to another number of threads.
4.2 Streamcluster
Streamcluster is a parallel application from the PARSEC benchmark suite. We run this application on the 1x1x32 machine with NumaMMA with a sample rate of 2000 and the alarm mechanism disabled. The total runtime of this profiled execution of the application is 125 seconds. NumaMMA collects 115.7 million samples, including 102.1 million (88%) on the stack and 13.6 millions (12%) on global and dynamically allocated objects and dynamically allocated ones. NumaMMA reports that two objects, both dynamically allocated with malloc, are mainly accessed:
- block which size is 98 MiB and representing 66% of the samples on global and dynamically allocated objects;
- points which size is 6 MiB and representing 31% of the samples on global and dynamically allocated objects.
Figures 5 and 6 depict the detected access patterns for block and points as reported by NumaMMA. The block variable is accessed randomly by all the threads. The access pattern for
The optimization consists in allocating the application objects as low as possible, and thus we must focus on long phases only. The evaluation shows that the overhead caused by NumaMMA is low. The experiments also show that the memory access information collected by NumaMMA can be used for improving the allocation strategy of several applications from the NAS Parallel Benchmark and the Streamcluster benchmark. The optimization consists in allocating the application objects impacting performances, that is the most accessed ones, according to their access patterns as reported by NumaMMA. As a result, the optimized applications perform significantly better than the original ones.
We are already working on several extensions to NumaMMA. First, we want to provide an automatic way of computing the best memory allocation policy for any object. This includes computing automatically the size of the distribution of objects for which a block-distribution should be made. Second, we are planning to use the timing information provided by NumaMMA to implement runtime mechanisms allowing to dynamically adapt memory placement according to the application phases. Because moving pages at runtime is expensive, the number of such dynamic adaptations should be made as low as possible, and thus we must focus on long phases only.
Table 4: Performance improvement on Streamcluster. By allocating block and points in the way suggested by NumaMMA, we have a speedup of 28% over Linux default first-touch policy. This 28% speedup is better than the 22% one of the interleaved policy.
<table>
<thead>
<tr>
<th>policy</th>
<th>execution time(s)</th>
<th>speedup</th>
</tr>
</thead>
<tbody>
<tr>
<td>first-touch</td>
<td>93.72</td>
<td>1</td>
</tr>
<tr>
<td>interleaved</td>
<td>76.76</td>
<td>1.22</td>
</tr>
<tr>
<td>block-naive</td>
<td>79.75</td>
<td>1.17</td>
</tr>
<tr>
<td>NumaMMA</td>
<td>73.32</td>
<td>1.28</td>
</tr>
</tbody>
</table>
The results of this evaluation are reported in Table 4. While using a single policy (block or interleaved) for both objects improves the performance, the best performance is obtained when using the most appropriate policy for each object as inferred using NumaMMA. In this case we have a speedup of 28% which is better than the 22% one obtained with the interleaved policy. Again, for the same reasons than for LU described above, we have been able to optimize Streamcluster on the AMD48 machine by profiling it on the Intel32 machine.
5 CONCLUSION AND FUTURE WORK
We have presented NumaMMA, a new memory profiler allowing to understand the evolution of memory access patterns inside objects allocated by applications. Compared to all existing offline profiling solutions presented in Section 2, NumaMMA is the first open-source software combining efficient trace collection using hardware sampling with the reporting of information at the page level to understand the distribution of memory accesses inside each object of the application. Also, NumaMMA provides original visualization means allowing to see how memory access patterns evolve over time.
Third, we are also working on the integration of the cost information of memory accesses, that is the latency, into the visual representations provided by NumaMMA. Finally, we started to work on the automatic implementation of the memory policies suggested by NumaMMA such that the programmer does not have to modify its application by hand.
ACKNOWLEDGEMENTS
This work was supported by the Paris Ile-de-France Region.
REFERENCES
|
{"Source-Url": "https://hal-cea.archives-ouvertes.fr/cea-01854072/document", "len_cl100k_base": 9601, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 42911, "total-output-tokens": 12766, "length": "2e13", "weborganizer": {"__label__adult": 0.0004127025604248047, "__label__art_design": 0.0005640983581542969, "__label__crime_law": 0.00039505958557128906, "__label__education_jobs": 0.000682830810546875, "__label__entertainment": 0.00016009807586669922, "__label__fashion_beauty": 0.0002143383026123047, "__label__finance_business": 0.0002887248992919922, "__label__food_dining": 0.00038504600524902344, "__label__games": 0.0010318756103515625, "__label__hardware": 0.0070648193359375, "__label__health": 0.0005693435668945312, "__label__history": 0.0006031990051269531, "__label__home_hobbies": 0.00015604496002197266, "__label__industrial": 0.000919342041015625, "__label__literature": 0.00028395652770996094, "__label__politics": 0.0004277229309082031, "__label__religion": 0.0007562637329101562, "__label__science_tech": 0.3857421875, "__label__social_life": 9.54270362854004e-05, "__label__software": 0.01416015625, "__label__software_dev": 0.58349609375, "__label__sports_fitness": 0.0003941059112548828, "__label__transportation": 0.000926494598388672, "__label__travel": 0.0002646446228027344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 51789, 0.04506]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 51789, 0.39851]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 51789, 0.89803]], "google_gemma-3-12b-it_contains_pii": [[0, 994, false], [994, 5744, null], [5744, 11910, null], [11910, 18261, null], [18261, 24069, null], [24069, 28384, null], [28384, 33123, null], [33123, 37695, null], [37695, 40623, null], [40623, 43640, null], [43640, 51789, null]], "google_gemma-3-12b-it_is_public_document": [[0, 994, true], [994, 5744, null], [5744, 11910, null], [11910, 18261, null], [18261, 24069, null], [24069, 28384, null], [28384, 33123, null], [33123, 37695, null], [37695, 40623, null], [40623, 43640, null], [43640, 51789, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 51789, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 51789, null]], "pdf_page_numbers": [[0, 994, 1], [994, 5744, 2], [5744, 11910, 3], [11910, 18261, 4], [18261, 24069, 5], [24069, 28384, 6], [28384, 33123, 7], [33123, 37695, 8], [37695, 40623, 9], [40623, 43640, 10], [43640, 51789, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 51789, 0.1629]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
b0fbbfe6c126c47426df1848281483828793e9df
|
An Empirical Study of Client-Side JavaScript Bugs
Frolin S. Ocariza, Jr., Kartik Bajaj, Karthik Pattabiraman, Ali Mesbah
University of British Columbia
Vancouver, BC, Canada
{frolino, kbajaj, karthikp, amesbah}@ece.ubc.ca
Abstract—Context: Client-side JavaScript is widely used in web applications to improve user-interactivity and minimize client-server communications. Unfortunately, web applications are prone to JavaScript faults. While prior studies have demonstrated the prevalence of these faults, no attempts have been made to determine their root causes and consequences.
Objective: The goal of our study is to understand the root causes and impact of JavaScript faults and how the results can impact JavaScript programmers, testers and tool developers.
Method: We perform an empirical study of 317 bug reports from 12 bug repositories. The bug reports are thoroughly examined to classify and extract information about the fault’s cause (the error) and consequence (the failure and impact).
Result: The majority (65%) of JavaScript faults are DOM-related, meaning they are caused by faulty interactions of the JavaScript code with the Document Object Model (DOM). Further, 50% of the highest impact JavaScript faults are DOM-related. Finally, most JavaScript faults originate from programmer mistakes committed in the JavaScript code itself, as opposed to other web application components such as the server-side or HTML code.
Conclusion: Given the prevalence of DOM-related faults, JavaScript programmers need development tools that can help them reason about the DOM. Also, testers should prioritize detection of DOM-related faults as most high impact faults belong to this category. Finally, developers can use the error patterns we found to design more powerful static analysis tools for JavaScript.
Index Terms—JavaScript, Document Object Model (DOM), empirical study
I. INTRODUCTION
Web developers often rely on JavaScript to enhance the interactivity of a web application. For instance, JavaScript is used to assign event handlers to different web application components, such as buttons, links, and input boxes, effectively defining the functionality of the web application when the user interacts with its components. In addition, JavaScript can be used to send HTTP requests to the server, and update the web page’s contents with the resulting response.
Client-side JavaScript contains several features that set it apart from other traditional languages. First of all, JavaScript code executes under an asynchronous model. This allows event handlers to execute on demand, as the user interacts with the web application components. Secondly, much of JavaScript is designed to interact with an external entity known as the Document Object Model (DOM). This entity is a dynamic tree-like structure that includes the components in the web application and how they are organized. Using DOM API calls, JavaScript can be used to access or manipulate the components stored in the DOM, thereby allowing the web page to change without requiring a page reload.
While the above features allow web applications to be highly interactive, they also introduce additional avenues for faults in the JavaScript code. In a previous study [1], we collected JavaScript console messages from fifty popular web applications to understand how prone web applications are to JavaScript faults and what kinds of JavaScript faults appear in these applications. We found that an average of four JavaScript console messages appear even in popular production web applications, and that most JavaScript console messages fall under five different categories. While the study pointed to the prevalence of JavaScript faults, it did not explore their impact or root cause, nor did it analyze the type of failures they caused. Understanding the root cause and impact of the faults is vital for developers, testers, as well as static and dynamic analysis tool builders to increase the reliability of web applications.
In this study, our goal is to discover the causes of JavaScript faults (the error) in web applications, and analyze their consequences (the failure and impact). Towards this goal, we conduct an empirical study of over 300 publicly available JavaScript bug reports. We choose bug reports as they typically have detailed information about a JavaScript fault and also reveal how a web application is expected to behave; this is information that would be difficult to extract from JavaScript console messages or static analysis. Further, we confine our search to bug reports that are marked “fixed”, which further eliminates spurious or superfluous bug reports.
A major challenge with studying bug reports, however, is that few web applications make their bug repositories publicly available. Even those that do, often classify the reports in ad-hoc ways, which makes it challenging to extract the relevant details from the report [2].
Our work makes the following main contributions:
• We collect and systematically categorize a total of 317 bug reports, from eight web applications and four JavaScript libraries;
• We categorize the JavaScript faults into multiple classes. We find that one class dominates the others, namely DOM-related JavaScript faults (more details below);
• We quantitatively analyze the nature (i.e., cause and consequences) and the impact of JavaScript faults; and
• We analyze the implications of the results on developers, testers, and tool developers for JavaScript code.
Our results show that around 65% of JavaScript faults are DOM-related faults, which occur as a result of a faulty interaction between the JavaScript code and the DOM. A
simple example is the retrieval of a DOM element using an incorrect ID, which can lead to a null exception. Further, we find that DOM-related faults account for about 80% of the highest impact faults in the web application. Finally, we find that the majority of faults arise due to the JavaScript code rather than server-side code/HTML, and that there are few recurring programming patterns that lead to these bugs.
II. BACKGROUND AND MOTIVATION
This section provides background information on the structure of modern web applications, and how JavaScript is used in such applications. We also define terms used throughout this paper such as JavaScript error, fault, failure, and impact. Finally, we describe the goal and motivation of our study.
A. Web Applications
Modern web applications – commonly known as Web 2.0 applications – contain three client-side components: (1) HTML code, which defines the webpage’s initial elements and its structure; (2) CSS code, which defines these elements’ initial styles; and (3) JavaScript code, which defines client-side functionality in the web application. These client-side components can either be written manually by the programmer, or generated automatically by the server-side (e.g., PHP) code.
The Document Object Model (DOM) is a dynamic tree data structure that defines the elements in the web application, their properties including their styling information, and how the elements are structured. Initially, the DOM contains the elements defined in the HTML code, and these elements are assigned the styling information defined in the CSS code. However, JavaScript can be used to manipulate this initial state of the DOM through the use of DOM API calls. For example, an element in the DOM can be accessed through its ID by calling the getElementsByTagName() method. The attributes of this retrieved DOM element can then be modified using the setAttribute() method. In addition, elements can be added to or removed from the DOM by the JavaScript code.
In general, a JavaScript method or property that retrieves elements or attributes from the DOM is called a DOM access method/property. Examples of these methods/properties include getElementsByTagName(), getElementsByTagName(), and parentNode. Similarly, a JavaScript method or property that is used to update values in the DOM (e.g., its structure, its elements’ properties, etc.) is called a DOM update method/property. Examples include setAttribute(), innerHTML, and replaceChild(). Together, the access and update methods/properties constitute the DOM API.
B. JavaScript Bugs
JavaScript is particularly prone to faults, as it is a weakly typed language, which makes the language flexible but also opens the possibility for untyped variables to be (mis)used in important operations. In addition, JavaScript code can be dynamically created during execution (e.g., by using eval).
\(^1\)JavaScript is a scripting language based on the ECMAScript standard, and it is used in other applications such as desktop widgets and even web servers.
Further, JavaScript code interacts extensively with the DOM, which can lead to faults that are only detected at runtime. Further, JavaScript code interacts extensively with the DOM, which makes it challenging to test/debug, and this leads to many faults as we find in our study.
JavaScript Bug Sequence. The following sequence describes the progression of a JavaScript bug, and the terms we use to describe this sequence:
1) The programmer makes a mistake at some point in the code being written or generated. These errors can range from simple mistakes such as typographical errors or syntax errors, to more complicated mistakes such as errors in logic or semantics. The error can be committed in the JavaScript code, or in other locations such as the HTML code or server-side code (e.g., PHP).
2) The error can propagate, for instance, into a JavaScript variable, the parameter or assignment value of a JavaScript method or property, or the return value of a JavaScript method during JavaScript code execution. Hence, by this point, the error has propagated into a fault.
3) The fault either directly causes a JavaScript exception (code-terminating failure) or a corruption in the output (output-related failure). This is called the failure.
Figure 1 shows a real-world example of the error, fault, and failure associated with a JavaScript bug report from the Moodle web application. Note that for output-related failures, the pertinent output can be one or a combination of many things, including the DOM, server data, or important JavaScript variables. We will be using the above error-fault-failure model to classify JavaScript bugs, as described in Section III.
If a JavaScript error propagates into the parameter of a DOM access/update method or to the assignment value for a DOM access/update property – thereby causing an incorrect retrieval or an incorrect update of a DOM element – then the error is said to have propagated into a DOM-related fault.
For example, if an error eventually causes the parameter of the DOM access method `getElementById()` to represent a nonexistent ID, and this method is called during execution with the erroneous parameter, then the error has propagated into a DOM-related fault. However, if the error does not propagate into a DOM access/update method/property, the error is considered to have propagated into a non-DOM-related fault.
**Severity.** While the appearance of a failure is clear-cut and mostly objective (i.e., either an exception is thrown or not; either an output contains a correct value or not), the severity of the failure is subjective, and depends on the context in which the web application is being used. For example, an exception may be tolerable and non-severe if it happens in a “news ticker” web application widget; but if the news ticker is used for something important – say, stocks data – the same exception may now be classified as severe. In this paper, we will refer to the severity as the impact of the failure.
**C. Goal and Motivation**
Our overall goal in this work is to understand the sources and the impact of JavaScript faults in web applications. To this end, we conduct an empirical study of JavaScript bug reports in deployed web applications. There are several factors that motivated us to pursue this goal. First, understanding the root cause of JavaScript faults could help make developers aware of programming pitfalls to be avoided, and the results could pave the way for better JavaScript debugging techniques. Second, analyzing the impact could steer developers’ and testers’ attention towards the highest impact faults, thereby allowing these faults to be detected early. Finally, we have reason to believe that JavaScript faults’ root causes and impacts differ from those of traditional languages because of JavaScript’s permissive nature and its many distinctive features (e.g., event-driven model; interaction with the DOM; dynamic code creation; etc.)
Other work has studied JavaScript faults through console messages or through static analysis [3], [4], [5], [6]. However, bug reports contain detailed information about the root cause of the faults and the intended behaviour of the application, which is missing in these techniques. Further, they typically contain the fix associated with the fault, which is useful in further understanding it.
**III. EXPERIMENTAL METHODOLOGY**
We describe our methodology for the empirical study on JavaScript faults. First, we enumerate the research questions that we want to answer. Then we describe the web applications we study and how we collected their bug reports. All our collected empirical data is available for download.²
**A. Research Questions**
To achieve our goal, we address the following research questions through our bug report study:
²http://ece.abc.ca/~frolino/projects/js-bugs-study/
**RQ1:** What types of faults exist among reported JavaScript faults, and how prevalent are these fault types?
**RQ2:** What is the nature of failures stemming from JavaScript faults? What is the impact of the failures on the web applications?
**RQ3:** What is the root-cause of JavaScript faults? Are there specific programming practices that lead to JavaScript faults?
**RQ4:** Do JavaScript faults exhibit browser-specific behaviour?
**RQ5:** How long does it take programmers to triage a JavaScript fault reported in a bug report to a developer? How long does it take programmers to fix these JavaScript faults?
**B. Experimental Objects**
To ensure representativeness, we collect and categorize bug reports from a wide variety of web applications and libraries. Each object is classified as either a web application or a JavaScript library. We made this distinction to see if there are any differences between JavaScript faults in web applications and those in libraries; we did not, however, find any substantial differences after performing our analysis. In total, we collected and analyzed 317 bug reports from 8 web applications and 4 libraries.
Table I lists the range of the software versions considered for each experimental object. The web applications and libraries were chosen based on several factors, including their popularity, their prominent use of client-side JavaScript, and the descriptiveness of their bug reports (i.e., the more information its bug reports convey, the better). Another contributing factor is the availability of a bug repository for the web application or library, as such repositories were not always made public. In fact, finding web applications and libraries that satisfied these criteria was a major challenge in this study.
**C. Collecting the Bug Reports**
For each web application bug repository, we collect a total of \{30, NumJSReports\} JavaScript bug reports, where NumJSReports is the total number of JavaScript bug reports in the repository. We chose 30 as the maximum threshold for each repository to balance analysis time with representativeness. To collect the bug reports for each repository, we perform the following steps:
**Step 1** Use the filter/search tool available in the bug repository to narrow down the list of bug reports. The filters and search keywords used in each bug repository are listed in Table 1. In general, where appropriate, we used “javascript” and “js” as keywords to narrow down the list of bug reports (in some bug repositories, the keyword “jQuery” was also used to narrow down the list even further). Further, to reduce spurious or superfluous reports, we only considered bug reports with resolution “fixed”, and type “bug” or “defect” (i.e., bug reports marked as “enhancements” were neglected). Table I also lists the number of search results after applying the filters in each bug repository. The bug report repositories were examined between January 30, 2013 and March 13, 2013.
**TABLE I**
**Experimental objects from which bug reports were collected.**
<table>
<thead>
<tr>
<th>Application</th>
<th>Version Range</th>
<th>Type</th>
<th>Description</th>
<th>Size of JS Code (KB)</th>
<th>Bug Report Search Filter</th>
<th># of Reports Collected</th>
</tr>
</thead>
<tbody>
<tr>
<td>Moodle</td>
<td>1.9-2.3.3</td>
<td>Web Application</td>
<td>Learning Management</td>
<td>352</td>
<td>(Text contains javascript OR js OR jquery) AND (Issue type is bug) AND (Status is closed) - Number of Results: 1209</td>
<td>30</td>
</tr>
<tr>
<td>Joomla</td>
<td>3.x</td>
<td>Web Application</td>
<td>Content Management</td>
<td>434</td>
<td>(Category is JavaScript) AND (Status is Fixed) - Number of Results: 62</td>
<td>11</td>
</tr>
<tr>
<td>WordPress</td>
<td>2.0.6-3.6</td>
<td>Web Application</td>
<td>Blogging</td>
<td>197</td>
<td>(Description contains javascript OR js) OR (Keywords contains javascript OR js) AND (status is closed) - Number of Results: 875</td>
<td>30</td>
</tr>
<tr>
<td>Drupal</td>
<td>6.x-7.x</td>
<td>Web Application</td>
<td>Content Management</td>
<td>213</td>
<td>(Text contains javascript OR js OR jQuery) AND (Category is bug report) AND (Status is closed(fixed)) - Number of Results: 608</td>
<td>30</td>
</tr>
<tr>
<td>Roundcube</td>
<td>0.1-0.9</td>
<td>Web Application</td>
<td>Webmail</td>
<td>729</td>
<td>(Description contains javascript OR js) OR (Keywords contains javascript OR js) AND (status is closed) - Number of Results: 234</td>
<td>30</td>
</tr>
<tr>
<td>WikiMedia</td>
<td>1.16-1.20</td>
<td>Web Application</td>
<td>Wiki Software</td>
<td>160</td>
<td>(Summary contains javascript) AND (Status is resolved) AND (Resolution is fixed) - Number of Results: 49</td>
<td>30</td>
</tr>
<tr>
<td>TYPO3</td>
<td>1.0-6.0</td>
<td>Web Application</td>
<td>Content Management</td>
<td>2252</td>
<td>(Status is resolved) AND (Tracker is bug) AND (Subject contains javascript) (Only one keyword allowed) - Number of Results: 81</td>
<td>30</td>
</tr>
<tr>
<td>TaskFreak</td>
<td>0.6.x</td>
<td>Web Application</td>
<td>Task Organizer</td>
<td>74</td>
<td>(Search keywords contain javascript OR js) AND (User is any user) - Number of Results: 57</td>
<td>6</td>
</tr>
<tr>
<td>jQuery</td>
<td>1.0-1.9</td>
<td>Library</td>
<td>—</td>
<td>94</td>
<td>(Type is bug) AND (Resolution is fixed) - Number of Results: 242</td>
<td>30</td>
</tr>
<tr>
<td>Prototype.js</td>
<td>1.6.0.1.7.0</td>
<td>Library</td>
<td>—</td>
<td>164</td>
<td>(State is resolved) - Number of Results: 142</td>
<td>30</td>
</tr>
<tr>
<td>MooTools</td>
<td>1.1-1.4</td>
<td>Library</td>
<td>—</td>
<td>101</td>
<td>(Label is bug) AND (State is closed) - Number of Results: 52</td>
<td>30</td>
</tr>
<tr>
<td>Ember.js</td>
<td>1.0-1.1</td>
<td>Library</td>
<td>—</td>
<td>745</td>
<td>(Label is bug) AND (State is closed) - Number of Results: 347</td>
<td>30</td>
</tr>
</tbody>
</table>
**Step 2** Once we have the narrowed-down list of bug reports from Step 1, we manually examine each report in the order in which it was retrieved. Since the filter/search features of some bug tracking systems were not as descriptive (e.g., the TYPO3 bug repository only allowed the user to search for bug reports marked “resolved”, but not “fixed”), we also had to manually check whether the bug report satisfied the conditions described in Step 1. If the conditions are satisfied, the bug report is analyzed. Otherwise, the bug report is discarded. A bug report is also discarded if its fault is found to not be JavaScript-related – that is, the error does not propagate into any JavaScript code in the web application. This step is repeated until min\{30, NumJSReports\} reports have been collected in the repository. The number of bug reports we ended up collecting for each bug repository is shown in Table I. Note that Joomla and TaskFreak had only 11 and 6 reports, respectively, which satisfied the above criteria. For all remaining applications, we collected 30 bug reports each.
**Step 3** For each report, we created an XML file that describes and classifies, the error, fault, failure, and impact of the JavaScript bug reported. The XML file also describes the fix applied for the bug. Typically this data is presented in raw form in the original bug report, based on the bug descriptions, developer discussions, patches, and supplementary data; hence, we needed to thoroughly read through, understand, and interpret each bug report in order to extract all the information included in the corresponding XML file. We also include data regarding the date and time of each bug being assigned and fixed in the XML file. We have made these bug report XML files publicly available for reproducibility.²
**D. Analyzing the Collected Bug Reports**
The collected bug report data, captured in the XML files, enable us to qualitatively and quantitatively analyze the nature of JavaScript bugs.
**Fault Categories.** To address RQ1, we classify the bug reports according to the following fault categories that were identified through an initial pilot study:
- **Undefined/Null Variable Usage:** A JavaScript variable that has a null or undefined value – either because the variable has not been defined or has not been assigned a value – is used to access an object property or method. **Example:** The variable x, which has not been defined in the JavaScript code, is used to access the property bar via x.bar.
- **Undefined Method:** A call is made in the JavaScript code to a method that has not been defined. **Example:** The undefined function foo() is called in the JavaScript code.
- **Incorrect Method Parameter:** An unexpected or invalid value is passed to a native JavaScript method, or assigned to a native JavaScript property. **Example:** A string value is passed to the JavaScript Date object’s setDate() method, which expects an integer. Another example is passing an ID string to the DOM method getElementById() that does not correspond to any IDs in the DOM. Note that this latter example is a type of DOM-related fault, which is a subcategory of Incorrect
TABLE II
IMPACT TYPES.
<table>
<thead>
<tr>
<th>Type</th>
<th>Description</th>
<th>Examples</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Cosmetic</td>
<td>Table is not centred; header is too small</td>
</tr>
<tr>
<td>2</td>
<td>Minor functionality loss</td>
<td>Cannot create e-mail addresses containing apostrophe characters, which are often only used by spammers</td>
</tr>
<tr>
<td>3</td>
<td>Some functionality loss</td>
<td>Cannot use delete button to delete e-mails, but delete key works fine.</td>
</tr>
<tr>
<td>4</td>
<td>Major functionality loss</td>
<td>Cannot delete e-mails at all; cannot create new posts</td>
</tr>
<tr>
<td>5</td>
<td>Data loss, crash, or security issue</td>
<td>Browser crashes/hangs; entire application unusable; save button does not work and prevents user from saving considerable amount of data; information leakage</td>
</tr>
</tbody>
</table>
Method Parameter faults where the method/property is a DOM API method/property (as defined in Section II-B).
- **Incorrect Return Value**: A user-defined method is returning an incorrect return value even though the parameter(s) is/are valid. *Example*: The user-defined method `factorial(3)` returns 2 instead of 6.
- **Syntax-Based Fault**: There is a syntax error in the JavaScript code. *Example*: There is an unescaped apostrophe character in a string literal that is defined using single quotes.
- **Other**: Errors that do not fall into the above categories. *Example*: There is a naming conflict between methods or variables in the JavaScript code.
Failure Categories. The failure category refers to the observable consequence of the fault. For each bug report, we marked the failure category as either Code-terminating or Output-related, as defined in Section II-B. This categorization helps us answer RQ2.
Impact Types. To classify the impact of a fault, we use the classification scheme used by Bugzilla. This scheme is applicable to any software application, and has been also used in other studies [7], [8]. Table II shows the categories. This categorization helps us answer RQ2.
Error Locations. The error location refers to the code unit or file where the error was made (either by the programmer or the server-side program generating the JavaScript code). For each bug report, we marked the error location as one of the following: (1) *JavaScript code (JS)*; (2) *HTML Code (HTML)*; (3) *Server-side code (SSC)*; (4) *Server configuration file (SCF)*; (5) *Other (OTH)*; and (6) *Multiple error locations (MEL)*. In cases where the error location is marked as either OTH or MEL, the location(s) is/are specified in the error description. This categorization helps us answer RQ3.
Browser Specificity. In addition, we also noted whether a certain bug report is browser-specific – that is, the fault described in the report only occurs in one or two browsers, but not in others – to help us answer RQ4.
Time for Fixing. To answer RQ5, we define the triage time as the time it took a bug to get assigned to a developer, from the time it was reported (or, if there is no “assigned” marking, the time until the first comment is posted in the report). We also define fix time as the time it took the corresponding JavaScript fault to get marked as “fixed”, from the time it was triaged. We recorded the time taken for each JavaScript bug report to be triaged, and for the report to be fixed. Other studies have classified bugs on a similar basis [9], [10]. Further, we calculate times based on the calendar date; hence, if a bug report was triaged on the same date as it was reported, the triage time is recorded as 0.
IV. RESULTS
In this section, we present the results of our empirical study on JavaScript bug reports. The subsections are organized according to the research questions in Section III-A.
A. Fault Categories
Table III shows the breakdown of the fault categories in our experimental objects. The pie chart in Figure 2 shows the overall percentages. As seen from the table and the figure, approximately 74% of JavaScript faults belong to the “Incorrect Method Parameter” category. This suggests that most JavaScript faults result from errors related to setting up the parameters of native JavaScript methods, or the values assigned to native JavaScript properties.
Finding #1: “Incorrect Method Parameter” faults account for around 74% of JavaScript faults.
In our earlier studies of JavaScript console messages [1] and fault-localization of JavaScript bugs [11], we also noticed many “Incorrect Method Parameter” faults, but their prevalence was not quantified. Interestingly, we also observed in these earlier studies that many of the methods and properties affected by these faults are DOM methods/properties – in other words, DOM-related faults, as defined in Section II. Based on these prior observations, we became curious as to how many of these “Incorrect Method Parameter” faults are DOM-related.
We further classified the “Incorrect Method Parameter” faults based on the methods/properties in which the incorrect values propagated, and found that 88% of these faults are DOM-related faults. This indicates that among all JavaScript faults, approximately 65% are DOM-related faults (see rightmost pie chart in Figure 2). We find that DOM-related faults range from 50 to 87% of the total JavaScript faults across applications, as seen on the last column of Table III.
Finding #2: DOM-related faults account for 88% of “Incorrect Method Parameter” faults. Hence, the majority – around 65% – of JavaScript faults are DOM-related.
### B. Consequences of JavaScript Faults
We now show the failure categories of the bug reports we collected, as well as the impact of the JavaScript faults that correspond to the reports.
**Failure Categories.** Table IV shows the distribution of failure categories amongst the collected reports; all faults are classified as either leading to a code-terminating failure or an output-related failure (these terms are defined in Section III-D). As the table shows, around 56% of JavaScript faults are code-terminating, which means that in these cases, an exception is thrown. Faults that lead to code-termination are generally easy to detect, since the exceptions have one or more corresponding JavaScript error message(s) (provided the error can be reproduced during testing). On the other hand, output-related failures do not have such messages; they are typically only detected once the user observes an abnormality in the behaviour or appearance of the application.
Since the majority of JavaScript faults are DOM-related, we explored how these failure categories apply to these DOM-related faults. Interestingly, we found that for DOM-related faults, most failures are output-related (at 61%), while for non-DOM-related faults, most failures are code-terminating (at 88%). This result suggests that DOM-related faults may be more difficult to detect than non-DOM-related faults, as most of them do not have error messages.
**Impact Types.** The impact indicates the severity of the failure; Hence, we also classify bug reports based on impact types as defined in Section III-D (i.e., Type 1 has lowest severity, and Type 5 has highest severity).
The impact type distribution for each web application and library is shown in Table V. Most of the bug reports were classified as having Type 3 impact (i.e., some functionality loss). Type 1 and Type 5 impact faults are the fewest, with around 30 bug reports each. Finally, Type 2 and Type 4 impact faults are represented by 92 and 43 bug reports, respectively. The average impact of the collected JavaScript bug reports is close to the middle, at 2.83.
Table V also shows the impact distribution for DOM-related faults in parentheses. As seen in the table, each impact type is comprised primarily of DOM-related faults. Further, almost 80% (23 out of 29) of the highest severity faults (i.e., Type 5 faults) are DOM-related. Additionally, all but two of the experimental objects contain at least one DOM-related fault.
---
**TABLE III**
<table>
<thead>
<tr>
<th>Application</th>
<th>Undefined/Null Variable Usage</th>
<th>Undefined Method</th>
<th>Incorrect Return Value</th>
<th>Syntax-Based Fault</th>
<th>Other</th>
<th>Incorrect Method Parameter</th>
<th>DOM-related</th>
<th>Not DOM-related</th>
<th>Total</th>
<th>Percent DOM-related</th>
</tr>
</thead>
<tbody>
<tr>
<td>Moodle</td>
<td>3</td>
<td>3</td>
<td>0</td>
<td>7</td>
<td>0</td>
<td>15</td>
<td>2</td>
<td>17</td>
<td>30%</td>
<td></td>
</tr>
<tr>
<td>Joomla</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>3</td>
<td>0</td>
<td>6</td>
<td>1</td>
<td>7</td>
<td>55%</td>
<td></td>
</tr>
<tr>
<td>WordPress</td>
<td>1</td>
<td>2</td>
<td>0</td>
<td>3</td>
<td>21</td>
<td>23</td>
<td>23</td>
<td>75%</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Drupal</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>5</td>
<td>0</td>
<td>23</td>
<td>1</td>
<td>24</td>
<td>77%</td>
<td></td>
</tr>
<tr>
<td>Roundcube</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>4</td>
<td>0</td>
<td>22</td>
<td>1</td>
<td>23</td>
<td>75%</td>
<td></td>
</tr>
<tr>
<td>WikiMedia</td>
<td>2</td>
<td>4</td>
<td>0</td>
<td>5</td>
<td>0</td>
<td>15</td>
<td>4</td>
<td>19</td>
<td>50%</td>
<td></td>
</tr>
<tr>
<td>TYPO3</td>
<td>3</td>
<td>0</td>
<td>0</td>
<td>7</td>
<td>0</td>
<td>18</td>
<td>0</td>
<td>18</td>
<td>60%</td>
<td></td>
</tr>
<tr>
<td>TaskFreak</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>4</td>
<td>1</td>
<td>5</td>
<td>67%</td>
<td></td>
</tr>
<tr>
<td>jQuery</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>26</td>
<td>3</td>
<td>29</td>
<td>87%</td>
<td></td>
</tr>
<tr>
<td>Pine volcano</td>
<td>0</td>
<td>1</td>
<td>2</td>
<td>0</td>
<td>22</td>
<td>5</td>
<td>27</td>
<td>75%</td>
<td></td>
<td></td>
</tr>
<tr>
<td>MooTools</td>
<td>3</td>
<td>1</td>
<td>3</td>
<td>0</td>
<td>19</td>
<td>3</td>
<td>22</td>
<td>65%</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Ember.js</td>
<td>2</td>
<td>1</td>
<td>4</td>
<td>0</td>
<td>16</td>
<td>3</td>
<td>21</td>
<td>65%</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Overall</td>
<td>18</td>
<td>15</td>
<td>10</td>
<td>34</td>
<td>5</td>
<td>207</td>
<td>28</td>
<td>235</td>
<td>65%</td>
<td></td>
</tr>
</tbody>
</table>
**TABLE IV**
<table>
<thead>
<tr>
<th>Application</th>
<th>Code-terminating</th>
<th>Output-related</th>
</tr>
</thead>
<tbody>
<tr>
<td>Moodle</td>
<td>140</td>
<td>14</td>
</tr>
<tr>
<td>Joomla</td>
<td>12</td>
<td>3</td>
</tr>
<tr>
<td>WordPress</td>
<td>11</td>
<td>19</td>
</tr>
<tr>
<td>Drupal</td>
<td>12</td>
<td>18</td>
</tr>
<tr>
<td>Roundcube</td>
<td>18</td>
<td>11</td>
</tr>
<tr>
<td>WikiMedia</td>
<td>19</td>
<td>11</td>
</tr>
<tr>
<td>TYPO3</td>
<td>21</td>
<td>9</td>
</tr>
<tr>
<td>TaskFreak</td>
<td>3</td>
<td>3</td>
</tr>
<tr>
<td>jQuery</td>
<td>17</td>
<td>13</td>
</tr>
<tr>
<td>Pine volcano</td>
<td>10</td>
<td>20</td>
</tr>
<tr>
<td>MooTools</td>
<td>21</td>
<td>9</td>
</tr>
<tr>
<td>Ember.js</td>
<td>16</td>
<td>14</td>
</tr>
<tr>
<td>Overall</td>
<td>177</td>
<td>140</td>
</tr>
</tbody>
</table>
Finding #3: While most non-DOM-related JavaScript faults lead to exceptions (around 88%), only a small percentage (39%) of DOM-related faults lead to such exceptions.
with Type 5 impact. This result suggests that high severity failures often result from DOM-related faults. We find that these high-impact faults broadly fall into three categories.
1) Application/library becomes unusable. This occurs because an erroneous feature is preventing the user from using the rest of the application, particularly in DOM-related faults. For example, one of the faults in Drupal prevented users from logging in (due to incorrect attribute values assigned to the username and password elements), so the application could not even be accessed.
2) Data loss. Once again, this is particularly true for DOM-related faults, which account for 9 out of the 10 data-loss-causing faults that we encountered. One example comes from Roundcube; in one of the bug reports, the fault causes an empty e-mail to be sent, which causes the e-mail written by the user to be lost. As another example, a fault in WordPress causes server data (containing posts) to be deleted automatically without confirmation.
3) Browser hangs and information leakage. Hangs often occur as a result of a bug in the browser; the type 5 faults leading to browser hangs that we encountered are all browser-specific. Information leakage only occurred once, as a result of a JavaScript fault in TYPO3 that caused potentially sensitive code from the server to be displayed on the page.
**Finding #4:** About 80% of the highest severity JavaScript faults are DOM-related.
### C. Causes of JavaScript Faults
#### Locations
Before we can determine the causes, we first need to know where the programmers committed the programming errors. To this end, we marked the error locations of each bug report; the error location categories are listed in Section III-D. The results are shown in Table VI. As the results show, the vast majority (86%) of the JavaScript faults occur as a result of programming errors in the JavaScript code itself. If only DOM-related faults were considered, a similar distribution of fault locations was observed; in fact, the majority is even larger for DOM-related faults that originated from the JavaScript code, at 92%. For these bug reports where the error location is in the JavaScript code itself, the fix involved the manual modification of the corresponding JavaScript file(s). This observation suggests that JavaScript faults typically occur because the programmer herself writes erroneous code, as opposed to server-side code automatically generating erroneous JavaScript code, or HTML.
**Finding #5:** Most JavaScript faults (86%) originate from manually-written JavaScript code as opposed to code automatically generated by the server.
#### Patterns
To understand the programmer mistakes associated with JavaScript errors, we manually examined the bug reports for errors committed in JavaScript code (which were the dominant category). We found that errors fell into the following common patterns:
1) **Erroneous input validation.** Around 18% of the bugs occurred because inputs passed to the JavaScript code (i.e., user input from the DOM or inputs to JavaScript functions) are not being validated or sanitized. The most common mistake made by programmers in this case is neglecting valid input cases. For example, in the jQuery library, the `replaceWith()` method is allowed to take an empty string as input; however, the implementation of this method does not take this possibility into account, thereby causing the call to be ignored.
2) **Error in writing a string literal.** Approximately 14% of the bugs were caused by a mistake in writing a string literal in the JavaScript code. These include forgetting prefixes and/or suffixes, typographical errors, and including wrong character encodings. Half of these errors relate to writing a syntactically valid but incorrect CSS selector (which is used to retrieve DOM elements) or regular expression.
3) **Neglecting differences in browser behaviour.** Around
9% of the bugs were caused by differences in how browsers treat certain methods, properties or operators in JavaScript. Of these, around 60% pertain to differences in how browsers implement native JavaScript methods. For example, a fault occurred in WikiMedia in Internet Explorer 7 and 8 because of the different way those browsers treat certain methods, properties or operators in JavaScript. Of these, around 60% pertain to differences in how browsers implement native JavaScript methods. The remaining 40% pertain to differences in how browsers handle certain features of the language that are not part of the standard.
4) **Forgetting null/undefined check.** Around 9% of the bugs resulted from missing null/undefined checks for a particular variable, assuming that the variable is allowed to have a value of null or undefined.
5) **Error in syntax.** Interestingly, around 7% of bugs resulted from syntax errors in the JavaScript code that were made by the programmer. Note, also, that we found instances where server-side code generated syntactically incorrect JavaScript code, though this is not accounted for here.
**Finding #6:** There are several recurring error patterns – causing JavaScript faults – that arise from JavaScript code.
### D. Browser Specificity
We analyzed the browser specificity of the bug reports we collected. A bug is browser specific if it occurs only in a certain browser. As Table VII shows, most JavaScript faults (74%) are non-browser specific. However, among the browser-specific faults, about 69% are specific to Internet Explorer (IE).
After analyzing the IE-specific faults, we found that most of them (44%) were due to the use of methods and properties that were not supported in that browser (particularly in earlier versions, pre-Internet Explorer 8). This is likely because the use of browser-specific method and property names (which may not be standards-compliant) is more prevalent in IE than in other browsers. In addition, IE has low tolerance of small errors in the JavaScript code. For example, 24% of the IE-specific faults occurred because IE could not handle trailing commas in object-creation code; while these trailing commas are technically syntax errors, other browsers can detect their presence and remove them.
**Finding #7:** Most JavaScript faults (74%) are not browser-specific.
### E. Triage and Fix Time for JavaScript Faults
We calculated the triage time and fix time for each bug report and found that on average, the triage time for JavaScript faults is 32.7 days, while the average fix time is 82.5 days (see Table VIII).
As before, we made the same calculations for DOM-related faults and non-DOM-related faults. We found that DOM-related faults have an average triage time of 26.4 days, compared to 44.4 days for non-DOM-related faults. On the other hand, DOM-related faults have an average fix time of 90.8 days, compared to 66.8 days for non-DOM-related faults. This suggests that developers find DOM-related faults important enough to be triaged more promptly than non-DOM-related faults. However, DOM-related faults take longer to fix, perhaps because of their inherent complexity.
**Finding #8:** On average, DOM-related faults get triaged more promptly than non-DOM-related faults (26.4 days vs. 44.4 days); however, DOM-related faults take longer to fix than non-DOM-related faults (90.8 days vs. 66.8 days)
### F. Threats to Validity
An internal validity threat is that the classifications were made by multiple individuals (i.e., two of the co-authors), which may introduce inconsistencies and bias, particularly in the classification of the impacts. In order to mitigate any possibilities of bias, we conducted a review process in which each person reviews the classifications assigned by the other person. Any disagreements were discussed until a consensus on the classification was reached.
In terms of external threats, our results are based on bug reports from a limited number of experimental objects, which calls into question the representativeness; unfortunately, public bug repositories for web applications are not abundant, as previously mentioned. We mitigated this by choosing web applications that are used for different purposes, including content management, webmail, and wiki.
A construct validity threat is that the bug reports may not be fully representative of the JavaScript faults that occur in web applications. This is because certain types of faults – such as non-deterministic faults and faults with low visual impact – may go unreported. In addition, we focus exclusively on bug reports that were fixed. This decision was made since the root cause would be difficult to determine from open reports, which have no corresponding fix. Further, open reports may not be representative of real bugs, as they are not deemed important enough to fix.
For the triage and fix times, we did not account for possible delays in marking a bug report as “assigned” or “fixed”, which may skew the results. In addition, the triage time is computed as the time until the first developer comment, when there is no “assigned” marking; although we find this approximation reasonable, the developer may not have started fixing until some days after the first comment was posted. These are likewise construct validity threats.
V. DISCUSSION
In this section, we discuss the implications of our findings on web application developers, testers, developers of web analysis tools, and designers of web application development frameworks.
Findings 1 and 2 reveal the difficulties that web application developers have in setting up values passed or assigned to native JavaScript methods and properties – particularly DOM methods and properties. Many of these difficulties arise because the asynchronous, event-driven JavaScript code must deal with the highly dynamic nature of the DOM. This requirement forces the programmer to have to think about how the DOM is structured and what properties its elements possess at certain DOM interaction points in the JavaScript code; doing so can be difficult because (1) the DOM frequently changes at runtime and can have many states, and (2) there are many different ways a user can interact with the web application, which means there are many different orders in which JavaScript event handlers can execute. This suggests the need to equip these programmers with appropriate tools that would help them reason about the DOM, thereby simplifying these DOM-JavaScript interactions.
With regards to Findings 3, 4, and 8, these results suggest that web application testers should prioritize emulating DOM-related faults, as most high-impact faults belong to this category. One possible way to do this is to prioritize the creation of tests that cover DOM interaction points in the JavaScript code. By doing so, testers can immediately find most of the high-impact faults. This early detection is useful because, as Finding 3 suggests, DOM-related faults often have no accompanying error messages and can be more difficult to detect. Further, as Finding 8 suggests, DOM-related faults take longer to fix on average compared to non-DOM-related faults.
As for Findings 5 and 6, these results can be useful for developers of static analysis tools for JavaScript. Many of the current static analysis tools only address syntactic issues with the JavaScript code (e.g., JSLint, Closure Compiler, JSure), which is useful since a few JavaScript faults occur as a result of syntax errors, as described in Section IV-C. However, the majority of JavaScript faults occur because of errors in semantics or logic. Some developers have already started looking into building static semantics checkers for JavaScript, including TAJS, which is a JavaScript type analyzer. However, the programming mistakes we encountered in the bug reports (e.g., erroneous input validations, erroneous CSS selectors, etc.) call for more powerful tools to improve JavaScript reliability.
Finally, while Finding 7 suggests that most JavaScript faults are non-browser specific, we did find a few (mostly IE-specific) faults that are browser-specific. Hence, it is useful to design JavaScript development tools that recognize cross-browser differences and alerts the programmer whenever she forgets to account for these. Some Integrated Development Environments (IDEs) for JavaScript have already implemented this feature, including NetBeans and Aptana.
VI. RELATED WORK
There has been a large number of empirical studies conducted on faults that occur in various types of software applications. Due to space constraints, we focus on those studies that pertain to web applications.
Server-Side Studies. In the past, researchers have studied the causes of web application faults at the server-side using session-based workloads, server logs, and website outage incidents. Further, there have been studies on the control-flow integrity and end-to-end availability of web applications. Our current study differs from these works in that we focus on web application faults that occur at the client-side, particularly ones that propagate into the JavaScript code.
Client-Side Studies. Several empirical studies on the characteristics of client-side JavaScript have been made. For instance, Ratanaworabhan et al. used their JSMeter tool to analyze the dynamic behaviour of JavaScript in web applications. Similar work was conducted by Richards et al. and Martinsen et al. A study of parallelism in JavaScript code was also undertaken by Fortuna et al. Finally, there have been empirical studies on the security of JavaScript. These include empirical studies on cross-site scripting (XSS) sanitization, privacy-violating information flows.
and remote JavaScript inclusions [30], [31]. Unlike our work which studies functional JavaScript faults, these related works address non-functional properties such as security and performance.
Our earlier work [1] looked at the characteristics of failures caused by JavaScript faults, based on console logs. However, we did not study the causes or impact of JavaScript faults, nor did we examine bug reports as we do in this study. To the best of our knowledge, we are the first to perform an empirical study on the characteristics of these real-world JavaScript faults, particularly their causes and impacts.
VII. CONCLUSIONS AND FUTURE WORK
Client-side JavaScript contains many features that are attractive to web application developers and is the basis for modern web applications. However, it is prone to errors that can impact functionality and user experience. In this paper, we perform an empirical study of over 300 bug reports from various web applications and JavaScript libraries to help us understand the nature of the errors that cause these faults, and the failures to which these faults lead. Our results show that (1) around 65% of JavaScript faults are DOM-related; (2) most (around 80%) high severity faults are DOM-related; (3) the vast majority (around 86%) of JavaScript faults are caused by errors manually introduced by JavaScript code programmers; (4) error patterns exist in JavaScript bug reports; and (5) DOM-related faults take longer to fix than non-DOM-related faults.
For future work, we plan to use the results of this study to design static and dynamic analysis tools that would simplify how programmers write reliable JavaScript code.
ACKNOWLEDGMENT
This research was supported in part by NSERC Strategic Project Grants (Mesbah and Pattabiraman), a Four Year Fellowship (FYF) from UBC, a MITACS Graduate Fellowship, and a research gift from Intel Corporation.
REFERENCES
|
{"Source-Url": "http://blogs.ubc.ca/karthik/files/2013/07/esem-camera-ready.pdf", "len_cl100k_base": 11144, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 38047, "total-output-tokens": 13134, "length": "2e13", "weborganizer": {"__label__adult": 0.0003383159637451172, "__label__art_design": 0.0002639293670654297, "__label__crime_law": 0.0002772808074951172, "__label__education_jobs": 0.0006918907165527344, "__label__entertainment": 5.799531936645508e-05, "__label__fashion_beauty": 0.0001417398452758789, "__label__finance_business": 0.00015914440155029297, "__label__food_dining": 0.00024008750915527344, "__label__games": 0.0004591941833496094, "__label__hardware": 0.0005784034729003906, "__label__health": 0.000324249267578125, "__label__history": 0.00014853477478027344, "__label__home_hobbies": 5.817413330078125e-05, "__label__industrial": 0.00019550323486328125, "__label__literature": 0.0001932382583618164, "__label__politics": 0.00016605854034423828, "__label__religion": 0.0003082752227783203, "__label__science_tech": 0.00466156005859375, "__label__social_life": 7.468461990356445e-05, "__label__software": 0.00498199462890625, "__label__software_dev": 0.98486328125, "__label__sports_fitness": 0.0002312660217285156, "__label__transportation": 0.00025177001953125, "__label__travel": 0.000152587890625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57181, 0.02181]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57181, 0.41968]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57181, 0.89857]], "google_gemma-3-12b-it_contains_pii": [[0, 5681, false], [5681, 10701, null], [10701, 16574, null], [16574, 23071, null], [23071, 28198, null], [28198, 35434, null], [35434, 39373, null], [39373, 43262, null], [43262, 49109, null], [49109, 57181, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5681, true], [5681, 10701, null], [10701, 16574, null], [16574, 23071, null], [23071, 28198, null], [28198, 35434, null], [35434, 39373, null], [39373, 43262, null], [43262, 49109, null], [49109, 57181, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57181, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57181, null]], "pdf_page_numbers": [[0, 5681, 1], [5681, 10701, 2], [10701, 16574, 3], [16574, 23071, 4], [23071, 28198, 5], [28198, 35434, 6], [35434, 39373, 7], [39373, 43262, 8], [43262, 49109, 9], [49109, 57181, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57181, 0.21983]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
ddbe6f40e8e9bd303c008888bebfb21690f1b1b0
|
An Overview of PLATINUM
A Platform for Investigating
Non-Uniform Memory (Preliminary Version)
Robert J. Fowler and Alan L. Cox
Technical Report 262
November 1988
**An Overview of PLATINUM, A Platform for Investigating Non-Uniform Memory (Preliminary Version)**
Robert J. Fowler and Alan L. Cox
Computer Science Department
734 Computer Studies Bldg
University of Rochester, Rochester, NY 14627
PLATINUM is an experimental operating system kernel designed to facilitate research on memory management systems for Non-Uniform Memory Access (NUMA) Multiprocessor Architectures. It exports to user programs a simple abstraction of a shared memory multiprocessor in which all memory appears to be uniformly and rapidly accessible from all processors in the machine. The perceived uniformity on top of a non-uniform physical memory architecture is supported by an abstraction called coherent memory. Implemented in software as an extension of a...
of a directory-based caching mechanism using invalidation, coherent
memory attempts to transparently migrate and replicate data to locations
that are physically close to the processors that use it. A fundamental
property of PLATINUM coherent memory is that it automatically reverts to
the use of remote memory access for data that is not amenable to caching.
PLATINUM currently runs on BBN Butterfly Plus Computers.
This report is an overview of PLATINUM. In addition to motivating the
project and presenting our research plans, we describe the interface that
the kernel provides to its users.
An Overview of PLATINUM
A Platform for Investigating Non-Uniform Memory
(Preliminary Version)
Robert J. Fowler
Alan L. Cox
The University of Rochester
Computer Science Department
Rochester, New York 14627
Technical Report 262
November 1988
Abstract
PLATINUM is an experimental operating system kernel designed to facilitate research on memory management systems for Non-Uniform Memory Access (NUMA) Multiprocessor Architectures. It exports to user programs a simple abstraction of a shared memory multiprocessor in which all memory appears to be uniformly and rapidly accessible from all processors in the machine. The perceived uniformity on top of a non-uniform physical memory architecture is supported by an abstraction called coherent memory. Implemented in software as an extension of a directory-based caching mechanism using invalidation, coherent memory attempts to transparently migrate and replicate data to locations that are physically close to the processors that use it. A fundamental property of PLATINUM coherent memory is that it automatically reverts to the use of remote memory access for data that is not amenable to caching. PLATINUM currently runs on BBN Butterfly Plus Computers.
This report is an overview of PLATINUM. In addition to motivating the project and presenting our research plans, we describe the interface that the kernel provides to its users.
---
This work is supported in part by U. S. Army Engineering Topographic Laboratories research contract no. DACA 76-85-C-0001, in part by ONR research contract no. N00014-84-K-0655, and in part by NSF research grant no. CCR-8704492.
1 Introduction.
PLATINUM is an experimental operating system kernel designed to facilitate research on memory management systems for Non-Uniform Memory Access (NUMA) multiprocessor architectures. The name “PLATINUM” is an acronym for “Platform for Investigating Non-Uniform Memory”. Specifically, it provides a platform for evaluation implementations in software of coherent memory abstractions on top of non-uniform physical memory architectures. The distributed, shareable memory of a NUMA machine can be referenced by any processor on the machine, but the cost of accessing a particular physical location varies with the distance between the processor and the memory module. An implementation of coherent memory within PLATINUM can replicate and migrate data to locations close to the processors using that data, thus creating the appearance that memory is uniformly and rapidly accessible. The protocol for controlling this data movement is an extension of a directory-based caching algorithm using selective invalidation to maintain coherency [1, 4].
Because PLATINUM runs on a NUMA machine, a coherent memory protocol always has the option of choosing not to replicate or migrate data, but to use the underlying remote access mechanism instead, in effect dynamically disabling caching on a block-by-block basis. This is crucial because the modification of shared data at fine temporal and spatial granularities can cause interference that costs more than not having caching at all. This effect can be especially expensive with the large block sizes associated with software-assisted caching.
Trace-driven simulation is a standard technique for evaluating multiprocessor memory management protocols. We considered simulating coherent memory protocols prior to implementing them in PLATINUM, but we rejected this approach because we believe that simulations would be able to produce unequivocal results only with a level of effort and computer time considerably greater than the straightforward strategy of implementing a small, instrumented multiprocessor kernel, writing (or converting) a test suite of application programs to run on that kernel, and observing the instrumented system in operation. Factors that influenced our decision to implement rather than simulate included:
- Obtaining reference traces can be a major effort. Existing traces recorded by computer manufacturers are not in the public domain and can be difficult to obtain. Recording accurate multiprocessor traces is especially expensive and slow because it entails the creation of a serialized recording of the memory references of all of the processors in the computation. In a set of traces that has obtained recent prominence in the literature [1, 2, 12, 26] each run is able to record only a few seconds of references for four processors before consuming the available buffer space. In contrast, the execution of an instrumented kernel can be observed for long periods of time on larger numbers of processors. Furthermore, the relative ease of actually running programs means that many more experiments can be performed.
- Trace driven simulations are useful for answering questions about how an existing program would run on the simulated system. Our experience has been that because performance is the driving force behind parallel computation, programmers and compilers optimize parallel programs for the architectures on which the programs are run.
---
1 We are not considering fault-tolerant systems.
Running and tuning applications on an instrumented kernel has the potential to yield insights not obtainable by simulation with traces generated by a “dusty deck” optimized for some other parallel architecture.
- The acid test of any idea is its implementation. Running an implementation on real hardware forced us to address all the details of building a memory manager.
This paper is an overview of PLATINUM. It presents a rationale for the project, describes the interface that the kernel exports to user programs, enumerates some of the experiments we anticipate performing, and points to future directions. A companion paper [13] describes the details of the design and implementation of the memory management subsystem.
PLATINUM currently runs on BBN Butterfly Plus Computers [9]. We are in the process of implementing the first real application: a neural network simulator for experimenting with asynchronous recurrent back-propagation [25].
2 NUMA shared memory and its management.
Any large computing system must have an internal structure that is both physically and logically distributed, composed of modules that communicate through some form of interconnection network. This network introduces limitations on the speed of the system: physical propagation delay, switching delay, arbitration protocols that must be executed if there is potential contention, and the serialization that occurs when contention actually exists. These factors make large memories slower than small ones and make memory systems that can be shared among multiple processors and DMA channels slower than those accessible from only one device. The design of the memory systems of all large fast computers must address these factors in order to keep average access times small enough to allow the central processor to run at close to full speed. The universal approach to this problem is to construct a memory hierarchy that contains fast local memories at strategic points in the system. In some cases, such as general-purpose scalar and vector register sets, these memories are explicitly managed by user programs. The architecture can also provide implicit management, as in the cases of data, instruction, and address translation caches.
The problem of memory speed in a complex system is exacerbated when multiple processors share some of the memory system. Because parts of the memory system are necessarily far from some of the processors, if physical memory speed is to be uniform (as in the case of so-called “dance hall architectures” [27]) then it must be uniformly slow. As in the uniprocessor case, the most common method of increasing average memory speed is to add fast local memories, ranging from hardware caches to user-managed general-purpose registers and private memories. The design of the IBM RP3 [21] multiprocessor contains provisions for all of these.
Adopting the terminology of [30] we refer to multiprocessors in which all local memory (except for processor registers) is implicitly managed by the architecture as uniform memory access (UMA) machines. Memory locality is transparent to user programs. Although it may be possible to detect and induce some variability of access times due to the behavior of the cache, the architecture is designed to maintain the illusion of a single fast global memory.
The cache controller executes a coherency protocol [10], ensuring that all processors have a consistent view of memory when multiple caches share a data item. The economy of implementing coherency protocols by "snooping" on a shared memory bus has enabled a whole generation of modestly sized multiprocessors. These protocols increase effective memory speed seen by the processors and reduce the rate at which each processor uses the bus to access main memory, thereby allowing more processors to be added to the system. Although these protocols are effective with a modest amount of parallelism, the scaleability of these strategies is limited by bus bandwidth, which is consumed by memory traffic and by a rapidly increasing number of bus cycles used to maintain coherency [3, 4]. Directory-based caching schemes are more scaleable than bus-based schemes [2] and are amenable to multi-stage memory-switch architectures. Implemented in hardware, they could be the basis for the design of more scaleable UMA machines.
An alternative to building uniformity into the architecture is to build the multiprocessor so that the physical location of data in memory is both apparent and controllable by the user program. Locality remains transparent in the sense that a single mechanism suffices to access local memory, shared global memory, or the local memory of another processor; however, the time for a processor to access physical memory does vary with its location. We refer to these as non-uniform memory access (NUMA) architectures. NUMA architectures were among the earliest large multiprocessors [29, 15] and they continue to be prominent [7, 9, 21]. NUMA architectures are more scaleable than UMA architectures because they do not depend on coherent hardware caches, instead displacing the management of the memory hierarchy from the architecture and forcing it into higher layers of the system.
The physical placement of code and data is critical to performance on NUMA computers. For example, on the BBN Butterfly no program can afford to fetch its instructions from remote memory. Therefore, shared code must be replicated among all the local memories of processors that use it. Furthermore, considerable effort can be expended on situating concurrently accessed data to reduce both access time and contention. Methods include locating data at the processor that accesses it and scattering the data among the memory modules. Even when a programming system manages location automatically, slow memory access is still apparent to programmers. For example, the Uniform System [8] package on the Butterfly transparently scatters arrays of globally shared data among the memory modules of the machine. This has the effect of statistically reducing contention and making access times more uniform but noticeably longer than those for local memory. In reaction to this, application programmers concerned with performance adopt the programming idiom of locking a piece of the shared data, using a fast block transfer to copy the data to a memory location known to be local, operating on it there, and then block-copying it back to its original location [8, 17].
Explicit management of the physical location of code and data by users is a burden on the programmer and can be difficult even in scientific applications that use very regular patterns of sharing. Because the choice of data structures and algorithms affects the viability of each location strategy, this management of location is often done ad hoc for each application, consuming a significant amount of programmer effort. A premise of this project is that a programmer should be able to concentrate on the application and spend less time programming the architecture. The implicit management of memory hierarchies
on uniprocessors makes the programmer's task for most applications much easier at the cost of acceptable sacrifices in performance. The implicit memory management of PLATINUM is intended to achieve a similar state of affairs on NUMA multiprocessors.
There are, however, some programs whose behavior defeats the purpose of implicitly managed memory hierarchies. For example, programs exhibiting poor locality of reference can induce thrashing in paging systems. A critical advantage of implicit NUMA memory management in PLATINUM over schemes such as the software caching of Li's Distributed Virtual Memory [19] and the software-controlled caching of the VMP Multiprocessor [11, 12] is the option of using remote memory references. Interference causes poor cache performance when memory is shared at a very fine temporal grain by multiple processors. The effects of this interference are magnified when several shared data items are packed into a single cache block. This effect can be severe for implementations of caching in software because they have a relatively high fixed cost per operation that is amortized by using a relatively large block size. With the option of performing remote references, in effect dynamically disabling caching when interference is detected, PLATINUM has the potential to accommodate fine-grained sharing without suffering the overhead of cache interference. Although remote memory access is more expensive than local access, it is still much cheaper than communicating through message passing for fine-grain communication and synchronization.
We are not alone in the investigation of NUMA memory management. Recent work in the area includes the analytic studies of optimal NUMA memory management by Black et al. [5], Sheurich and Dubois' study of the benefits of data migration in mesh-connected NUMA machines [24], and Bolosky's addition of NUMA memory management to Mach on the IBM ACE Multiprocessor Workstation [6].
Section 3, below, discusses the abstract machine model implemented by PLATINUM. Sections 4 through 7 are a detailed exposition of the implementation of the model by the interface the kernel exports to its users. Sections 8 and 9 present our plan for future research using PLATINUM and review the current status of the project. For more detail on the motivation, design, and implementation of PLATINUM, and especially of the coherent memory layer, see [13].
3 The PLATINUM Model.
The model of computation that PLATINUM exports to user programs is a virtual UMA multiprocessor architecture in which all primary memory accessible to user programs appears to be in an abstraction of a fast (on average) shared physical memory module that is uniformly accessible from all of the processors in the system. The physical location of data in primary memory is hidden from the user. As stated above, the kernel implements this abstraction on top of the underlying NUMA architecture through the use of software caching techniques built into its memory management system.
The fundamental abstractions supported by PLATINUM are the thread, the memory object, the port, and the address space. These objects all appear in a single flat global name space.
A memory object is an abstraction of an ordered list of memory pages. A range of pages within a memory object may be bound to any contiguous virtual address range of the same size, subject to hardware alignment restrictions. Neither the virtual address range nor the access rights need be the same in every address space. Since they have global names, memory objects serve as the unit of data- or code-sharing between address spaces.
A thread is a kernel-schedulable thread of control. At any time it is bound to a single processor. An explicit migration operation can move it to another location. It is, however, constrained to execute within a single address space.
An address space is a list of bindings of memory objects and access rights to virtual address ranges. It defines the environment in which one or more threads may execute. The threads in a single address space may be spread among multiple processors.
A Port is a protected message queue that can have any number of senders and receivers. Messages are variable-length arrays of zero or more bytes. Globally named, ports provide a communication medium usable by threads that do not share access to a common memory object. Receive operations on ports can block in the kernel, thus providing a blocking synchronization mechanism.
Parallelism is realized through the use of multiple threads to implement a single application. Many different styles of communication and synchronization can be utilized by a collection of cooperating threads under PLATINUM. Communication between threads can use either shared memory or message-passing via ports. Threads that coexist within a single address space share all of the memory objects mapped into that address space. This implies, in addition to data coherency, that these threads share a coherent view of the mappings of memory objects into the shared space. Alternatively, a memory object can be mapped into multiple address spaces and thus be shared by all of the threads in those spaces. A shared memory object need not be mapped at the same virtual address range in every address space referencing it, nor do the access rights have to be uniform.
All PLATINUM kernel primitives are synchronous. They do not return until the requested operation is completed.
3.1 Rationale for the PLATINUM Model
The success or failure of NUMA architectures will rest on their ability to compete with supercomputers and multicomputers on the bases of performance and programmability in the execution of such computation-intensive programs as occur in scientific and artificial intelligence applications. PLATINUM is therefore aimed at user programs of this sort. As such, it provides a small set of very efficient communication and synchronization primitives with an emphasis on shared memory. Although the model is general-purpose, the current implementation of PLATINUM does not include support for protection and persistent storage required of an operating system for machines used by competing and perhaps hostile user programs.
We repeat our intention that PLATINUM be a simple platform for developing and experimenting with that part of the memory management system which deals specifically with NUMA. The PLATINUM project intends neither to design and implement a radically different general-purpose operating system nor to present users with a new conceptual model.
of virtual memory. The goal is, rather, to concentrate our efforts on research issues directly related to the design, implementation, and evaluation of the memory management aspects of operating systems for NUMA multiprocessors. A secondary goal is to ensure that if our implementations of NUMA memory management prove successful, they can also be of widespread utility. One way of ensuring this is to anticipate the integration of the NUMA memory management subsystem of PLATINUM with an existing general-purpose operating system. Mach [22] is the logical target for this exercise. The model of virtual memory that PLATINUM presents to user programs is therefore derived from Mach. PLATINUM's virtual memory interface is a subset of the Mach virtual memory interface, and much of the code that implements the interface is derived from Mach sources.
4 Data Types
PLATINUM and all current applications are written in C++. From user programs all PLATINUM objects (threads, memory objects, address spaces, and ports) are referenced with unique 32-bit identifiers created by the kernel. Names can be compared, copied, placed in shared memory and passed in messages. The only protection on names is provided by C++ type checking.
```c
typedef object_id_t thread_t;
typedef object_id_t port_t;
typedef object_id_t address_space_t;
typedef object_id_t memory_object_t;
```
In addition to object names, the following data types appear in the argument lists to kernel operations.
```c
typedef short priority_t;
typedef int vm_offset_t;
typedef unsigned vm_size_t;
const vm_size_t vm_page_size;
enum
{
vm_prot_read = 1,
vm_prot_write = 2,
vm_prot_execute = 4
}
const vm_prot_t vm_prot_default = vm_prot_read | vm_prot_write;
```
A `vm_offset_t` is an address in virtual memory and is represented as a signed offset with respect to an address space. The actual range of meaningful addresses is machine-dependent. The type `vm_size_t` is used to express the sizes of memory objects. The ratio of the size of a virtual memory page (`vm_page_size`) to the size of the machine page must be a non-negative power of two. All addresses and sizes are expressed in terms of bytes.
The access rights to a memory object within an address space are encoded by OR'ing together the appropriate set of protection bits as defined by `vm.prot_t`.
The codes returned by kernel operations indicate success or failure.
```c
enum return_t {
failure = 0,
success = 1,
warning = 2
};
```
## 5 Threads
PLATINUM threads are bound to a single processor at any given time. This binding is under the complete control of the application. The initial binding is set at thread creation time, but the application can change it later. A change in binding results in the thread's migration to another processor. The kernel, however, never migrates a thread without a directive from the application.
Some multiprocessor operating systems such as Mach perform dynamic load-balancing among the processors through automatic thread migration. Automatic thread migration, however, makes it more difficult to study the effects of sharing on the memory management system. When a thread migrates the numbers of both cache misses and invalidations are likely to increase. This increase corresponds, respectively, to the replication of pages already at the previous location and to writes to pages still replicated there. For experimental purposes we want to be able to separate cache interference due to thread migration from cache interference due to sharing. Thus, PLATINUM does not provide automatic thread migration.
### 5.1 `create_thread`
```c
return_t create_thread(
address_space_t address_space,
vm_offset_t program_counter,
vm_offset_t stack_pointer,
priority_t priority,
unsigned char *node, // IN/OUT
thread_t *thread) // OUT
```
This primitive creates a new thread and returns its name. The thread will execute in the address space specified by `address_space` and starts in the initial state specified by `program_counter`, `stack_pointer`, and `priority`. The new thread is created in the suspended state and must be explicitly started using the `resume_thread` primitive in order to execute. If `node` is specified, the thread is created on the specified processor. Otherwise, the kernel uses a static load-balancing heuristic to select the processor on which to create the thread. The new thread's priority can be no higher than that of the creating thread.
Threads are scheduled strictly by priority. On each processor the highest priority runnable threads are scheduled in a round-robin fashion. If a thread of higher priority becomes ready on a processor, the running thread is immediately preempted. This can occur both when a high priority thread is unblocked by another processor or device and when a thread’s priority is increased by a thread running on another processor.
5.2 destroy_thread
return_t destroy_thread(
thread_t thread)
The specified thread is destroyed.
5.3 migrate_thread
return_t migrate_thread(
thread_t thread,
unsigned char *node) // IN/OUT
This primitive binds the thread to a new location. If node is specified, the thread is moved to the specified processor. Otherwise, the kernel uses a static load-balancing heuristic to choose a destination processor. In the latter case it is possible that the thread will not move.
5.4 set_priority_thread
return_t set_priority_thread(
thread_t thread,
priority_t priority)
A thread’s priority can be set no higher than that of the thread changing its priority.
5.5 suspend_thread
return_t suspend_thread(
thread_t thread)
The specified thread is placed in a suspended state. It cannot run in user state until it is resumed. Kernel primitives called by the thread are allowed to complete. Thus, a suspended thread that is blocked because it is executing a receive on a port retains its position in the queue and can become unblocked if it reaches the head of the queue and a message arrives. The thread remains suspended. Suspend_thread returns failure if the specified thread is already suspended.
5.6 resume_thread
return_t resume_thread(
thread_t thread)
The thread is taken out of the suspended state. If the thread is not blocked it is made runnable. Otherwise, it continues to wait. Resume-thread returns failure if the specified thread is not in a suspended state.
Suspend and resume are intended to be used by user-level process management.
6 Messages and Ports
PLATINUM ports are simple, fast message queues. Any number of threads may send to or receive messages from a port. Network operating systems such as Mach, however, restrict the set of receiving threads to those within a single task (address space). This can be attributed to the difficulty of implementation when receiving threads are running on different machines in the network. Because they do not have this restriction, PLATINUM ports can be used as a blocking synchronization mechanism for data in memory objects shared by multiple address spaces.
A message is a variable-length array of zero or more bytes. The maximum size of a message is vm_page.size. The kernel does not interpret the message data. In particular, it performs no type checking. All PLATINUM object identifiers can be transmitted freely through messages or shared memory. Although the message-passing mechanism does not itself implement the automatic transmission of out-of-band data, an application can include the identifier for a memory object in a message and map it in the receiving address space.
In addition to ports allocated by user programs the kernel provides a set of "well-known" ports. These serve as the interface to the system's input/output services.
6.1 create_port
return_t create_port(
port_t *port) // OUT
This primitive creates a new port and returns its name.
6.2 destroy_port
return_t destroy_port(
port_t port)
The specified port is destroyed. All threads waiting on the port when it is destroyed will be unblocked with a status code of failure.
6.3 receive_message
return_t receive_message(
port_t port,
vm_offset_t buffer,
vm_size_t *size) // IN/OUT
This primitive removes the message at the head of port’s queue. If no message is available, the thread blocks. Blocked threads are served in first-come, first-served order. If the message at the head of the queue is larger than the buffer, the message remains on the queue and a warning status code is returned.
6.4 send_message
return_t send_message(
port_t port,
vm_offset_t buffer,
vm_size_t size)
The sending of a message is non-blocking.
6.5 send.receive.message
return_t send_receive_message(
port_t send_port,
vm_offset_t send_buffer,
vm_size_t send_size,
port_t receive_port,
vm_offset_t receive_buffer,
vm_size_t *receive_size) // IN/OUT
This operation combines a send and a receive. It is intended for use in implementing remote procedure call and other synchronous message-passing protocols. If the message at the head of the queue is larger than the buffer, the message remains on the queue and a warning status code is returned.
7 Memory Objects and Address Spaces
PLATINUM has two types of memory object. Named memory objects are created explicitly by user programs. Anonymous memory objects are created by the kernel when a virtual address range is allocated but not mapped to a named memory object. Anonymous memory objects are zero-fill memory that is private to a single address space.
The process of mapping a virtual address range to a contiguous range of pages in a memory object creates a reference to that object. A memory object persists as long as there is at least one reference to it. A name counts as an additional reference, so a named memory object can survive even though it is not currently mapped into any address space. Destroying an address space or deallocating a virtual address range can remove a reference to a memory object. If an entire virtual address range mapping a memory object in an address space is deallocated, then a reference to the memory object is removed. If only a subrange of a virtual address range mapping a memory object is deallocated, then the range is either clipped at the appropriate end or split into two ranges. A split creates an additional reference to the memory object.
7.1 create_memory_object
```c
return_t create_memory_object(
vm_size_t size,
memory_object_t *memory_object) // OUT
```
This primitive creates a new memory object and returns its name. The newly created object is not in any address space. It is filled with zeros.
7.2 destroy_memory_object
```c
return_t destroy_memory_object(
memory_object_t memory_object)
```
This primitive removes the binding between a name and the memory object to which it refers. The object can no longer be accessed through the name. The resources associated with the now anonymous memory object can be reclaimed when the last reference to it is removed.
A named object will be retained even if no mapping to it exists.
7.3 create_address_space
```c
return_t create_address_space(
address_space_t *address_space) // OUT
```
This creates a new address space and returns its name.
7.4 destroy_address_space
```c
return_t destroy_address_space(
address_space_t address_space)
```
Destroying an address space destroys all threads running within it. This implicitly removes the mappings to its memory objects, thus potentially allowing them to be destroyed or reclaimed.
7.5 allocate_range_with_memory_object
```c
return_t allocate_range_with_memory_object(
address_space_t address_space,
vm_offset_t *vadr, // IN/OUT
vm_size_t size,
boolean anywhere,
memory_object_t memory_object
vm_offset_t memory_object_offset)
```
This binds a window of pages beginning at memory_object_offset within a memory object to a range of addresses in the specified address space. If vadr is provided, it will be truncated to the nearest virtual page boundary, as will memory_object_offset. Size will be rounded upward to the next virtual page boundary. If anywhere is true, the kernel will allocate the first available region of sufficient size. Otherwise, it will return failure if vadr is not the start of a sufficiently large region. Access to the range is set to vm.prot_default.
7.6 allocate_range
```c
return_t allocate_range(
address_space_t address_space,
vm_offset_t *vadr, // IN/OUT
vm_size_t size,
boolean anywhere)
```
This allocates a region of virtual address space and creates an anonymous memory object which is mapped into that region. Since the memory object is unnamed there is no way that it can be mapped into any other address space. If vadr is provided, it is truncated to the nearest virtual page boundary. Size is rounded upward to the next virtual page boundary. If anywhere is true, the kernel allocates an available region of sufficient size. Otherwise, it returns failure if vadr is not the start of a sufficiently large region. Access to the range is set to vm.prot_default. The virtual memory region allocated is filled with zeros.
7.7 deallocate_range
```c
return_t deallocate_range(
address_space_t address_space,
vm_offset_t vadr,
vm_size_t size)
```
This primitive deallocates the specified address range. Vadr is truncated to the nearest virtual page boundary. Size is rounded upward to the next multiple of the virtual page size. The deallocation of the range can remove references to one or more objects and potentially cause them to be destroyed. Deallocating an address range in the middle of a range to which an object is mapped splits the existing reference to the object into two.
### 7.8 protect_range
```c
return_t protect_range(
address_space_t address_space,
vm_offset_t vadr,
vm_size_t size,
vm_prot_t prot)
```
Vadr is truncated to the nearest virtual page boundary. Size is rounded upward to the next multiple of the virtual page size. Access rights to the specified range of pages in the address space are set to the requested value.
### 8 Experiments with NUMA Memory Management.
As stated in section 2, the problem of providing a form of uniform shared memory model on a physically distributed shared memory machine can be attacked at several levels:
- Memory coherence can be implemented in the machine architecture level using hardware caching, as in UMA multiprocessors.
- It can be implemented transparently in the operating system kernel level as part of the memory management system.
- It can be implemented in user programs, either explicitly by the programmer or implicitly as part of the programming language model.
- The implementation can span two or more levels.
While PLATINUM primarily addresses the feasibility of a software implementation in the kernel, it also interacts with the layers above and below it. Experiments with PLATINUM cannot test the kernel in isolation; they must also shed light on these interactions.
The version of PLATINUM described in this paper is an experiment in providing uniformity by maintaining a coherent memory abstraction entirely and transparently in the operating system kernel on an existing NUMA architecture. The user program is not able to direct the execution of the coherency mechanism, nor is it able to affect the policies directing the mechanism. We intend to explore this approach thoroughly before examining other strategies for providing uniformity. This will include the tuning of the implementation of coherent memory as well as analyzing in detail the performance of the system running
user programs with widely varying patterns of shared memory usage. At one extreme, applications performing fine-grain modification on very large amounts of shared data will not benefit from the potential of migrating and replicating that data. At best we can hope to reduce the overhead incurred in recognizing this situation. At the other extreme, programs that perform relatively few modifications on shared data will place few demands on the coherency protocol. By characterizing the behavior of the memory manager on a variety of programs that lie between these two poles, we intend to define the domain for which this approach is effective.
PLATINUM is being instrumented to record the kind of detailed information we will need to analyze these experiments. Internally, the kernel uses simple locking protocols to synchronize access to its data structures. Fine-grain synchronization traces can be recorded using instrumented versions of the locking operations [18]. These can then be analyzed off-line using a suite of debugging and performance analysis tools that we have developed over the last two years at the University of Rochester [14]. The traces will be useful for tuning the kernel as well as recording the interleaving of kernel operations for the purpose of evaluating the performance of the memory management system.
Programmers and compiler writers concerned with performance try to tune their code for the architecture on which it is run. Although the implementation of PLATINUM coherent memory is entirely within the kernel, one effective mechanism for tuning user programs running on top of PLATINUM will be the careful placement of data within memory objects to reduce inter-processor interference. Performance can be adversely affected by co-locating in one page of coherent memory data items that have radically different properties with respect to sharing. Co-locating the private data of threads on distinct processors induces spurious sharing. Co-locating data items that are shared at different temporal granularities can lead to location choices inappropriate for each. For example, processors busy waiting on a lock will attempt to modify it using test-and-set at a much finer granularity than the data it protects. If the lock and the data are both on the same page, the contention for the lock will make it appear that there is a finer granularity of sharing for the data than is the case. This can prevent the data from being moved to the processor accessing it. These effects will have to be considered in the evaluation of PLATINUM.
Since programmers and compilers will attempt to be clever about the placement of data in memory, we will evaluate the effect of adding a mechanism for declaring the sharing properties of pages in coherent memory. A declaration will be used to parameterize the policy for migrating and replicating those pages. In the extreme, it will be used to disable data movement.
Implicit memory hierarchy management schemes are all based on the locality of memory references. When a program is in equilibrium, access patterns in the near future will be similar to those of the recent past. If a program executes in phases and access patterns change between phases, there will be transient decrease in the performance of the memory hierarchy at each change [28]. If phase changes are frequent and the mechanism to detect them reacts comparatively slowly, the system will never achieve equilibrium. Because coherent memory relies heavily on software, we expect that this will be one of the limitations of PLATINUM. A possible method of improving the response to transients without special architectural support is to provide a mechanism by which directives from the user program
can mark its phase changes for the kernel. For example, the act of releasing a lock usually
marks the end of a phase of intense access to a block of data by one processor. By executing
an appropriate directive the user program can inform the memory manager that the recent
activity should be ignored when deciding whether to migrate or replicate the data. Directives
to the memory manager can be inserted explicitly by the programmer or implicitly
by compilers and/or run-time libraries. A similar strategy is advocated by McNiven and
Davidson for providing information to the block replacement policy of a hardware cache
[20]. Extensions to the PLATINUM interface in this direction will improve its ability to sup-
port languages such as Emerald [16], which includes a form of language-directed migration
of shared data.
The viability of kernel-supported coherent memory will depend upon the architecture
on which it is implemented. Although PLATINUM does not require architectural support
beyond that available on a Butterfly Plus, it does take advantage of the facilities available
to it. For example, the processor-memory switch in the Butterfly Plus provides a block
transfer primitive that moves data between memories at an incremental cost comparable to
reading a local memory. Given an approximately fifteen-to-one ratio between the costs of
remote and local access, replication and migration are usually desirable even if only a small
fraction of the data moved is actually accessed at the destination. PLATINUM also makes
extensive use of the flexibility of the Motorola MC68851 memory management unit.
We anticipate porting PLATINUM to a very different NUMA machine. The IBM ACE
Multiprocessor Workstation has a global memory whose access cost is between that of
accessing local memory and that of accessing another processor's memory remotely, a very
different memory management unit, and no special block transfer mechanism. On this
architecture the high relative cost of data movement will make it less attractive than on
a Butterfly Plus. On the other hand, placing data in the common global memory is a
useful alternative. These properties will affect the policies used within PLATINUM. The
architectural decisions made for each machine can then be evaluated with respect to kernel-
supported memory coherency by comparing the PLATINUM implementations.
Comparative architectural studies will also help predict the value in practice of other
forms of architectural support. For example, analytic studies [5, 24] have assumed the
existence of reference counters that are sensitive to the relative locality of the processor
generating each reference. Such counters are not part of any existing machine. Before
actually designing shared memory management and caching hardware that includes coherent
reference counts it is worth while to attempt to understand the performance of systems
without them.
9 Status and Conclusions.
At this time PLATINUM is running on BBN Butterfly Plus Multiprocessors. Since all
kernel data structures that are not a part of the coherent memory system are stored in
coherent memory, memory management had to be functional before we could finish the
kernel. Consequently, it is the most thoroughly tested part of the kernel. Furthermore,
building the remainder of the kernel on the coherent memory made the kernel's design and
development an easier task than the construction of Osiris, a similar experimental NUMA kernel implemented as a pedagogical exercise.
PLATINUM is a small kernel. We are now in the process of designing and implementing a more complete operating system interface that will provide basic services such as file and terminal I/O. These services will be provided by a set of servers communicating with applications through message-passing and shared memory.
We have begun work on the development of applications to run on PLATINUM. A simulator for recurrent backpropagation networks [25] is the first real application to be ported.
Acknowledgements.
We thank Lawrence Crowl and Tom LeBlanc for their helpful comments and suggestions. Special thanks go to Niki Hansen for her editorial assistance.
References
|
{"Source-Url": "http://www.dtic.mil/dtic/tr/fulltext/u2/a213911.pdf", "len_cl100k_base": 8651, "olmocr-version": "0.1.53", "pdf-total-pages": 23, "total-fallback-pages": 0, "total-input-tokens": 48878, "total-output-tokens": 11394, "length": "2e13", "weborganizer": {"__label__adult": 0.0004856586456298828, "__label__art_design": 0.0006108283996582031, "__label__crime_law": 0.0003960132598876953, "__label__education_jobs": 0.0006642341613769531, "__label__entertainment": 0.00011628866195678712, "__label__fashion_beauty": 0.00023174285888671875, "__label__finance_business": 0.0002834796905517578, "__label__food_dining": 0.0004503726959228515, "__label__games": 0.0010099411010742188, "__label__hardware": 0.0105743408203125, "__label__health": 0.0007262229919433594, "__label__history": 0.0005183219909667969, "__label__home_hobbies": 0.00016498565673828125, "__label__industrial": 0.0009527206420898438, "__label__literature": 0.00030493736267089844, "__label__politics": 0.00031375885009765625, "__label__religion": 0.0008306503295898438, "__label__science_tech": 0.228759765625, "__label__social_life": 8.07046890258789e-05, "__label__software": 0.012481689453125, "__label__software_dev": 0.73828125, "__label__sports_fitness": 0.0003972053527832031, "__label__transportation": 0.0011587142944335938, "__label__travel": 0.0002677440643310547}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49210, 0.01856]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49210, 0.56671]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49210, 0.90117]], "google_gemma-3-12b-it_contains_pii": [[0, 164, false], [164, 945, null], [945, 1540, null], [1540, 3163, null], [3163, 6658, null], [6658, 9983, null], [9983, 13761, null], [13761, 16960, null], [16960, 20334, null], [20334, 22518, null], [22518, 24826, null], [24826, 26471, null], [26471, 28431, null], [28431, 29851, null], [29851, 31671, null], [31671, 33616, null], [33616, 35959, null], [35959, 39699, null], [39699, 43071, null], [43071, 43866, null], [43866, 46161, null], [46161, 48780, null], [48780, 49210, null]], "google_gemma-3-12b-it_is_public_document": [[0, 164, true], [164, 945, null], [945, 1540, null], [1540, 3163, null], [3163, 6658, null], [6658, 9983, null], [9983, 13761, null], [13761, 16960, null], [16960, 20334, null], [20334, 22518, null], [22518, 24826, null], [24826, 26471, null], [26471, 28431, null], [28431, 29851, null], [29851, 31671, null], [31671, 33616, null], [33616, 35959, null], [35959, 39699, null], [39699, 43071, null], [43071, 43866, null], [43866, 46161, null], [46161, 48780, null], [48780, 49210, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49210, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49210, null]], "pdf_page_numbers": [[0, 164, 1], [164, 945, 2], [945, 1540, 3], [1540, 3163, 4], [3163, 6658, 5], [6658, 9983, 6], [9983, 13761, 7], [13761, 16960, 8], [16960, 20334, 9], [20334, 22518, 10], [22518, 24826, 11], [24826, 26471, 12], [26471, 28431, 13], [28431, 29851, 14], [29851, 31671, 15], [31671, 33616, 16], [33616, 35959, 17], [35959, 39699, 18], [39699, 43071, 19], [43071, 43866, 20], [43866, 46161, 21], [46161, 48780, 22], [48780, 49210, 23]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49210, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
af5274bbe018bbdcf07b0f62091bb61c501facdb
|
Citation for published version
DOI
Link to record in KAR
http://kar.kent.ac.uk/42968/
Document Version
Pre-print
Copyright & reuse
Content in the Kent Academic Repository is made available for research purposes. Unless otherwise stated all content is protected by copyright and in the absence of an open licence (eg Creative Commons), permissions for further reuse of content should be sought from the publisher, author or other copyright holder.
Versions of research
The version in the Kent Academic Repository may differ from the final published version. Users are advised to check http://kar.kent.ac.uk for the status of the paper. Users should always cite the published version of record.
Enquiries
For any further enquiries regarding the licence status of this document, please contact: researchsupport@kent.ac.uk
If you believe this document infringes copyright then please contact the KAR admin team with the take-down information provided at http://kar.kent.ac.uk/contact.html
Run-Time Generation, Transformation, and Verification of Access Control Models for Self-Protection
Christopher Bailey
School of Computing
University of Kent, UK
c.bailey@kent.ac.uk
Lionel Montrieux
Centre for Research in Computing
The Open University, UK
lionel.montrieux@open.ac.uk
Rogério de Lemos
School of Computing
University of Kent, UK
r.delemos@kent.ac.uk
Yijun Yu
Centre for Research in Computing
The Open University, UK
yijun.yu@open.ac.uk
Michel Wermelinger
Centre for Research in Computing
The Open University, UK
michel.wermelinger@open.ac.uk
ABSTRACT
Self-adaptive access control, in which self-* properties are applied to protecting systems, is a promising solution for the handling of malicious user behaviour in complex infrastructures. A major challenge in self-adaptive access control is ensuring that chosen adaptations are valid, and produce a satisfiable model of access. The contribution of this paper is the generation, transformation and verification of Role Based Access Control (RBAC) models at run-time, as a means for providing assurances that the adaptations to be deployed are valid. The goal is to protect the system against insider threats by adapting at run-time the access control policies associated with system resources, and access rights assigned to users. Depending on the type of attack, and based on the models from the target system and its environment, the adapted access control models need to be evaluated against the RBAC metamodel, and the adaptation constraints related to the application. The feasibility of the proposed approach has been demonstrated in the context of a fully working prototype using malicious scenarios inspired by a well documented case of insider attack.
Categories and Subject Descriptors
D.4.6 [Software Engineering]: Security and Protection—Access controls, Verification
General Terms
Security, Verification
Keywords
Adaptive security, RBAC, model verification, self-adaptation
1. INTRODUCTION
The incorporation of self-adaptability into complex systems inevitably involves the creation and manipulation of several diverse models related to the different viewpoints of the system and its environment. In this paper, we show how this can be achieved in the context of systems security, in particular, how self-adaptive access control (the parametric adaptation of permissions and user access rights) can be an effective solution in protecting against insider threats [13].
Traditionally, organisations rely on audit trails and human administrators to monitor access control systems for the purpose of identifying and handling malicious behaviour, and the consequences have been dire [9, 12, 13]. The application of self-adaptation to access control is a promising solution to improving management of access in organisations, in particular, the timely identification and response to malicious user behaviour for better protecting an organisation’s set of resources from internal attacks. However, the risk with self-adaptive access control is the potential negative impact to an organisation, should unnecessary or invalid adaptation be carried out to systems that are of a critical nature. The use of models, together with model transformation and verification at run-time, is seen as a solution to ensure that when handling malicious behaviour, we are able to obtain a verified modelled state of access control that conforms to the organisation’s own requirements.
Authorisation infrastructures, which implement access control, are typically deployed as a set of independent systems that conform to an access control methodology, such as Role Based Access Control (RBAC) [36]. For example, an authorisation infrastructure may contain an access control service, which provides access decisions based on a set of access control rules, in addition to an identity service, which maintains a set of users and user assigned access rights. Users use their access rights, which are evaluated by the access control service, to assert whether or not the user should be given access to a resource. When adapting authorisation infrastructures (e.g., the removal of a user’s assigned access right to a database), it is necessary to maintain a model of each type of system service to produce a complete model of access that conforms to the system’s implemented access control methodology. Model transformation for producing
access control models allows self-adaptive controllers to abstract from implementation specific models, and verify access control as whole, as opposed to individual verification of models relating to independent systems.
The contribution of this paper is related to the provision of assurances for complex self-adaptive systems that require the manipulation of several diverse models. We propose a run-time approach based on model generation, transformation, and verification for providing assurances that the deployed adaptation conforms to the system requirements. This approach is applied, specifically, to self-adaptive access control systems in which adapted access control models are verified before being deployed. The overall goal of our approach is to identify malicious behaviour, in the form of insider attacks, in order to automatically modify policies and rules for mitigating ongoing attacks or prevent future ones. In order to show the feasibility of the proposed approach, we have developed a fully working prototype in which the implementation specific models, including the solutions to deal with the attacks, are transformed into an RBAC model using the Atlas Transformation Language (ATL) [21]. This RBAC model is then verified using the rbacDSML verification tool [1, 27], which is able to verify a UML model of RBAC against OCL constraints. To evaluate our approach, we simulate a documented case of insider attack within our own deployed self-adaptive authorisation infrastructure [4]. The simulation has demonstrated the ability of our prototype to handle multiple attacks using verified adaptations of the authorisation infrastructure.
The rest of this paper is structured as follows. In Section 2, we present background to our work. Section 3 describes the simulation of accessing a real life insider attack. In Section 4, we describe an experiment involving our prototype, demonstrating the handling of an insider attack. Section 5 discusses related work in terms of access control verification, and self-adaptation. Finally, Section 6 concludes by summarising the work done so far, and indicates future directions of research.
2. BACKGROUND
2.1 Role Based Access Control (RBAC)
Role-Based Access Control (RBAC) is an access control methodology that features roles as first-class citizens [36]. In RBAC, users are not assigned permissions directly. Instead, they are assigned roles, and those roles are in turn assigned permissions, in order to facilitate the maintenance of large access control policies. RBAC also features role hierarchies, where a role inherits its ancestors’ permissions, as well as constraints. Example of constraints are static separation of duties (SSoD), where in two roles cannot be assigned to a user, and dynamic separation of duties (DSoD), where two roles cannot be activated at the same time by a user. RBAC has been standardised by OASIS [30], and is composed of four levels, each one adding new constructs on top of the lower one.
2.2 RBAC Model Verification
Large access control models can be difficult to manage by hand. Ensuring the consistency of the model, but also making sure that the model conforms to the designers’ requirements can become a non-trivial and error-prone task when carried out manually. An automated verification mechanism can greatly increase the quality of an access control model, and reduce the number of errors as well as the time spent maintaining access.
As a domain specific language, and a verification tool, rbacDSML allows one to model RBAC policies that conform to the RBAC standard [30], alongside scenarios, which are instantiations of the designers’ requirements. rbacDSML is implemented as a UML profile, and ensures the consistency of the policy as well as its satisfaction of the scenarios using OCL constraints [1, 27]. rbacDSML is available as an open-source plugin for IBM Rational Software Architect [20]. A standalone version is also available, currently with a limited set of features.
Since rbacDSML is a UML profile, it is defined as an extension of the UML metamodel that adds new stereotypes and associations to standard UML models. Figure 1 shows the extension of the UML metamodel for rbacDSML, in MOF, the OMG language for meta-model representation [33]. Users, roles, permissions and resources are represented by stereotypes attached to UML classes. Static and dynamic separation of duty constraints are represented as stereotyped associations between two roles. Role hierarchies are represented as class hierarchies. These constructs are a one-to-one translation of the standard RBAC model. In addition to standard RBAC, rbacDSML provides several types scenarios, that are represented as stereotypes attached to classes. User scenarios require that a user, given a set of active roles, must be able to (resp. not be able to) access a set of resources if stereotyped with Granted (resp. Forbidden). User - role scenarios require a role to be assigned to at least one user. Role - resource scenarios require a set of resources to be accessible using the permissions given by a role. Finally, resource scenarios require a resource to be accessible by at least one user.
rbacDSML uses seven OCL constraints: two to verify that SSoD and DSoD constraints are not violated; one to verify that roles activated in a scenario have been assigned to the user involved in the scenario; and finally, one constraint for each type of scenario.
2.3 Self-Adaptive Authorisation
Authorisation infrastructures exist to control access to an organisation’s electronic resources (e.g., web applications, servers, databases). They are represented as a collection of identity services [25], which maintain information about
users and their access rights, and authorisation services [14], which enable access control (the evaluation of user access rights). Management of authorisation infrastructures has increased in complexity, as a result of large user bases and federation [29], but typically rely on human administrators to maintain the conditions of access, and identify when access should change.
Previous work has proposed a Self-Adaptive Authorisation Framework (SAAF) as a solution to managing access control autonomically [3]. SAAF is based on the MAPE-K [23] feedback loop for identifying and responding to insider threats [13], which are typically conducted through user exploitation of legitimately assigned access rights. The provision of self-adaptation to authorisation infrastructures has shown to be a promising solution to respond to insider threats [4, 5], as the adaptation of access control can prevent or limit a malicious user’s ability to access protected resources, thus mitigating the attack. The SAAF controller performs adaptations when reacting to identified insider attacks, either by modifying access control policies or user access rights (e.g., the removal of user RBAC roles).
Figure 2 presents a conceptual view of SAAF in which an autonomic controller monitors and adapts multiple systems within an authorisation infrastructure. This presents a challenge since no single system provides a complete view of access in terms of what users own in access rights, what access control rules exist, and finally, how users are utilising access rights. In addition to this, each system may differ on their implementation of the access control methodology that the system claims to conform to (e.g., the RBAC standard). As a result, it can be said that each authorisation service has its own implementation specific model representing part of an access control model (such as, active RBAC roles and permissions). Moreover, an existing limitation of SAAF is its inability to verify an adapted state of access before it is realised in an authorisation infrastructure. In its current form, SAAF assumes that whatever adaptations take place will not break conformance to the service’s implemented access control methodology (RBAC), nor conflict with application domain requirements (e.g., ensure access to business critical systems). The use of models (to identify state of access), and model verification at run-time, is seen as a solution to the above existing SAAF limitations.
3. APPROACH
Authorisation infrastructures can be considered critical for organisations, as they provide services to an organisation that enables their users to access resources and perform their duties. A primary concern when adapting a user’s access to resources is to obtain guarantees that the resulting adaptation will resolve problems without creating additional ones. It is also important to ensure that any adapted model of access conforms to the authorisation infrastructure’s implemented access control methodology (i.e., RBAC).
In the following, we take as an example, a well reported case of IP theft involving a chemical research company [13], where, as any modern organisation requires, there is a need to provide secure access to organisational resources to relevant employees. The chemical company at any given time may need to modify its authorisation infrastructure due to the organisation undergoing natural change (new users, organisational roles, resources), or as a result of access being defined incorrectly, or due to the identification of malicious activities exhibited by their users. As such, the chemical company case study provides the basis to highlighting the benefits of using models, and their run-time verification, in self-adaptive authorisation infrastructures. We do not discuss the detection of insider threats since in a previous work [4] we have shown how the SAAF controller identifies and responds to extreme usage of resources. Such detection techniques can be improved upon with existing approaches, including, anomalous detection through machine learning [10] to handle the detection of unknown attacks.
In this section, we detail our approach in which a SAAF controller makes use of models for capturing the current state of access control, and of model transformation for supporting the verification of those models. Verification enables a controller to identify whether the adapted modelled state of access conforms to the authorisation infrastructure’s implemented access control methodology (i.e., RBAC), as well as ensuring the model of access meets the application domain’s requirements.
3.1 Chemical Company Case Study
In late 2005, a chemical research company was a victim to an insider attack [13] in which an attacker stole around 22,000 sensitive documents from an ElectronicLibrary. The attacker, at the time, was an employee of the chemical company, whereby it was assumed he had legitimate access rights to the ElectronicLibrary. The attack was committed over a period of 4 months, and only identified once the attacker had ended his contract and begun working for a competitor.
From the account of the attack it is difficult to surmise a complete picture of the system, however it is likely the chemical company operated an authorisation service to manage access to their ElectronicLibrary, and utilised identity services to maintain access rights of their users. For the purpose of demonstrating our approach, we make the assumption that the chemical company implements RBAC (due to RBAC’s popularity in industry) as their access control methodology, as shown in Figure 3, where users have relevant roles, such as Researcher, who have permissions, such as Get Document from ElectronicLibrary. To implement RBAC, we provide an identity service referred to as LDAP [25], which is a directory service commonly used to hold information (including user roles) about users within an organisation, and an authorisation service known as PERMISSIONS [14], a standalone service used to generate RBAC access control decisions based on roles owned by users. It is assumed the attacker would have utilised his role stored within the LDAP directory for gaining access to the ElectronicLibrary, whereby the ElectronicLibrary would request

Figure 3: Interpreted chemical company class diagram
an access control decision from the PERMIS authorisation service. The PERMIS authorisation service would in turn check permissions held within its own access control policy, to see if the accessing user has the relevant roles for access.
Although the identification of the attack is not clearly discussed in the account, we will classify the properties of the attack in terms of the attacker’s usage of the Electronic Library. Notably, the attacker’s usage was 15 times higher than the next highest user downloads, and many of the downloaded documents were not related to the attacker’s role [13]. Had a SAAF-like controller been deployed in this case, it would have been possible for the attack to be detected (and thus responded to) using a set of predefined rules that enable the controller to detect unacceptable patterns of user behaviour [28].
3.2 Model Generation
Before the SAAF controller can begin to identify and respond to the insider attack the chemical company was victim to, it must generate a set of implementation specific models representing the active identity services, and authorisation services within the authorisation infrastructure. The SAAF controller generates these models via its monitor component within the MAPE-K loop, whereby probes obtain information about the services, which is in turn injected into a model of the service. A model generated from the LDAP identity service provides a view of active users and user role assignments. A model generated from the PERMIS authorisation service provides a view of active RBAC access control rules, such as the permissions of each role. Both models generated conform to implementation specific metamodels, which describe what can exist in terms of LDAP and PERMIS. The PERMIS metamodel is automatically generated from PERMIS’s own proprietary access control policy schema, whereas the LDAP metamodel has been defined solely to capture the necessary user information in terms of how LDAP views a user’s set of assigned roles. A benefit in utilising implementation specific models is that a service’s model can be adapted and easily realised against the deployed service. However, a limiting factor is that the SAAF controller must maintain an understanding of each type of service it is to control, in order to identify how the service implements RBAC.
3.3 Model Transformation
Relying on implementation specific models is useful since it is easier to understand and adapt the current state of the LDAP and PERMIS services, considering that each model is independent to each other and is subject to independent change. However, for verifying a modelled state of access, the SAAF controller combines the implementation specific models into a single model, which embodies the authorisation infrastructure’s access control methodology (RBAC).
Figure 4 portrays the use of models within the SAAF controller as a set of model to model transformations, conforming to the model driven engineering framework [11]. The transformation diagram describes two domains, the first is the SAAF controller’s domain, where it maintains metamodels of the LDAP identity service (LDAPUser) and the PERMIS authorisation service (PERMIS). The RBAC metamodel is an implementation of the RBAC standard, relevant to SAAF. The second domain is RBACDSML [27], which maintains a metamodel to model RBAC in UML for the purpose of verification, which is described in Section 3.5.
The RBAC model represents the SAAF controller’s knowledge of the current state of access. It combines a view of the active RBAC access control rules maintained in the PERMIS authorisation service, as well as current user role assignments held in the LDAP directory. In the chemical company’s case it represents a combined view of the active RBAC access control rules maintained in the PERMIS authorisation service, as well as active user role assignments held in the LDAP directory. The RBAC model is produced as a result of an Atlas Transformation Language (ATL) [21] transformation program, referred to as PERMIS+USER2RBAC. The PERMIS+USER2RBAC transformation takes as input a model generated from what is injected from the LDAP directory, and a model generated from what is injected from the PERMIS active access control policy. Each time the implementation specific models are updated, via injection of data collected by probes in the authorisation infrastructure, the SAAF controller performs the PERMIS+USER2RBAC transformation. This ensures that the SAAF controller maintains an up-to-date modelled state of access that exists within the authorisation infrastructure. Once the implementation specific models have been transformed into the RBAC model, the SAAF controller is able to reason about the state of access and adapt the RBAC model in light of detected attacks.
Whenever the RBAC model undergoes adaptation, the RBAC model must be transformed back into the implementation specific models, and then deployed back into the relevant services of the authorisation infrastructure. Transformation programs are beneficial here, as the SAAF controller is not concerned with how to adapt implementation specific models, rather, relies on the transformation program to transform the changes made against the RBAC model, into the relevant LDAP or PERMIS model. Two separate transformation programs have been created to enable this: 1) RBAC2PERMIS, which creates a new PERMIS access control policy model, capturing new RBAC access control rules, and 2) RBAC2USER, which creates a new user model specifying new user role assignments.
3.4 Adaptation
Figure 5 depicts a partial view of the SAAF controller capturing the process of analysis, verification and selection
of a verified RBAC model. The SAAF controller comprises
the analysis, which generates new access control models (in
terms of RBAC), and the planning, which selects the most
appropriate access control model amongst the valid ones.
For each identified attack, and depending on the type of at-
tack and current access control model, obtained by inspect-
ing the authorisation infrastructure, the SAAF controller se-
lects a subset of solutions applicable to a particular attack.
The solutions are tailored and incorporated into the current
access control model. In order to ensure that the adapted
access control models are relevant for the user identified as
malicious and the resources they are accessing, each adapted
RBAC model is verified against the rbacDSML verifica-
tion tool. Depending on a positive output of the verification
tool, the adapted RBAC models are collated into a set of
verified adapted RBAC models, applicable for planning.
At deployment-time, the SAAF controller is loaded with
a set of predefined solutions to respond to malicious events.
The solutions match a finite set of actions that can be per-
formed within the application domain, and are parametric
in order to tailor the solutions to specific cases of insider
attacks. Given a detected attack, a solution is selected from
the following alternatives: 1) increasing, limiting or remov-
ing access rights owned by an individual, 2) increasing or
limiting the scope of access defined by RBAC access control
rules, 3) warning the individual(s) of their behaviour, and
4) monitoring the behaviour further. Associated with each
solution is an impact, since depending on the type of action
invoked could cause either negligible or severe consequences
to the system (which may be warranted given the severity
of the attack detected). Which solution is selected depends
on how severe the SAAF controller deems the identified be-
behavior to be, in terms of utility, for example: the number
of non malicious users impacted negatively by the solution
(thus losing access to resources). This may be necessary for
cases where many users are identified as being malicious in
relation to specific resources or roles, where changing RBAC
access control rules provide a more effective means to re-
sponding to the attack.
A simple case of adaptation can be made in terms of the
RBAC metamodel (Figure 1). Adaptation can be performed
against an RBAC model in terms of removing associations
from users and roles, resources and permissions, and roles
and permissions. For example, removing the role Researcher
from user Bob to prevent Bob from accessing resource Elec-
tronicLibrary.
it conforms to the RBAC standard and that separation of duty constraints are not violated, and to make sure that the RBAC model does not violate the adaptation constraints. To this end, a transformation combines the adapted RBAC model with the application’s adaptation constraints into an rbacDSML model. The standalone version of the rbacDSML tool’s OCL constraints carry out the verification process.
Each OCL constraint has been defined on the rbacDSML profile metamodel. Each constraint has a context: a stereotype on which the constraint applies. The verification process will evaluate each OCL constraint on every instance of its context stereotype present in the model. For example, the SSoD constraint’s context is the User stereotype. If there are 20 users in the model, this constraint will be evaluated 20 times, once for each user.
rbacDSML returns a list of violated constraints, together with their context elements. Therefore, if the SSoD constraint has been violated for user Bob, then rbacDSML will return (WF SSoD, Bob) as an element of the list. If no constraints have been violated, rbacDSML returns an empty list.
If the verification has succeeded (i.e., an empty list is returned), the adapted RBAC model is acceptable, and it will be deployed. If one or several errors are detected, the RBAC model is not acceptable, and the SAAF controller will select another candidate RBAC model. If the SAAF controller runs out of candidates, the adaptation is simply cancelled, and the state of access remains the same. The failure to handle an adaptation is simply logged by the SAAF controller, however this could be improved with a mail notification to human administrators.
4. EXPERIMENTS
In this section, we evaluate our approach through a scaled simulation inspired by the chemical company insider attack within an RBAC self-adaptive authorisation infrastructure. A SAAF controller is deployed in order to identify the insider attack, and attempt to handle the attack by adapting the state of access. We focus our evaluation on verification, by demonstrating that the SAAF controller considers several solutions while handling the simulated attack, whereby only a verified solution is selected. To showcase the evaluation of complex solutions, we extend the insider attack scenario to consider the case of multiple collaborating attackers. This enables the demonstration of solutions involving adaptations against access control policies. Evidence is provided by way of a table in which we capture the escalation of the attack and the increasing set of solutions relevant to resolving the attack. For each phase of the attack, the available solutions are verified, restricting the overall set of solutions for the SAAF controller to select, and deploy. Finally we provide scalability measures in regards to the verification of access control models at run-time.
4.1 Scenario Setup
To simulate the insider attack, we deploy an RBAC authorisation infrastructure containing an LDAP directory with several users, a PERMIS authorisation service with an access control policy, and a SAAF controller. We refer to this deployment as a self-adaptive authorisation infrastructure and is based on Figure 3. The authorisation infrastructure’s state of access (pre-adaptation) is identified in Figure 6. At deployment-time, 8 users are active, with assigned roles held in the LDAP directory. The PERMIS authorisation service has one active access control policy, which states users with the role Supervisor, Researcher and Administrator can access the ElectronicLibrary_GetDoc resource. Note in this case, multiple roles have access to the same permission expressed in the PERMIS access control policy.
The properties of the chemical company case suggest a long term attack, whereby a single user downloaded a high volume of documents over a period of 4 months. In addition, the detection of the attack suggests it was made through calculating the deviation of the attacker’s historic usage of the ElectronicLibrary to other users, where the attacker’s usage was 15 times greater [13]. For the purpose of the paper, we scale down the attack and simulate usage of the ElectronicLibrary within a period of 4 hours (as opposed to the 4 months in which the attack was conducted), and instead of 22,000 documents downloaded, we assume 240. We also assume that the acceptable number of downloaded documents within that period of 4 hours is 16, which is 15 times less than 240.
4.2 Deployment
The self-adaptive authorisation infrastructure is hosted across two virtual machines, each with 1024MB of RAM and running Ubuntu 12.04.3 LTS. The virtual machines represent an identity service, containing an LDAP directory, and an authorisation service, containing a deployment of PERMIS. The SAAF controller is also deployed on the authorisation service machine, where it is best suited to managing PERMIS access control policies. Finally, the existence of the ElectronicLibrary is simulated via access requests made in the form of HTTP requests from a Windows 7 machine (2GB of RAM). Access is simulated through the use of an automated script, sending access requests to PERMIS, whereby user access rights are evaluated. Each granted request to download a document from the ElectronicLibrary is seen as synonymous with a user downloading a document.
4.3 Application Domain Requirements
The application domain represents the victim organisation (the chemical company), whereby the organisation owns the authorisation infrastructure, its deployed services, the...
SAAF controller, and the protected resources (i.e., ElectronicLibrary). The application domain’s requirements are necessary in governing the extent of adaptation, regardless of what malicious behaviour is detected, and are modelled as rbacDSML scenarios (adaptation constraints) as described in Section 2.2. In these cases, it may be that the chemical company is only willing to risk automated adaptation where only low level workers are impacted. To reflect these concerns, we deploy the following adaptation constraints:
- C1 Administrator role must maintain access to all resources (Role Resource Scenario)
- C2 At least one user must be assigned the Administrator role (User Role Scenario)
- C3 Each resource should be accessible by at least one user (Resource Scenario)
4.4 Identification
The SAAF controller is capable of identifying malicious behaviour within an authorisation infrastructure, either via signature, pattern, or deviation based behaviour rules. Behaviour rules denote pre-defined conditions which represent malicious behaviour within the target authorisation infrastructure. Signature based refers to access or usage of a resource from blacklisted subjects or IP addresses. Pattern based refers to a pattern of usage of access or a resource, conducted by a user over time, for example, the rate of access requests to a resource in a given period of time. Finally, deviation based refers to a user’s pattern of usage in comparison to historical usage of a user or other users, for example, how one user’s activity compares to that of another user with the same role.
Considering the properties of the attack, the SAAF controller is deployed with a single deviation type behaviour rule, whereby should it detect usage of the ElectronicLibrary from users with the role of Researcher as greater than 3 times the frequency of average number of downloads (within the 4 hour interval), malicious behaviour is detected. We assume for the purpose of the experiment that the average number of downloads is considered to be at most 16, as discussed in the adaptation scenario. In addition, to classify severe behaviour, a composite rule is applied [4], which indicates after the deviation rule has been broken multiple times, the behaviour is severe enough to warrant adaptations to policies (which generate greater impact).
4.5 Solutions
The SAAF controller is deployed with a set of solutions, tailorable to detectable attacks. All of the below solutions are considered to be capable in resolving malicious behaviour detected by the deviation type behaviour rule expressed in Section 4.4. These solutions are expressed in XML and parsed into the SAAF controller once initiated. Solution S1 indicates adaptation to the individual, where as, solutions S2 to S5 indicates policy adaptation, impacting many individuals. They remain fixed throughout run-time.
- S1 Remove all roles from <user>
- S2 Remove <permission> from <role>
- S3 Remove all permissions to <resource>
- S4 Remove all permissions from <role>
- S5 Remove all permissions from all roles
4.6 Execution
To demonstrate the flexibility of adaptation and verification, we simulate the properties of the chemical company insider attack as a coordinated attack between 4 users with the Researcher role, with the intent to carry out IP theft against the ElectronicLibrary. There are 4 stages of the attack, capable of demonstrating simple adaptation against individual users, followed by adaptation against access control policies. In each stage a new user is simulated to break the SAAF controller’s behaviour rules, allowing SAAF to identify the malicious behaviour and respond to it accordingly. All but three users of the Researcher role and the one user owning the Administrator role take part in the attack. As each stage is simulated, the number of solutions applicable to the behaviour increases, identifying that the ElectronicLibrary is under persistent attack.
The first stage demonstrates the user Anne breaking the deviation type behaviour rule by downloading a high number of documents at the start of the 4 hour attack period, using her assigned Researcher role. The second and third stage introduce users John and Mary carrying out similar activity to stage one, again within the same 4 hour window and using the Researcher role. Finally, the forth stage simulates the user Bob breaking the same behaviour rule, using his Researcher role. Each stage considers a set of solutions, whereby the set of verified solutions is captured, and the result of the adaptation engine is shown in terms of a selected verified solution.
4.7 Scenario Results
We have simulated the attack over a period of 4 hours, in accordance to the 4 stages described in Section 4.6. A set of solutions \{(S1, S2, S3, S4, S5)\} were deployed in the SAAF controller, relevant to handling the deviation based behaviour rule. The solutions were chosen to demonstrate the verification of invalid and valid RBAC models at runtime. To gain a performance average for the response to each attack stage, the experiment was executed 30 times. For practical reasons, performance averages were obtained from simulating the attack in a reduced attack period of 5 minutes, where adaptation and verification results showed negligible difference to the 4 hour simulation.
Table 1 portrays the 4 stages of attack. In the first two stages, the SAAF controller considers the malicious behaviour to be minor, only identifying solution S1 as a relevant solution. At this point solution S1 has been tailored to the role the user is activating (Researcher), and the resource they are accessing (ElectronicLibrary). In both stages, the tailored solutions result in a verified RBAC model since there is no conflict with the 3 constraints described in Section 4.3. Solution S1, which removes Anne and John’s access rights, thus their ability to access the ElectronicLibrary, is chosen as it is the only valid solution available. The solution is realised by transforming the adapted RBAC model into a LDAP user model, which is then used to update the current state of access rights within the LDAP. The adaptation, from detection to response within the authorisation infrastructure, took an average of 18.70 seconds to complete in the first stage, and a average 10.74 seconds to complete in the second stage. The difference in time is assumed to be as result
of the Java virtual machine warming up, in which both the SAAF controller and verification tool runs on.
Once the third stage of the attack was executed, the SAAF controller identified that there was a continuous malicious activity regarding the role of Researcher, and the resource ElectronicLibrary. As a result, the SAAF controller selects a more severe set of solutions (\{S1, S2, S3, S4, S5\}). In this case, the SAAF controller builds multiple RBAC models in accordance to the tailored solutions, and verifies them using the rbacDSML tool, resulting in solutions S3 and S5 verified as invalid. This is due to the fact that solution S3 removes all access to the ElectronicLibrary, violating adaptation constraints: C1, and C3. The same violation of constraints C1 and C3 occurred when the SAAF controller deactivated all permissions within the RBAC model, for solution S5. Solution S1 is ultimately chosen as the solution with the optimum utility, given the severity of the attack and the solutions available (Section 3.4). This is a result of the SAAF controller calculating that stronger adaptations (S2 and S4) would cause greater impact than allowing the attack to continue, whereas S1 does not, as it only impacts the attacker. As with stage 1 and 2, Mary's access right to the ElectronicLibrary has now been removed, preventing her from further access. The adaptation of stage 3, from detection to response, took a total average of 45.12 seconds. This is due to additional RBAC models undergoing adaption, transformation into a rbacDSML UML model, and verification using the rbacDSML verification tool.
Finally, in the last stage of the attack, the same solutions are identified and verified similarly to stage 3; however, solution S4 is selected. Solution S4 removes all permissions from the Researcher role, preventing any future user with the same role from activating it. The solution is realised by transforming the adapted RBAC model into a new PERMIS model, which is then deployed as a new access control policy. This has a negative consequence on the remaining 3 users with the Researcher role, as they are no longer capable of accessing the ElectronicLibrary. However, the SAAF controller has selected this solution due to the persistent attacks against the ElectronicLibrary. A contributing dimension of utility to this is that in stage 4, there are more malicious users that own the Researcher role when compared to non-malicious users.
4.8 Scalability of Verification
To demonstrate the scalability of verification in terms of RBAC models, we randomly generated models with up to 10000 elements (where an element could be of type subject, role, permission, and constraint scenario). Each model increased in size, and verified on the same environment described in Section 4.2. For consistency, each model generated contained a ratio of 50% subject elements, 15% role elements, 10% permission elements, 10% resource elements, and 15% constraint scenario elements. The verification of each model was repeated 10 times to obtain an average and standard deviation. The scalability results are shown in Figure 7, where as the model size increased, the verification times were shown to follow a linear pattern. Note that these performance measures only capture the time it takes to complete a verification cycle, and does not represent a complete adaptation cycle (as shown in Table 1).
4.9 Discussion
The results have enabled us to demonstrate the verification of RBAC models, which has prevented invalid tailored solutions from being deployed in the target authorisation infrastructure. In addition, we have shown the escalation of attack to be met with the verification and application of stronger solutions, ultimately stopping the collaborated attack through an adaptation to the access control policy.
One restriction in our approach is that verification is confined to mandatory constraints that must always be verified per adaptation. In some cases it can be argued that different levels of verification are needed, given the attack or solutions available. For example, given a minor attack on the ElectronicLibrary, the application domain may require a constraint guaranteeing at least one researcher maintains access to the resource. However, should the attack continue and becomes severe, the application domain may require that the constraint is no longer applicable since the ElectronicLibrary has suffered a severe attack. One solution to this is to classify identified attacks against available constraints, indicating which constraints should be verified per attack (in addition to mandatory constraints).
In regards to performance, solution verification is a resource intensive operation, and as a result, it takes longer when processing multiple solutions. As SAAF serialises the solution analysis when reacting to attacks, the set of solutions applicable to each attack can be verified in parallel (as each solution is independent of one another).
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Anne</td>
<td>S1</td>
<td>S1</td>
<td>S1</td>
<td>18.70</td>
<td>1.11</td>
</tr>
<tr>
<td>2</td>
<td>John</td>
<td>S1</td>
<td>S1</td>
<td>S1</td>
<td>10.74</td>
<td>0.64</td>
</tr>
<tr>
<td>3</td>
<td>Mary</td>
<td>S1, S2, S3, S4, S5</td>
<td>S1, S2, S4</td>
<td>S1</td>
<td>45.12</td>
<td>1.30</td>
</tr>
<tr>
<td>4</td>
<td>Bob</td>
<td>S1, S2, S3, S4, S5</td>
<td>S1, S2, S4</td>
<td>S4</td>
<td>44.79</td>
<td>1.31</td>
</tr>
</tbody>
</table>
Figure 7: Scalability of model verification
5. RELATED WORK
5.1 Access Control and Verification
Role Based Access Control (RBAC) is arguably one of the most researched access control models; however, recently, Attribute-Based Access Control (ABAC) models [40] have been receiving more interest from the research community. Sandhu argues that the move from role-based to attribute-based access control opens up new possibilities, as well as new research challenges [35]. RBAC models can be represented using ABAC models, where the roles are defined as attributes. One of the best known ABAC policy languages, XACML [31], features a profile to represent RBAC models [32]. The focus of this paper is on RBAC, both for its standardised and well-understood model, and for its support by PERMIS.
The conformance of XACML policies to designers’ requirements has received a lot of interest. Fisler et al. transform access control policies into decision diagrams that can be queried [17]; Hughes and Bultan use a SAT solver on XACML policies to verify that the policy conforms to some properties [19]. Gofman et al. verify properties of RBAC and ARBAC (another RBAC extension) models using RBAC-PAT [18]. The Ponder2 framework also provides policy verification capabilities, using event calculus [6].
Many approaches have also been proposed that allow one to model authorisation policies, and sometimes verify them against requirements, as part of a Model-Driven Engineering approach. rbacDSML is one of them. A few of these approaches use UML profiles to represent RBAC policies, and often query then using OCL constraints; they include UMLsec [22], SecureUML [8], Shin and Ahn’s approach [2], and Cirit and Buzluca’s UML profile [15]. Kim et al. represent RBAC policies as UML patterns that are then instantiated on a model, using UML template diagrams [24]. Song et al. use Aspect-Oriented Modelling to represent RBAC policies as crosscutting concerns in a UML model, and provides support for verifying properties that the model should satisfy [38]. Sun et al. translate UML models to Alloy in order to verify properties using a SAT solver [39]. Finally, Sohr et al. concentrate on the satisfaction of constraints such as separation of duty, using OCL [37], as well as dynamic, time-based constraints [26], using a domain-specific modelling language (DSML) for RBAC. rbacDSML was very well suited for this paper, because of its open source implementation, and because we were able to define a partial rbacDSML model to represent the application’s adaptation constraints, and to merge it at runtime with the rest of the RBAC model in order to form and verify a complete rbacDSML model.
5.2 Self-Adaptive Access Control
To the best of our knowledge model driven approaches have not been used to enable adaptation of authorisation infrastructures, specifically in the establishment of security concerns and assignment of access to better protect an organisation’s resources. The concept of modelling authorisation, specifically security, is not new [7]. System designs and security concerns can be modelled together, to create authorisation infrastructures. The use of metamodels, in this paper, can be likened to efforts in security requirements engineering, whereby models of systems are expressed to refine and generate security policies [16]. However, in our specific case the metamodel is used to aid runtime generation of a model view of an authorisation infrastructure, relating existing models of security concerns and subject privileges.
The concept of utilising model driven approaches [11] to enable self-* properties is not new. Works such as [34] outline a model driven approach in enabling self-managing systems, particularly at an architectural level, whereby the role of models is discussed both during design time and runtime of a system. Whilst our work applies model driven approaches in order to achieve self-adaptive properties, the purpose of our models differ. Rather than modelling architectural state and properties, we focus on modelling volatile parameters of structural components that control component execution. For example, modelling a security concern used to govern authorisation decisions executed by an authorisation service.
6. CONCLUSIONS
In this paper, we have presented the first model-driven self-adaptive approach to access control, capable of handling multiple insider attacks whilst maintaining user-defined application constraints. Assurances that the adaptations to be deployed are valid are obtained through the usage of models, model transformation, and model verification at runtime. We describe the generation of implementation specific models of multiple deployed systems that implement different aspects of access control. These implementation specific models are transformed into a single model of access control, whereby adaptation is carried out and evaluated using model verification. We have demonstrated our approach by deploying a self-adaptive authorisation infrastructure in which we simulate and respond to a well documented case of insider attack against a chemical research company [13], whilst considering several application constraints. The simulation has captured the process of model verification, whereby only verified models are used to adapt the current state of access control within the authorisation infrastructure.
From the evaluations, we have shown that we are able to prevent the simulated attack from continuing, and handling the attack in a more timely manner if compared with approaches that rely on human administrators. There are some limitations with this approach, notably that model verification at run-time is a time consuming operation. The time it takes for our self-adaptive authorisation infrastructure to respond to attack is dependent on the number of solutions that must be verified, as each insider attack could be resolved by multiple solutions. Despite the time it takes to verify adaptations, we consider this to be faster than traditional human based approaches.
Our future work involves the further development of the Self-Adaptive Authorisation Framework (SAAF), specifically, with an aim to improve the performance of verification. As we have currently adopted a brute force approach to verifying all applicable solutions to an attack, we aim to improve upon this by using change impact analysis to only verify a subset of the adapted access control model, depending on the changes made compared to the previous model.
7. ACKNOWLEDGEMENTS
Co-financed by the Foundation for Science and Technology via project CMU-PT/ELE/0030/2009 and by FEDER via the “Programa Operacional Factores de Competitivi-
8. REFERENCES
[33] OMG. Meta Object Facility (MOF) 2.0.
|
{"Source-Url": "https://kar.kent.ac.uk/42968/1/84_seams14_camera_ready.pdf", "len_cl100k_base": 10045, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 35629, "total-output-tokens": 13226, "length": "2e13", "weborganizer": {"__label__adult": 0.0004837512969970703, "__label__art_design": 0.0007290840148925781, "__label__crime_law": 0.0024967193603515625, "__label__education_jobs": 0.002689361572265625, "__label__entertainment": 0.0001220107078552246, "__label__fashion_beauty": 0.00027561187744140625, "__label__finance_business": 0.0009150505065917968, "__label__food_dining": 0.0003554821014404297, "__label__games": 0.000888824462890625, "__label__hardware": 0.0012216567993164062, "__label__health": 0.0009899139404296875, "__label__history": 0.0004906654357910156, "__label__home_hobbies": 0.0001531839370727539, "__label__industrial": 0.0007214546203613281, "__label__literature": 0.0004839897155761719, "__label__politics": 0.0006146430969238281, "__label__religion": 0.00044417381286621094, "__label__science_tech": 0.2403564453125, "__label__social_life": 0.00020170211791992188, "__label__software": 0.035186767578125, "__label__software_dev": 0.708984375, "__label__sports_fitness": 0.00024580955505371094, "__label__transportation": 0.0005016326904296875, "__label__travel": 0.00021851062774658203}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58364, 0.02932]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58364, 0.13326]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58364, 0.91098]], "google_gemma-3-12b-it_contains_pii": [[0, 1322, false], [1322, 5753, null], [5753, 11481, null], [11481, 17802, null], [17802, 23560, null], [23560, 26209, null], [26209, 31775, null], [31775, 38175, null], [38175, 43945, null], [43945, 50605, null], [50605, 58364, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1322, true], [1322, 5753, null], [5753, 11481, null], [11481, 17802, null], [17802, 23560, null], [23560, 26209, null], [26209, 31775, null], [31775, 38175, null], [38175, 43945, null], [43945, 50605, null], [50605, 58364, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58364, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58364, null]], "pdf_page_numbers": [[0, 1322, 1], [1322, 5753, 2], [5753, 11481, 3], [11481, 17802, 4], [17802, 23560, 5], [23560, 26209, 6], [26209, 31775, 7], [31775, 38175, 8], [38175, 43945, 9], [43945, 50605, 10], [50605, 58364, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58364, 0.02575]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
862b20c3ea94172371a84a0fa4c2524c5dba0a22
|
[REMOVED]
|
{"len_cl100k_base": 13577, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 54259, "total-output-tokens": 19465, "length": "2e13", "weborganizer": {"__label__adult": 0.0003771781921386719, "__label__art_design": 0.0007634162902832031, "__label__crime_law": 0.00030803680419921875, "__label__education_jobs": 0.0019588470458984375, "__label__entertainment": 0.0002605915069580078, "__label__fashion_beauty": 0.00020635128021240232, "__label__finance_business": 0.000949382781982422, "__label__food_dining": 0.0003943443298339844, "__label__games": 0.0009593963623046876, "__label__hardware": 0.00249481201171875, "__label__health": 0.000553131103515625, "__label__history": 0.0005602836608886719, "__label__home_hobbies": 0.00014925003051757812, "__label__industrial": 0.0005497932434082031, "__label__literature": 0.0005159378051757812, "__label__politics": 0.0004296302795410156, "__label__religion": 0.0005321502685546875, "__label__science_tech": 0.26171875, "__label__social_life": 0.00013434886932373047, "__label__software": 0.03277587890625, "__label__software_dev": 0.6923828125, "__label__sports_fitness": 0.00020372867584228516, "__label__transportation": 0.0005555152893066406, "__label__travel": 0.00025153160095214844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 78636, 0.03479]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 78636, 0.28533]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 78636, 0.8457]], "google_gemma-3-12b-it_contains_pii": [[0, 3801, false], [3801, 9409, null], [9409, 14029, null], [14029, 17217, null], [17217, 22768, null], [22768, 28468, null], [28468, 34837, null], [34837, 40794, null], [40794, 46931, null], [46931, 50427, null], [50427, 54103, null], [54103, 59487, null], [59487, 63749, null], [63749, 68549, null], [68549, 73322, null], [73322, 76736, null], [76736, 78636, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3801, true], [3801, 9409, null], [9409, 14029, null], [14029, 17217, null], [17217, 22768, null], [22768, 28468, null], [28468, 34837, null], [34837, 40794, null], [40794, 46931, null], [46931, 50427, null], [50427, 54103, null], [54103, 59487, null], [59487, 63749, null], [63749, 68549, null], [68549, 73322, null], [73322, 76736, null], [76736, 78636, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 78636, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 78636, null]], "pdf_page_numbers": [[0, 3801, 1], [3801, 9409, 2], [9409, 14029, 3], [14029, 17217, 4], [17217, 22768, 5], [22768, 28468, 6], [28468, 34837, 7], [34837, 40794, 8], [40794, 46931, 9], [46931, 50427, 10], [50427, 54103, 11], [54103, 59487, 12], [59487, 63749, 13], [63749, 68549, 14], [68549, 73322, 15], [73322, 76736, 16], [76736, 78636, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 78636, 0.12355]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
abff3d5a25633e49a32d19b1090c21f9fa405e16
|
<table>
<thead>
<tr>
<th>Title</th>
<th>Capturing propagation of infected program states</th>
</tr>
</thead>
<tbody>
<tr>
<td>Author(s)</td>
<td>Zhang, Z; Chan, WK; Tse, TH; Jiang, B; Wang, X</td>
</tr>
<tr>
<td>Citation</td>
<td>Esec-Fse'09 - Proceedings Of The Joint 12Th European Software Engineering Conference And 17Th Acm Sigsoft Symposium On The Foundations Of Software Engineering, 2009, p. 43-52</td>
</tr>
<tr>
<td>Issued Date</td>
<td>2009</td>
</tr>
<tr>
<td>URL</td>
<td><a href="http://hdl.handle.net/10722/93325">http://hdl.handle.net/10722/93325</a></td>
</tr>
<tr>
<td>Rights</td>
<td>This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.; © ACM, 2009. This is the author's version of the work. It is posted here by permission of ACM for your personal use. Not for redistribution. The definitive version was published in the Proceedings of the 7th Joint Meeting of the European Software Engineering Conference and the ACM SIGSOFT Symposium on the Foundations of Software Engineering (ESEC 2009/FSE-17), Amsterdam, The Netherlands, August 24-28, 2009, p. 43-52.</td>
</tr>
</tbody>
</table>
Capturing Propagation of Infected Program States
Zhenyu Zhang
The University of Hong Kong
Pokfulam, Hong Kong
zyzhang@cs.hku.hk
W. K. Chan†
City University of Hong Kong
Tat Chee Avenue, Hong Kong
wkchan@cs.cityu.edu.hk
T. H. Tse
The University of Hong Kong
Pokfulam, Hong Kong
thtse@cs.hku.hk
Bo Jiang
The University of Hong Kong
Pokfulam, Hong Kong
bjiang@cs.hku.hk
Xinming Wang
Hong Kong University of Science and Technology
Clear Water Bay, Hong Kong
rubin@cse.ust.hk
ABSTRACT
Coverage-based fault-localization techniques find the fault-related positions in programs by comparing the execution statistics of passed executions and failed executions. They assess the fault suspiciousness of individual program entities and rank the statements in descending order of their suspiciousness scores to help identify faults in programs. However, many such techniques focus on assessing the suspiciousness of individual program entities but ignore the propagation of infected program states among them. In this paper, we use edge profiles to represent passed executions and failed executions, contrast them to model how each basic block contributes to failures by abstractly propagating infected program states to its adjacent basic blocks through control flow edges. We assess the suspiciousness of the infected program states propagated through each edge, associate basic blocks with edges via such propagation of infected program states, calculate suspiciousness scores for each basic block, and finally synthesize a ranked list of statements to facilitate the identification of program faults.
We conduct a controlled experiment to compare the effectiveness of existing representative techniques with ours using standard benchmarks. The results are promising.
Categories and Subject Descriptors
D.2.5 [Software Engineering]: Testing and Debugging — Debugging aids
General Terms: Experimentation, Verification
Keywords
Fault localization, edge profile, basic block, control flow edge
1. INTRODUCTION
Coverage-based fault-localization (CBFL) techniques [2][8][15][21][23][24] have been proposed to support software debugging. They usually contrast the program spectra information [14] (such as execution statistics) between passed executions and failed executions to compute the fault suspiciousness [24] of individual program entities (such as statements [15], branches [21], and predicates [18]), and construct a list of program entities in descending order of their fault suspiciousness. Developers may then follow the suggested list to locate faults. Empirical studies [2][15][18][19] show that CBFL techniques can be effective in guiding programmers to examine code and locate faults.
During program execution, a fault in a program statement may infect a program state, and yet the execution may further propagate the infected program states [9][22] a long way before it may finally manifest failures [23]. Moreover, even if every failed execution may execute a particular statement, this statement is not necessarily the root cause of the failure (that is, the fault that directly leads to the failure) [9].
Suppose, for instance that a particular statement \( S \) on a branch \( B \) always sets up a null pointer variable. Suppose further that this pointer variable will not be used in any execution to invoke any function, until another faraway (in the sense of control dependence [5] or data dependence) statement \( S' \) on a branch \( B' \) has been reached, which will crash the program. If \( S \) is also exercised in many other executions that do not show any failure, \( S \) or its directly connected branches cannot effectively be pinpointed as suspicious. In this scenario, existing CBFL techniques such as Tarantula [15] or SBI [24] will rank \( S' \) as more suspicious than \( S \). Indeed, in the above scenario, exercising \( B' \) that determines the execution of \( S' \) always leads to a failure [24]. Thus, the branch technique proposed in [24], for example, will rank \( B' \) as more suspicious than \( B \), which in fact is directly connected to the first statement \( S \). The use of data flow analysis may reveal the usage of
the null pointer and help evaluate the suspiciousness of $S$, $S'$, $B$, and $B'$. However, data flow profiling is expensive [14][21].
A way out is to abstract a concrete program state as a control flow branch, and abstract the propagation of fault suspiciousness of these concrete program states by a “transfer function” of the fault suspiciousness of one branch or statement to other branches or statements. On one hand, existing techniques work at the individual program entity level and assess the fault suspiciousness of program entities separately. On the other hand, the transfer of fault suspiciousness of one program entity to another will change the fault suspiciousness of the latter. In the presence of loops, finding a stable propagation is non-trivial. Moreover, even if a stable propagation can be found, a direct implementation of such a propagation-based technique may indicate that the technique requires many rounds of iterations, which unfortunately are computationally expensive. We propose a steady and efficient propagation-based technique to crash. On the contrary, a passed execution is a program execution that shows no failure.
We abstract a given program as a control flow graph (CFG), sample a program execution as an edge profile [3], which indicates which edges of the CFG have been traversed during the execution, and quantifies every change of program state over an edge with the number of executions of the edge. We then compute a pair of mean edge profiles: the mean pass profile for all sampled passed executions, and the mean failed profile for all sampled failed executions. They capture abstractly the central tendency of the program state in a passed execution and that in a failed execution, respectively. For each edge, we contrast such a state abstraction in the mean pass profile with that in the mean failed profile to assess the fault suspiciousness of the edge. In our model, to backtrack how much every basic block [3] contributes to the observed program failures, we set up a system of linear algebraic equations to express the propagation of the suspiciousness scores of a basic block to its predecessor block(s) via directly connected control flow edges — for each edge, we split a fraction of the suspiciousness score to be propagated to a predecessor basic block.
Our model always constructs homogeneous equations and ensures that the number of equations is the same as the number of variables. Such a constructed equation set satisfies a necessary condition of being solvable by standard mathematics techniques such as Gaussian elimination [29]. By solving the set of equations, our technique obtains the suspiciousness score for each basic block. We finally rank the basic blocks in descending order of their suspiciousness scores, and assign a rank for each statement. We conduct controlled experiments to compare the effectiveness of existing representative techniques with ours on four real-life medium-sized programs. The empirical results show that our technique can be more effective than peer techniques.
The main contribution of this work is twofold: (i) To the best of our knowledge, the work is the first that integrates the propagation of program states to CBFL techniques. (ii) We use four real-life medium-sized programs flex, grep, gzip, and sed to conduct experiments on our technique and compare them with five other
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>if (block_queue) {</td>
<td>$e_1$</td>
<td>$b_1$</td>
<td>0.50</td>
<td>0.29</td>
<td>0.71</td>
<td>0.71</td>
<td>0.11</td>
</tr>
<tr>
<td>$count = block_queue->mem_count + 1;</td>
<td>$e_2$</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>n = (int) (count*ratio);</td>
<td>$e_3$</td>
<td>$b_2$</td>
<td>0.71</td>
<td>0.50</td>
<td>0.71</td>
<td>0.71</td>
<td>1.11</td>
</tr>
<tr>
<td>proc = find_nth(block_queue, n);</td>
<td>$e_4$</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>if (proc) {</td>
<td>$e_5$</td>
<td>$b_3$</td>
<td>1.00</td>
<td>3.00</td>
<td>0.71</td>
<td>0.71</td>
<td>1.00</td>
</tr>
<tr>
<td>block_queue= del_el(block_queue, proc);</td>
<td>$e_6$</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>prio = proc->priority;</td>
<td>$e_7$</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>prio_queue[prio] = append_el(prio_queue[prio], proc);</td>
<td>$e_8$</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>} // next basic block</td>
<td>$e_9$</td>
<td>$b_4$</td>
<td>0.50</td>
<td>0.29</td>
<td>0.71</td>
<td>0.71</td>
<td>0.11</td>
</tr>
</tbody>
</table>
Control Flow Graph (CFG) for the code excerpt above:
![CFG Diagram]
(We add a dummy block $b_4$ containing statement $s_9$, and an edge $e_6$ to make a complete CFG.)
| Edge | | | | | | | |
|------|------|------|------|------|------|------|
| | $e_1$ | $e_2$ | $e_3$ | $e_4$ | $e_5$ | $e_6$ |
| susp. | 0.53 | 0.71 | 0.00 | 0.11 | 0.41 | N/A |
| rank | 0.00 | 0.43 | 1.00 | 1.00 | 0.11 | 1.00 |
% of code examined according to the ranking of statements
<table>
<thead>
<tr>
<th>Class</th>
<th>P</th>
<th>P</th>
<th>F</th>
<th>P</th>
<th>F</th>
<th>P</th>
</tr>
</thead>
<tbody>
<tr>
<td>78%</td>
<td>78%</td>
<td>78%</td>
<td>100%</td>
<td>44%</td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Figure 1: Faulty version v2 of program schedule and fault localization comparison.
techniques, namely Tarantula, SBI, Jaccard, CBI, and SOBER. The empirical results show that our technique is promising.
The rest of this paper is organized as follows: Section 2 shows a motivating example. Section 3 presents our technique. Section 4 presents further discussion on our technique, followed by an experimental evaluation in Section 5 and a literature review in Section 6. Section 7 concludes the paper.
2. MOTIVATING EXAMPLE
This section shows an example on how the modeling of propagation of infected program states via control flow edges helps locate faults effectively.
Figure 1 shows a code excerpt from the faulty version v2 of the program schedule (from SIR [10]). The code excerpt manages a process queue. It first calculates the index of a target process, and then moves the target process among priority queues. We seed an extra “+1” operation fault into statement s2 in Figure 1. It may cause the program to select an incorrect operation for subsequent processing, which will lead to a failure.
This code excerpt contains two “if” statements (s1 and s5), which divide the code excerpt into three basic blocks [5] (namely, b1, b2, and b3). The basic block b1 contains only one statement s1. The result of evaluating “block queue” in s1 determines whether the statements s2 to s8 are skipped. The basic blocks b2 contains statements s2, s3, s4, and s5. The basic block b3 contains statements s6, s7, and s8. We also depict the code excerpt as a control flow graph (CFG) in Figure 1. In this CFG, each rectangular box represents a basic block and each arrow represents a control flow edge that connects two basic blocks. For example, e2 indicates that the decision in s1 has been evaluated to be true in an execution, so it transits from b1 to b2. Since the fault lies in b2, we use a weighted border to highlight the rectangular box b2. Note that we add a dummy block b4 (as a dashed rectangular box) and an edge e6 (as a dashed arrow) to make this CFG more comprehensible.
We examine the program logic, and observe that many failures are caused by the execution of b2 followed by b3, rather than merely executing b2 without executing b3. Even if b2 is executed and results in some infected program state, skipping b3 will not alter the priority queue, and thus the effect of the fault at s2 is less likely to be observed through subsequent program execution. On the other hand, executing b2 followed by b3 means that an infected program state (such as incorrect values for the variables count, n, or proc) at b2 is successfully propagated to b3 through the edge e4. Since previous studies suggest the comparison of execution statistics to assess the suspiciousness scores of statements, they will be more likely to result in a wrong decision — b3 will appear to be more suspicious than b2. The following serves as an illustration.
In this example, we use seven test cases (dubbed t1 to t7). Their statement and edge execution details are shown in Figure 1. A cell with the “●” notation indicates that the corresponding statement is exercised (or an edge is traversed) in the corresponding test execution. For instance, let us take the first test case t1 (8 successful one, referred to as “passed”). During its execution, the basic blocks b1, b2, and b4 are exercised; moreover, the control flow edges e1, e2, and e5 are traversed. Other test cases can be interpreted similarly. The passed/fail status of each test case is shown in the “Pass/Fail status” row. We apply Tarantula [24], Jaccard [1], and SBI [24] to compute the suspiciousness score of every statement, and rank statements in descending order of their scores. Presuming that the programmer may check each statement according to their ranks until reaching the fault [15][24], we thus compute the effort of code examination to locate this fault [15][24]. We show their effectiveness in the “sus.” and “rank” columns, and the row “% of code examined according to the ranking of statements” of Figure 1. We observe that b3, rather than b2, is deemed to be the most suspicious basic block if we apply Tarantula or SBI. When applying Jaccard, b2 and b3 are equally deemed to be the most suspicious basic blocks. As a result, the fault cannot be effectively located by any of these techniques. To locate the fault, each examined technique needs to examine 78% of the code.
Intuitively, the execution of b3 may lead to a failure, and yet it is not the fault. On the other hand, b2 contains the fault, but its execution does not lead to a failure as often as b3. Since existing techniques find the suspicious program entities that correlate to failures, they give higher ranks to those statements (such as b3) whose executions frequently lead to failures, but give lower ranks to those statements (such as b2) whose executions less often lead to failures. If we always separately assess the fault suspiciousness of individual statements (such as b2 and b3) and ignore their relations, this problem may hardly be solved.
Since executing an edge can be regarded as executing both the two basic blocks connected by the edge, do edge-oriented techniques somehow capture the relationships among statements and perform effectively on this example? We follow [21] to adopt hr, an edge-oriented technique (which we will refer to as Branch in this paper) to work on this example. Branch assesses the suspiciousness scores of control flow edges (say, e1 and e2), and then associate their suspiciousness scores with statements that are directly connected (in sense of incoming edges or outgoing edges). Branch first ranks e2 and e4 as the most suspicious edges (both having a suspiciousness score of 0.71). In a program execution, traversing e2 means to enter the true branch of s1 followed by executing b2, and traversing e4 means having executed b2 and will continue to execute b3. We observe that executing b2 generates infected program states (on variables count, n, and proc), which propagate to b3 through e4. We further observe that these two highly ranked edges precisely pinpoint the fault location. When associating edges to statements, the rules in Branch only propagate the edge suspiciousness to those statements within the same block as the conditional statement for the edge. However, a fault may be several blocks away from the edge and the loop construct may even feedback a faulty program state. For this example, Branch assigns identical suspiciousness scores to all statements and they cannot be distinguished from one another. As a result, 100% code examination effort is needed to locate the fault. Since the core of Branch is built on top of Ochiai [1], we have iteratively replaced this core part of Branch by Tarantula, Jaccard, and SBI. However, the fault-localization effectiveness results are still unsatisfactory (100% code to be examined). In practice, the propagation of infected program states may take a long way, such as a sequence of edges, before it may finally result in failures. We need a means to transfer over the edges information about infected program states and failures.
1 In this paper, we use the term SBI to denote Yu et al.’s approach [24] of applying Liblit et al.’s work CBI [18] at statement level. At the same time, we still keep the term CBI when referring to the original technique in [18].
3. OUR MODEL
3.1 Problem Settings
Let $P$ be a faulty program, $T = \{t_1, t_2, \ldots, t_6\}$ be a set of test cases associated with passed executions, and $T' = \{t'_1, t'_2, \ldots, t'_4\}$ be a set of test cases that are associated with failed executions. In the motivating example, for instance, $P$ is version v2 of schedule, $T = \{t_1, t_2, t_4, t_5, t_7\}$, and $T' = \{t_3, t_6\}$. Similar to existing work (such as [15]), the technique assesses the fault suspiciousness of each statement of $P$ and can also produce a list of statements of $P$ in descending order of the suspiciousness scores.
3.2 Preliminaries
We use $G(P) = (B, E)$ to denote the control flow graph (CFG) [3][5] of the program $P$, where $B = \{b_1, b_2, \ldots, b_n\}$ is the set of basic blocks (blocks for short) of $P$, and $E = \{e_1, e_2, \ldots, e_m\}$ is the set of control flow edges (edges for short) of $P$, in which each edge $e_i$ goes from one block to another (possibly the same block) in $B$. Thus, we sometimes write $e_i$ as $edg(b_{i1}, b_{i2})$ to denote an edge going from $b_{i1}$ to $b_{i2}$: this edge $e_i$ is called the incoming edge of $b_{i2}$ and the outgoing edge of $b_{i1}$. The block $b_{i2}$ is a successor block of $b_{i1}$, and the block $b_{i1}$ is a predecessor block of $b_{i2}$. We further use the notation $edg(\theta, b_1)$ and $edg(b_1, \theta)$ to represent the set of incoming edges and the set of outgoing edges of $b_1$, respectively. In Figure 1, for instance, edges $e4$ and $e5$ are the outgoing edges of block $b2$, and block $b3$ is a successor block of $b2$ with respect to edge $e4$; $edg(b3, \theta) = \{e6\}$ is the set of outgoing edges of block $b3$, and $edg(\theta, b3) = \{e4\}$ is the set of incoming edges of block $b3$.
An edge is said to have been covered by a program execution if it is traversed at least once. For every program execution of $P$, whether an edge is covered in $E$ can be represented by an edge profile. Suppose $t_i$ is a test case. We denote the edge profile for $t_i$ by $P(t_i) = (\theta(e_1, t_i), \theta(e_2, t_i), \ldots, \theta(e_m, t_i))$, in which $\theta(e_i, t_i)$ means whether the edge $e_i$ is covered in the corresponding program execution of $t_i$. In particular, $\theta(e_i, t_i) = 1$ if $e_i$ is covered by the execution, whereas $\theta(e_i, t_i) = 0$ if $e_i$ is not covered. Take the motivating example in Figure 1 for illustration. The edge profile for test case $t_1$ is $P(t_1) = (\theta(e1, t_1), \theta(e2, t_1), \theta(e3, t_1), \theta(e4, t_1), \theta(e5, t_1), \theta(e6, t_1)) = (1, 1, 0, 0, 1, 0)$.
3.3 CP: Our Fault-Localization Model
We introduce our fault-localization model in this section.
A program execution passing through an edge indicates that the related program states have propagated via the edge. Therefore, we abstractly model a program state in a program execution as related program states have propagated via the edge. Therefore, we abstractly model a program state in a program execution as
\[ \text{propagation via each edge, and use such a ratio to determine the fraction of the suspiciousness score of a block propagating to a predecessor block via that edge. We use backward propagation to align with the idea of backtracking from a failure to the root cause.}
For each block, $CP$ uses a linear algebraic equation to express its suspiciousness score by summing up such fractions of suspiciousness scores of successor blocks of the given block. Such an equation is constructed using equation (5) or (6), depending on whether the block is a normal or exit block. By solving the set of equations (by Gaussian elimination), we obtain the suspiciousness score for each block involved.
As presented in Section 3.3.3, $CP$ ranks all blocks in descending order of their suspiciousness scores, then assigns a rank to each statement, and produces a ranked list of statements by sorting them in descending order of their suspiciousness scores.
3.3.1 Calculating the Edge Suspiciousness Score
In Section 2, we have shown that edges can provide useful correlation information for failures. However, the size of $T$ may be very different from that of $T'$. To compare the sets of edge profiles for $T$ with those for $T'$, we propose to compare their arithmetic means (that is, central tendencies).
If an edge is never traversed in any execution, it is irrelevant to the observed failures. There is no need to compute the propagation of suspicious program states through that edge. We thus exclude them from our calculation model in Sections 3.3.1 and 3.3.2.
In our model, we use the notation $P' = (\theta'(e_1), \theta'(e_2), \ldots, \theta'(e_m))$ to denote the mean edge profile for $T$, and $P'' = (\theta''(e_1), \theta''(e_2), \ldots, \theta''(e_m))$ for $T'$, where $\theta'(e_i)$ and $\theta''(e_i)$ for $i = 1$ to $m$ are calculated by:
\[ \theta'(e_i) = \frac{1}{u} \sum_{t_k \in T} [\theta(e_i, t_k)]; \quad \theta''(e_i) = \frac{1}{v} \sum_{t_j \in T'} [\theta(e_i, t_j)]. \]
Note that the variables $u$ and $v$ in equation (1) represent the total numbers of passed and failed test cases, respectively. Intuitively, $\theta'(e_i)$ and $\theta''(e_i)$ stand for the probabilities of an edge being exercised in a passed execution and failed execution, respectively, over the given test set. For example, $\theta'(e4) = (\theta(e4, t3) + \theta(e4, t6)) / 2 = (1 + 0) / 2 = 0.5$ and, similarly, $\theta''(e4) = 0$.
**Edge suspiciousness calculation.** We calculate the suspiciousness score of any given edge $e_i$ using the equation
\[ \theta^s(e_i) = \frac{\theta''(e_i) - \theta'(e_i)}{\theta''(e_i) + \theta'(e_i)} \]
which contrasts the difference between the two mean edge profiles. Intuitively, $\theta^s(e_i)$ models the (normalized) difference between the probability of $e_i$ being traversed in an average passed execution and the probability of an average failed execution. When $\theta^s(e_i)$ is positive, it reflects that the probability of edge $e_i$ being covered in $P'$ is larger than that in $P$. Since such an edge is more frequently exercised in failed executions than in passed executions, it may be more likely to be related to a fault. When $\theta^s(e_i) = 0$, the edge $e_i$ has identical probabilities of being covered in $P'$ and $P$. Such an edge is deemed to be less likely to be related to a fault than an edge having a positive suspiciousness score. When $\theta^s(e_i)$ is negative, it means that $e_i$ is less frequently executed in $P$ than in $P'$.
In short, for an edge $e_i$, the higher the values of $\theta^s(e_i)$, the more suspicious the edge $e_i$ is deemed to be, and the more suspicious the propagation of program states via $e_i$ is deemed to be.
To understand why equation (2) is useful for ranking edges according to their suspiciousness, let \( \text{Prob}(e_i) \) denote the (unknown) probability that the propagation of infected program states via \( e_i \) will cause a failure. The proof in Appendix A shows that
\[
\text{Prob}(e_i) = \frac{v \cdot \theta^e(e_i)}{v \cdot \theta^e(e_i) + u \cdot \theta^e(e_i)}
\]
(3)
is the best estimate for this probability. It is also proved in Appendix B that, no matter whether equation (2) or (3) is chosen as the ratio of the suspiciousness of \( e_i \) to that of \( e_j \) (other than examining all three blocks at the same time). In the exception case where a block may have no successor. For a block that crashes, the program execution may leave the block, or cease any further branch transitions after executing the block. In our model, if a block is found not to transit the control to other successor blocks in the same CFG (as in the case of a return statement or callback function), we call it an exit block. Since exit blocks have no successor block, we do not apply equation (5) to calculate its suspiciousness score. Instead, we use the equation
\[
\text{BR}(b_j) = \sum_{\forall \text{edge}(b_j)} \left[ \text{BR}(b_k) \cdot W(b_j, b_k) \right]
\]
(5)
Let us take the motivating example for illustration: \( b_2 \) has two outgoing edges connecting to two successor blocks \( b_3 \) and \( b_4 \), respectively. Its suspiciousness score \( \text{BR}(b_2) \) is, therefore, calculated as \( \text{BR}(b_3) \cdot W(b_2, b_3) + \text{BR}(b_4) \cdot W(b_2, b_4) \). The propagation rate for \( W(b_2, b_3) \) is calculated as \( \theta^e(e_3) / \theta^e(e_5) = 1.00 / 1.00 = 1 \). The propagation rate for \( W(b_2, b_3) \) is calculated as \( \theta^e(e_4) = 1.00 / 1.00 = 1 \).
Handling exception cases. We normally calculate the suspiciousness score of a block via its successor blocks. Let us consider an exception case where a block may have no successor. For a block containing, say, a return, break, or exit() function call, or for a block that crashes, the program execution may leave the block, or cease any further branch transitions after executing the block. In our model, if a block is found not to transit the control to other successor blocks in the same CFG (as in the case of a return statement or callback function), we call it an exit block. Since exit blocks have no successor block, we do not apply equation (5) to calculate its suspiciousness score. Instead, we use the equation
\[
\text{BR}(b_j) = \sum_{\forall \text{edge}(b_j)} \left[ \text{BR}(b_k) \cdot W(b_j, b_k) \right]
\]
(6)
which sums the suspiciousness scores of all the incoming edges to calculate the suspiciousness score of the exit block. Consider the motivating example again. There is no successor for \( b_1 \) in the CFG in Figure 1. Hence, \( \text{BR}(b_3) = \theta^e(e_3) = -1.00 + 0.11 + 0.00 = 0.11 \). (We should add that there are alternative ways to model the suspiciousness score for an exit block, such as using the formulas for block-level CBFL techniques.)
We have constructed an equation of \( \text{BR}(b_j) \) for every block \( b_j \) (including exit blocks). In other words, we have set up an equation set containing \( n \) homogenous equations (one for each block) and \( n \) variables as the left-hand side of each equation (one for each suspiciousness score of that block). In such a case, the equation set satisfies a necessary condition of being solvable by existing efficient algorithms for solving equation sets (such as Gaussian elimination [29], which we also adopt in the experiment in Section 5).
In the motivating example, we can set up an equation set \( \{ \text{BR}(b_4) = 0.11, \text{BR}(b_3) = 9 \times \text{BR}(b_4), \text{BR}(b_2) = \text{BR}(b_4) + \text{BR}(b_3), \text{BR}(b_1) = -9 \times \text{BR}(b_4) + \text{BR}(b_2) \} \). We can solve it to give \( \text{BR}(b_4) = 0.11, \text{BR}(b_3) = 1.00, \text{BR}(b_2) = 1.11, \) and \( \text{BR}(b_1) = 0.11. \)
3.3.3 Synthesizing a Ranked List of Statements
After obtaining the suspiciousness score for every block, we further group those statements not in any block (such as global assignment statements) into a new block, and give it a lower suspiciousness score than that of any other ranked block. We also merge those blocks having identical suspiciousness scores, and produce a ranked list of blocks in descending order of their suspiciousness scores. All the non-executable statements and statements that are not exercised by any given executions are consolidated into one block, which is appended to the end of the ranked list and given the lowest suspiciousness score. Finally, one may assign ranks for statements. Following previous work [15], the rank of a statement is assigned as the sum of total number of statements in its belonging block and the total number of statements in the blocks prior to its belonging block. The CP column of Figure 1 shows the ranks of statements by our method, which only needs 44% code examination effort to locate a fault.
4. DISCUSSIONS
In previous work, a tie-break strategy (see [21][24]) is further employed to optimize the baseline fault-localization techniques. They give a better ranking list when one follows the ranking list to locate faults. However, they do not modify the computed suspicious scores of the program entities by those techniques. Our technique can also be optimized in exactly the same way.
In our technique, we capture the propagation of infected program states via CFG. In fact, other flow-graph representations of program executions, such as program dependency graphs [3] or data flow graphs, may be employed to replace CFG. We do not iteratively show how to adapt each of them in our technique.
The space and time complexity of our technique is analyzed as follows: With the same problem settings (u passed executions, v failed executions, n blocks, and m edges), the space complexity is mainly determined by the space needed to maintain the mean edge profiles for the passed executions and the failed executions, and the suspiciousness scores for edges, which are O(uvm), O(vvm), and O(vm), respectively. Therefore the space complexity of our technique is O(vm + vn). The time complexity is determined by the time used to solve the set of equations. If Gaussian elimination is adopted, the time complexity of our technique will be O(n^3).
5. EXPERIMENTAL EVALUATION
In this section, we conduct a controlled experiment to evaluate the effectiveness of our technique.
5.1 Setup of Experiment
5.1.1 Subject Programs
We use four UNIX programs, namely, flex, grep, gzip, and sed, as subject programs. They are real-life medium-sized programs, and have been adopted to evaluate other CBFL techniques (as in [14][23][26]). We downloaded the programs (including all versions and associated test suites) from SIR [10] on January 10, 2008. Each subject program has multiple (sequentially labeled) versions. Table 1 shows the real-life program versions, numbers of lines of executable statements (LOC), numbers of applicable faulty versions, and the sizes of the test pools. Take the program flex as an example. The real-life versions include flex-2.4.7 to flex-2.5.4, and have 8571 to 10124 lines of executable statements. 21 single-fault versions are used in the experiment. All these faulty versions share a test suite that consists of 567 test cases. Following [12], we apply the whole test suite as inputs to individual subject programs.
<table>
<thead>
<tr>
<th>Program</th>
<th>LOC</th>
<th>No. of single-fault versions</th>
<th>No. of test cases</th>
</tr>
</thead>
<tbody>
<tr>
<td>flex</td>
<td>8571–10124</td>
<td>21</td>
<td>567</td>
</tr>
<tr>
<td>grep</td>
<td>8053–9089</td>
<td>17</td>
<td>809</td>
</tr>
<tr>
<td>gzip</td>
<td>4081–5159</td>
<td>55</td>
<td>217</td>
</tr>
<tr>
<td>sed</td>
<td>4756–9289</td>
<td>17</td>
<td>370</td>
</tr>
</tbody>
</table>
Following the documentation of SIR [10] and previous experiments [12][15][18][19], we exclude any single-fault version whose faults cannot be revealed by any test case. This is because both our technique and the peer techniques used in the experiment [1][18][19][24] require the existence of failed executions. Moreover, we also exclude any single-fault version that fails for more than 20% of the test cases [10][12]. Besides, as Jones et al. have done in [15], we exclude those faulty versions that are not supported by our experimental environment and instrumentation tool (we use the Sun Studio C++ compiler and gcov to collect edge profile information on program versions). All the remaining 110 single-fault versions are used in the controlled experiment (see Table 1).
5.1.2 Peer Techniques
In our experiment, we select five representative peer techniques to compare with our technique. Tarantula [24] and Jaccard [1] are two statement-level techniques. They are often chosen as alternatives for comparison in other evaluations of fault-localization techniques. CBI [18] and SOBER [19] are predicate-level techniques. Since they make use of predicates (such as branch decisions) to locate suspicious program positions, which are related to the edge concept in our technique, we decide to compare these techniques with ours. Note that CBI originally proposed to use random sampling to collect predicate statistics to reduce overhead. In our evaluation on CBI, we sample all the predicates (as in [19]) via gcov. In Yu et al.'s work [24], CBI is modified to become a statement-level technique (SBI [24]), and we also include SBI for comparison with our technique. Note that a tie-breaking strategy is included in Tarantula as stated in [24]. CP uses no tie-breaking strategy in our experiment.
5.1.3 Effectiveness Metrics
Each of Tarantula, SBI, Jaccard, and CP produces a ranked list of all statements. For every technique, we check all the statements in ascending order of their ranks in the ordered list, until a faulty statement is found. The percentage of statements examined (with respect to all statements) is returned as the effectiveness of that technique. This metric is also used in previous studies [14][24]. We note also that statements having the same rank are examined as a group.
CBI and SOBER generate ranked lists of predicates. To the best of our knowledge, the metric T-score [20] is used to evaluate their effectiveness in previous studies [19]. T-score uses a program dependence graph to calculate the distance among statements. Starting from some top elements in a ranked list of predicates, T-score conducts breadth-first search among the statements to locate a fault. The search terminates when it encounters any faulty statement, and the percentage of statements examined (with respect to all statements) is returned as the effectiveness of that technique [20]. Since it is reported in [19] that the “top-5 T-score” strategy gives the highest performance for CBI and SOBER, we follow suit
to choose the top-5 predicates and report the top-5 T-score results as their effectiveness in our experiment.
If a fault is in a non-executable statement (such as the case of a code omission fault), dynamic execution information cannot help locate the fault directly. To reflect the effectiveness of a technique, we follow previous studies (such as [14]) to mark the directly infected statement or an adjacent executable statement as the fault position, and apply the above metrics.
5.1.4 Experiment Environment and Issues
The experiment is carried out in a Dell PowerEdge 1950 server (4-core Xeon 5355 2.66GHz processors, 8GB physical memory, and 400GB hard disk) serving a Solaris UNIX with the kernel version Generic_120012-14. Our framework is compiled using Sun C++ 5.8.
When applying our technique, an exceptional case is that the denominator in equation (4) may be zero. For every occurrence of a zero denominator in the experiment, the tool automatically replaces it by a small constant. $10^{-10}$ is chosen as the constant, which is less than any intermediate computing result by many degrees of magnitude. We have varied this constant from to $10^{-11}$ to $10^{-9}$ and compared the effectiveness results of CP, and confirmed that the results are the same.
In the experiment, the time needed to generate a ranked list for one faulty version is always less than 1 second. The mean time spent for one faulty version is about 0.455 seconds.
5.2 Data Analysis
In this section, we compare our technique with Tarantula, SBI, Jaccard, CBI, and SOBER, and report their effectiveness on the 110 single-fault program versions. In the following subsections, the data related to “Tarantula”, “SBI”, “Jaccard”, “CBI”, and “SOBER” are worked out using the techniques described in the papers [24], [24], [1], [18], and [19], respectively. The data related to “CP” are worked out using our technique. For every plot in Figure 2 and Figure 3, we use the same set of x-axis labels and legends.
5.2.1 Overall Results
To evaluate the overall effectiveness of a technique, we first take the average of the effectiveness results on the four subject programs. The results are shown in Figure 2. In the plot in Figure 2(a), the x-axis means the percentage of code that needs to be examined in order to locate the fault (according to the effectiveness metrics). We also refer to it as the code examination effort in this paper. The y-axis means the mean percentage of faults located. Take the curve for CP in Figure 2(a) for illustration. On average, CP can locate 48.24% of all faults by examining up to 5% of the code in each faulty version. The curves of Tarantula, Jaccard, CBI, SBI, and SOBER can be interpreted similarly. Note that the effectiveness of Tarantula, SBI, and Jaccard are very close, and hence their curves in Figure 2 and Figure 3 almost completely overlap.
Figure 2(a) gives the overall effectiveness of CP, Tarantula, SBI, Jaccard, CBI, and SOBER. Each of the six curves starts at the point (0%, 0%) and finally reaches the point (100%, 100%). Obviously, it reflects the fact that no fault can be located when examining 0% of the code, while all the faults can be located when examining 100%. We observe from the figure that CP can locate more faults than CBI and SOBER in the range from 1% to 99% of the code affordable to be examined. Moreover, the figure also shows that CP can locate more faults than Tarantula, SBI, and Jaccard almost in the entire range of the first one third (from 2% to 33%) of the code examination effort.
When comparing the mean effectiveness, although one cannot meaningfully conclude the results from outlier segments (such as those data points beyond three standard deviations), previous studies such as [19] once reported the results on the first 20% code examination range. Therefore, we further zoom in (to the range of [0%, 20%]) as shown in Figure 2(b).
The figure shows that, if only 1% of the code is affordable to be examined, Tarantula, SBI, and Jaccard can locate 31.99% of all faults, CP can locate 24.50%, CBI can locate 8.54%, while SOBER cannot locate any fault. If 2% of the code is affordable to be examined, encouragingly, CP not only catches up with Tarantula, SBI, and Jaccard, but also exceeds them a lot. For example, CP, Tarantula, SBI, Jaccard, CBI, and SOBER locate 41.55%, 33.18%, 32.45%, 32.90%, 11.48%, and 0.00% of the faults in all faulty versions, respectively. In the remaining range (from 2% to 20%) in Figure 2(b), CP always locates more faults than the peer techniques. For example, when examining 8%, 9%, and 10% of the code, CP locates 55.31%, 57.86%, and 57.86% of the faults, respectively; Tarantula locates 38.75%, 40.67%, and 42.03% of the faults; SBI locates 38.46%, 40.39%, and 41.75%. In summary, by examining up to 20% of the code, CP can be more effective than the peer techniques.
In previous studies, a weighted average method has also been used [8]. For example, Chilimbi et al. [8] uses the total number of faults located in all programs as the y-axis (in the sense of Figure 2(b)), rather than the average percentage of faults located. To enable reader to compare previously published results with ours, we follow [8] to present such a plot as Figure 2(c). From this figure, we observe that if 2% to 16% of the code is examined, CP performs better than the other five techniques. However, Tarantula, SBI, and Jaccard catch up with CP gradually. The range (21% to 99%) is not shown in this paper owing to space limit, and yet we do observe that the effectiveness of CP, Tarantula, SBI, and Jaccard are very similar. More detailed statistical comparisons can be found in Section 5.2.3.
Overall, the experiment shows that CP can be effective. At the same time, it also shows that CP can be further improved.
5.2.2 Results on Individual Subject Programs
We further compare the effectiveness of CP against the peer techniques on each subject program. Figure 3 shows the corresponding results on the programs flex, grep, gzip, and sed, respectively. Take the curve for SBI in Figure 3(a) for illustration. Like Figure 2(a), the x-axis means the percentage of code examined, and the y-axis means the percentage of faults located by SBI within the given code examination effort (specified by the respective value on the x-axis). The curves for CP, Tarantula, Jaccard, CBI, and SOBER can be interpreted similarly.
The four plots in Figure 3 give the overall effectiveness of CP, Tarantula, SBI, Jaccard, CBI, and SOBER on each subject program. If 5% of the code has been examined, CP can locate faults in 47.61%, 52.94%, 21.81%, and 70.58% of the faulty versions of the programs flex, grep, gzip, and sed, respectively. On the other hand, Tarantula can locate 52.38%, 0.00%, 18.18%, and 70.58% of the faults; SBI can locate 52.38%, 0.00%, 20.00%, and 70.58%; Jaccard can locate 52.38%, 0.00%, 21.81%, and 70.58%; CBI can locate 9.52%, 29.41%, 0.00%, and 35.29%; and SOBER can locate 0.00%, 5.88%, 0.00%, and 0.00%. The other points on the curves can be interpreted similarly.
Similarly to Section 5.2.1, let us discuss the first 20% of the code examination range. For flex and gzip, we observe that CP performs better than CBI or SOBER, and performs comparably with Tarantula, SBI and Jaccard. For grep and sed, CP locates more faults than Tarantula, SBI, Jaccard, CBI, and SOBER within the first 20% code examination range. In summary, CP performs outstandingly in this range.
5.2.3 Statistics Analysis on Individual Faulty Versions
In this section, we further use popular statistics metrics to compare different techniques. Table 2 lists out the minimum (min), maximum (max), medium, mean, and standard derivation (stdev) of the effectiveness of these techniques, on the 110 single-fault versions. The effectiveness of each technique is evaluated using the same metric as in the previous section; therefore, the smaller the magnitude, the better is the effectiveness. We observe that in each row, CP gives the best (smallest) value among the six techniques, which further strengthens our belief that CP can be effective on locating faults.
To further find the relative merits on individual versions, we compute the difference in effectiveness between CP and each peer technique, and the results are shown in Table 3. Take the cell in column “CP−Tarantula” and row “< −5%” as an example. It shows that, for 42 (38.18%) of the 110 faulty versions, the code examination effort of using CP to locate a fault is less than that of Tarantula by more than 5%. Similarly, for the row “≥ 5%”, only
Table 3: Statistics of differences in effectiveness
<table>
<thead>
<tr>
<th>Difference (percentage difference)</th>
<th>CP−Tarantula</th>
<th>CP−SBI</th>
<th>CP−Jaccard</th>
<th>CP−CBI</th>
<th>CP−SOBER</th>
</tr>
</thead>
<tbody>
<tr>
<td>−1% to 1%</td>
<td>17 (15.27%)</td>
<td>18 (16.36%)</td>
<td>19 (17.27%)</td>
<td>19 (17.27%)</td>
<td>6 (5.45%)</td>
</tr>
<tr>
<td>> 1%</td>
<td>25 (22.73%)</td>
<td>26 (23.63%)</td>
<td>27 (24.54%)</td>
<td>28 (25.45%)</td>
<td>30 (27.27%)</td>
</tr>
<tr>
<td>< 5% to 5%</td>
<td>41 (37.27%)</td>
<td>42 (38.18%)</td>
<td>43 (39.09%)</td>
<td>43 (39.09%)</td>
<td>42 (38.18%)</td>
</tr>
<tr>
<td>≥ 5%</td>
<td>7 (6.36%)</td>
<td>7 (6.36%)</td>
<td>7 (6.36%)</td>
<td>7 (6.36%)</td>
<td>7 (6.36%)</td>
</tr>
<tr>
<td>−10% to 10%</td>
<td>60 (54.54%)</td>
<td>60 (54.54%)</td>
<td>60 (54.54%)</td>
<td>60 (54.54%)</td>
<td>60 (54.54%)</td>
</tr>
<tr>
<td>> 10%</td>
<td>19 (17.27%)</td>
<td>19 (17.27%)</td>
<td>19 (17.27%)</td>
<td>19 (17.27%)</td>
<td>19 (17.27%)</td>
</tr>
</tbody>
</table>
620 do_yywrap = ...; // Fault F_AA_4
985 if (! do_yywrap )
3369 if ( ( need_backing_up & & ! nultrans ) ... ) // Fault F_AA_3
static yyconst short int yy_chk[2775] = { ...
11825 836, 836, 599, ... // Fault F_AA_2 ...
12193 while ( yy_chk[...]!= ... )
Figure 4: Excerpts from multi-fault program.
27 (24.54%) of the 110 versions, the code examination effort of CP is greater than that of Tarantula by more than 5%. For 41 (37.27%) of the faulty versions, the effectiveness between CP and Tarantula cannot be distinguished at the 5% significance level.
We therefore deem that, at the 5% significance level, the probability of CP performing better than Tarantula on these subject programs is higher than that of Tarantula performing better than CP. We further vary the significance level from 5% to 1% and 10% to produce the complete table. The experimental result shows that the probability of CP performing better than its peer technique is consistently higher than that for the other way round.
5.2.4 Discussions of Multi-Fault Programs
In this section, we use a real-life multi-fault program to validate the effectiveness of CP. Our objective here is to study CP rather than comparing CP with peer techniques.
Version v3 of flex has the largest number of feasible faults (9 in total) and flex is the largest subject program in the entire experiment. Therefore, we enable all the nine faults of this version to simulate a 9-fault program. Part of the code excerpt is shown in Figure 4. After enabling all nine feasible faults, we execute the test pool in the 9-fault program. It results in 136 failed executions and 431 passed executions.
We apply CP to this 9-fault program, and locate the first fault in line 3369 after examining 0.11% of the code. This fault is on an incorrect logical operator. By analyzing the faulty Boolean expression, we find that the fault is enabled only if the decision of the Boolean expression is true. As such, this edge (namely, the true decision made in line 3369) rightly reveals failures due to the fault, and CP locates this fault effectively. We simulate the fixing of this fault by reverting the statement to the original version. We rerun all the test cases, and find that failed executions have been reduced to 123. We re-apply CP and locate the second fault in line 620 after examining 1.21% of the code. The fault is an incorrect assignment of the variable yy_chk. In this version, the first statement that uses the variable yy_chk is in line 985; it is the root cause of failures. We manually examine the corresponding CFG between the block (dubbed b2) containing the statement in line 620 and the block (dubbed b3) containing the statement in line 985. There are many blocks and edges. We observe that, since none of them uses or redefines yy_chk, the infected program state of b2 has successfully been propagated to b3 along the edges. Finally, even though the statement that outputs the failure is far away from the fault position, CP successfully locates the fault. According to previous studies [11], both of these two faults frequently occur in C programs. CP seems to be effective in locating certain popular faults, although more experiments are required to confirm this conjecture.
For space reason, we do not describe the remaining faults in detail. The next six faults are located in lines 1030, 1361, 1549, 3398, 2835, and 11058, respectively. The code examination efforts for locating them are 1.12%, 8.50%, 7.25%, 21.19%, 13.82%, and 88.2%, respectively. The last fault, which results in 6 failures among 567 test cases, is found in line 12193. It is an incorrect static variable definition. Since this fault is seeded in a global definition statement and the compiler tool gcov fails to log its execution, we mark its directly affected statement (say, line 12193) as the fault position. However, CP needs to examine 93.55% of the code to locate this fault. We scrutinize the case and find it to be a coincidence. For 7 out of 567 test cases that do not reveal failures, this branch statement is never covered. For the 6 test cases that reveal failures and the remaining 560 passed test cases, both the true branch and the false branch are covered. For more than 90% of the cases, the number of times that each branch is covered is very close to each other (with less than 5% difference). It is hard for CP to distinguish these two edges. We view that this practical scenario provides a hint for further improving CP, even though the current experiment shows that CP is promising.
5.3 Threats to Validity
We used gcov to implement our tool in which coverage profiling is completely conducted. The generation of the equation set by the tool is relatively straightforward. The equations are solved using a standard Gaussian elimination implementation. We have implemented the peer techniques ourselves and checked that the implemented algorithms adhere strictly to those published in the literature. We have also conducted trial runs on toy programs with limited test cases to assure the implementations of CP and other peer techniques.
Currently, we follow [19] to use T-score when evaluating CBI and SOBER. Some researchers have reported limitations in T-score (see [9], for example). A P-score has been proposed in [27] and may be considered for future studies.
CP, Tarantula, SBI, and Jaccard produce ranked lists of statements, while CBI and SOBER generate ranked list of predicates. Consequently, the experiment has used two effectiveness metrics to report the results of different techniques. It is unsuitable to compare CP on a par with CBI and SOBER. In this connection, the comparison and the discussion of CP in relation to CBI and SOBER should be interpreted carefully.
We use grep, gzip, sed as well as their associated test suites to evaluate our technique. These programs are real-life programs with realistic sizes, and they have been used in previous studies [14][23][26]. It is certainly desirable to evaluate CP further on other real-life subject programs and scenarios.
6. RELATED WORK
Comparing program executions of a faulty program over different test cases and considering program states are frequently used fault-localization strategies. Delta debugging [9] isolates failure-causing inputs, produces cause effect chains and locates the root causes of failures. It considers a program execution (of a failure-causing test case) as a sequence of program states. Each state induces the next state, until a failure is reached. Since delta debugging is not a CBFL technique [23], we do not include it in our detail study. Predicate switching [26] is another technique to locate a fault by checking the execution states. It switches a predicate’s decision at execution time to alter the original control flow of a failure-causing test case, aiming at locating a predicate such that a switch of the decision will produce correct output. Their latest version [14] works on the value set of all variables and the result looks promising.
propagation of suspicious program states through control flow scores of basic blocks and statements, which abstractly models the all failed executions and those in all passed executions, execution. By collecting such evaluation biases of a statement in express the probability that a predicate is evaluated to be true in an execution. By collecting such evaluation biases of a statement in all failed executions and those in all passed executions, SOBER compares the two distributions of evaluation biases, and accordingly estimate how much the predicate is suspicious. Jones et al. [16] further use Tarantula to explore how to cluster test cases to facilitate multiple developers to debug a faulty program in parallel. Baudry et al. [6] observe that some groups of statements (known collectively as a dynamic basic block) are always executed by the same set of test cases. To optimize Tarantula, they use a bacteriologic approach to find out a subset of original test set that aims to maximize the number of dynamic basic blocks. Liblit et al. [2] further adapt CBI to handle compound Boolean expressions. Chilimbi et al. [8], in their work Holmes, conduct statistical fault localization using paths instead of predicates. Zhang et al. [28] empirically show that short-circuit rules in the evaluation of Boolean expressions may significantly affect the effectiveness of predicate-based techniques. In Yu et al. ’s work [24], CBI has been adapted to the statement level.
Edge profiles have been developed for years. Bond et al. [7] propose a hybrid instrumentation and sampling approach for continuous path and edge profiling. It has been used in fault localization. Santelices et al. [21] investigate the effectiveness of using different program entities (statements, edges, and DU-pairs) to locate faults. They show that the integrated results of using different program entities may be better than the use of any single kind of program entity. Slicing is also a means of locating faults. Gupta et al. [13] propose to narrow down slices using a forward dynamic slicing approach. Zhang et al. [26] integrate forward and backward dynamic slicing approaches for debugging.
7. CONCLUSION
Fault localization is a process to find the faults in failed programs. Existing coverage-based fault-localization approaches use the statistics of test case executions to serve this purpose. They focus on individual program entities, generate a ranked list of their suspiciousness, but ignore the structural relationships among statements.
In this paper, we assess the suspiciousness scores of edges, and set up a set of linear algebraic equations over the suspiciousness scores of basic blocks and statements, which abstractly models the propagation of suspicious program states through control flow edges in a back-tracking manner. Such equation sets can be efficiently solved by standard mathematical techniques such as Gaussian elimination. The empirical results on comparing existing techniques with ours show that our technique can be effective.
We have further conducted a case study on a multi-fault program to examine the effectiveness of our technique, and find cases that inspire future work. In order to further enhance the effectiveness of our approach, another prospective is to extend our edge profile technique to cover path profiles or data flow profiles as well.
8. REFERENCES
APPENDIX A. Proof of equation (3)
Let \( \text{Prob}(e) \) be the probability that the propagation of infected program states via \( e \) causes a failure.
Let \( T = \{ t_1, t_2, \ldots, t_n \} \) be a set of test cases associated with passed executions, and \( T' = \{ t'_1, t'_2, \ldots, t'_m \} \) be a set of test cases associated with failed executions. Let \( \theta(e, t) \) denote whether the edge \( e \) is covered in the corresponding program execution of \( t \). We would like to estimate the value of \( \text{Prob}(e) \) from the subsets \( T_1 = \{ t \mid \theta(e, t) = 1 \} \subset T \) and \( T_2 = \{ t' \mid \theta(e, t') = 1 \} \subset T' \) because the executions in these two subsets correlates with the traversal of \( e \). The expected number of failed executions in the sample set of \( T_1 \cup T_2 \) is \( \text{Prob}(e) \times |T_1 \cup T_2| \). This estimate is unbiased.
To maximize the value of \( \text{Prob}(e) \), we set the expected number of failed executions in the sample set to be equal to the actual number of failed executions. That is, we set \( \text{Prob}(e) \times |T_1 \cup T_2| = |T| \). We then solve for \( \text{Prob}(e) \) and obtain equation (3). The details of the proof are straightforward.
APPENDIX B. Proof that sorting of edges always produces the same sequence no matter whether equation (2) or (3) is used
We need an auxiliary function for the proof. We define a sign function such that \( \text{sgn}[x] = -1 \) if \( x < 0 \), \( \text{sgn}[x] = 0 \) if \( x = 0 \), and \( \text{sgn}[x] = 1 \) if \( x > 0 \).
Suppose \( e \) and \( e' \) are two edges in \( E \) satisfying the conditions (i) \( \theta(e) \neq 0 \lor \theta(e') \neq 0 \) and (ii) \( \theta(e) \neq 0 \lor \theta(e') \neq 0 \). We make use of the sign function to express their relative ranking order with respect to equation (3) as \( \text{sgn}[\text{Prob}(e) - \text{Prob}(e')] \). Similarly, we express their relative ranking order with respect to equation (2) as \( \text{sgn}[\theta^b(e) - \theta^b(e')] \).
Case 1 \( (\theta(e) = 0) \). By equation (3), \( \text{Prob}(e) = 0 \). Also by equation (3),
\[
\text{Prob}(e) = \begin{cases}
\frac{\theta^b(e)}{\theta^b(e) + \theta^b(e')} & \text{if } \theta(e) = 0, \\
0 & \text{otherwise}.
\end{cases}
\]
Similarly, by setting \( \theta(e) = 0 \), we have
\[
\text{Prob}(e') = \begin{cases}
\frac{\theta^b(e')}{\theta^b(e) + \theta^b(e')} & \text{if } \theta(e') = 0, \\
0 & \text{otherwise}.
\end{cases}
\]
Case 2 \( (\theta(e) = 0) \). Similarly to the proof of case 1, we have
\[
\text{sgn}[\text{Prob}(e) - \text{Prob}(e')] = \text{sgn}[\theta^b(e) - \theta^b(e')].
\]
Case 3 \( (\theta(e) \neq 0 \land \theta(e') \neq 0) \). Similarly to case (1), \( \text{sgn}[\text{Prob}(e) - \text{Prob}(e')] = \text{sgn}[\theta^b(e) - \theta^b(e')]. \)
Case 4 \( (\theta(e) \neq 0 \land \theta(e') \neq 0) \). We first discuss the value of \( \text{sgn}[\theta^b(e) - \theta^b(e')]. \) Since none of \( \theta(e), \theta(e'), \theta(e) \), and \( \theta(e') \) is 0, each of them should be a positive number. Suppose \( a, b, c \) are any positive numbers, and \( d \) is any number. We have
\[
\begin{align*}
\theta^b(e) - \theta^b(e') & = \text{sgn}[\theta^b(e) - \theta^b(e')] \equiv \text{sgn}[\theta^b(e) + a - b \theta^b(e')] = -\text{sgn}[\theta^b(e) + b - a \theta^b(e')] \\
\theta^b(e) - \theta^b(e') & = \text{sgn}[\theta^b(e) + a - b \theta^b(e')] = \text{sgn}[\theta^b(e') + a - b \theta^b(e)].
\end{align*}
\]
By setting \( a = u, b = v, c = u, \) and \( d = 0 \), we have \( \text{sgn}[\theta^b(e) - \theta^b(e')] = \text{sgn}[\text{Prob}(e) - \text{Prob}(e')] \). Similarly, by setting \( a = 1, b = 1, c = 2, \) and \( d = 1 \), we have \( \text{sgn}[\theta^b(e) - \theta^b(e')] = \text{sgn}[\text{Prob}(e) - \text{Prob}(e')] \). Hence, we obtain \( \text{sgn}[\text{Prob}(e) - \text{Prob}(e')] = \text{sgn}[\theta^b(e) - \theta^b(e')]. \)
Hence, the relative ranking order of any two edges computed by equation (2) is the same as that computed by equation (3).
|
{"Source-Url": "http://hub.hku.hk/bitstream/10722/93325/1/800155837.pdf", "len_cl100k_base": 15556, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 48971, "total-output-tokens": 17429, "length": "2e13", "weborganizer": {"__label__adult": 0.0003535747528076172, "__label__art_design": 0.0003170967102050781, "__label__crime_law": 0.0003521442413330078, "__label__education_jobs": 0.000644683837890625, "__label__entertainment": 6.669759750366211e-05, "__label__fashion_beauty": 0.00015485286712646484, "__label__finance_business": 0.00017309188842773438, "__label__food_dining": 0.00028204917907714844, "__label__games": 0.0010051727294921875, "__label__hardware": 0.00101470947265625, "__label__health": 0.0003817081451416016, "__label__history": 0.0002269744873046875, "__label__home_hobbies": 9.447336196899414e-05, "__label__industrial": 0.00030803680419921875, "__label__literature": 0.0002720355987548828, "__label__politics": 0.00020694732666015625, "__label__religion": 0.0003809928894042969, "__label__science_tech": 0.01508331298828125, "__label__social_life": 7.390975952148438e-05, "__label__software": 0.005496978759765625, "__label__software_dev": 0.97216796875, "__label__sports_fitness": 0.0002834796905517578, "__label__transportation": 0.0003814697265625, "__label__travel": 0.0001671314239501953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 62391, 0.05226]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 62391, 0.4433]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 62391, 0.89292]], "google_gemma-3-12b-it_contains_pii": [[0, 1073, false], [1073, 5245, null], [5245, 10117, null], [10117, 17440, null], [17440, 24169, null], [24169, 28187, null], [28187, 35002, null], [35002, 38908, null], [38908, 44431, null], [44431, 51480, null], [51480, 58315, null], [58315, 62391, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1073, true], [1073, 5245, null], [5245, 10117, null], [10117, 17440, null], [17440, 24169, null], [24169, 28187, null], [28187, 35002, null], [35002, 38908, null], [38908, 44431, null], [44431, 51480, null], [51480, 58315, null], [58315, 62391, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 62391, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 62391, null]], "pdf_page_numbers": [[0, 1073, 1], [1073, 5245, 2], [5245, 10117, 3], [10117, 17440, 4], [17440, 24169, 5], [24169, 28187, 6], [28187, 35002, 7], [35002, 38908, 8], [38908, 44431, 9], [44431, 51480, 10], [51480, 58315, 11], [58315, 62391, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 62391, 0.15564]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
09704c67ab213051162d13ed1cede9b3f7897d88
|
[REMOVED]
|
{"Source-Url": "http://www.cs.utexas.edu/~ai-lab/downloadPublication.php?filename=http%3A%2F%2Fwww.cs.utexas.edu%2Fusers%2Fml%2Fpapers%2Fraghavan.ecml11.pdf&pubid=127099", "len_cl100k_base": 9975, "olmocr-version": "0.1.50", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 42065, "total-output-tokens": 12103, "length": "2e13", "weborganizer": {"__label__adult": 0.00042557716369628906, "__label__art_design": 0.0007872581481933594, "__label__crime_law": 0.000713348388671875, "__label__education_jobs": 0.002872467041015625, "__label__entertainment": 0.00029659271240234375, "__label__fashion_beauty": 0.00027942657470703125, "__label__finance_business": 0.0004372596740722656, "__label__food_dining": 0.0005736351013183594, "__label__games": 0.001944541931152344, "__label__hardware": 0.00128936767578125, "__label__health": 0.0007815361022949219, "__label__history": 0.0004799365997314453, "__label__home_hobbies": 0.00021398067474365232, "__label__industrial": 0.0007672309875488281, "__label__literature": 0.0012617111206054688, "__label__politics": 0.0004096031188964844, "__label__religion": 0.0005688667297363281, "__label__science_tech": 0.438720703125, "__label__social_life": 0.0002199411392211914, "__label__software": 0.0265045166015625, "__label__software_dev": 0.51904296875, "__label__sports_fitness": 0.00033855438232421875, "__label__transportation": 0.0007295608520507812, "__label__travel": 0.000209808349609375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48018, 0.04886]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48018, 0.50378]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48018, 0.89247]], "google_gemma-3-12b-it_contains_pii": [[0, 2472, false], [2472, 5438, null], [5438, 8964, null], [8964, 11487, null], [11487, 14354, null], [14354, 16450, null], [16450, 19474, null], [19474, 22655, null], [22655, 25966, null], [25966, 29246, null], [29246, 32694, null], [32694, 35473, null], [35473, 38552, null], [38552, 41651, null], [41651, 44349, null], [44349, 48018, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2472, true], [2472, 5438, null], [5438, 8964, null], [8964, 11487, null], [11487, 14354, null], [14354, 16450, null], [16450, 19474, null], [19474, 22655, null], [22655, 25966, null], [25966, 29246, null], [29246, 32694, null], [32694, 35473, null], [35473, 38552, null], [38552, 41651, null], [41651, 44349, null], [44349, 48018, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48018, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48018, null]], "pdf_page_numbers": [[0, 2472, 1], [2472, 5438, 2], [5438, 8964, 3], [8964, 11487, 4], [11487, 14354, 5], [14354, 16450, 6], [16450, 19474, 7], [19474, 22655, 8], [22655, 25966, 9], [25966, 29246, 10], [29246, 32694, 11], [32694, 35473, 12], [35473, 38552, 13], [38552, 41651, 14], [41651, 44349, 15], [44349, 48018, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48018, 0.11979]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
f4ccf7a05d3bbc1557b0bffcc899d9718ace9a24
|
MULTI-QUERY OPTIMIZATION IN THE DATAPATH SYSTEM
By
NIKETAN R. PANSARE
A THESIS PRESENTED TO THE GRADUATE SCHOOL
OF THE UNIVERSITY OF FLORIDA IN PARTIAL FULFILLMENT
OF THE REQUIREMENTS FOR THE DEGREE OF
MASTER OF SCIENCE
UNIVERSITY OF FLORIDA
2009
1
To my family, friends and professors
ACKNOWLEDGMENTS
Thanks go out to Christopher Jermaine, Alin Dobra, Subi Arumugam, Ravi Jampani and Luis Perez.
<table>
<thead>
<tr>
<th>TABLE OF CONTENTS</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>ACKNOWLEDGMENTS</td>
<td>4</td>
</tr>
<tr>
<td>LIST OF TABLES</td>
<td>7</td>
</tr>
<tr>
<td>LIST OF FIGURES</td>
<td>8</td>
</tr>
<tr>
<td>ABSTRACT</td>
<td>9</td>
</tr>
<tr>
<td>CHAPTER</td>
<td></td>
</tr>
<tr>
<td>1 INTRODUCTION</td>
<td>10</td>
</tr>
<tr>
<td>1.1 Compute-Centric System</td>
<td>10</td>
</tr>
<tr>
<td>1.2 Data-Centric System</td>
<td>10</td>
</tr>
<tr>
<td>1.3 Compute-Centric Versus Data-Centric</td>
<td>11</td>
</tr>
<tr>
<td>1.4 Problem Statement</td>
<td>14</td>
</tr>
<tr>
<td>2 RELATED WORK</td>
<td>17</td>
</tr>
<tr>
<td>3 OVERVIEW</td>
<td>19</td>
</tr>
<tr>
<td>4 DESIGN</td>
<td>22</td>
</tr>
<tr>
<td>4.1 The Network Integrator Class</td>
<td>22</td>
</tr>
<tr>
<td>4.2 The Enumerator Method</td>
<td>22</td>
</tr>
<tr>
<td>4.3 The Cost Function</td>
<td>23</td>
</tr>
<tr>
<td>4.4 The Search Strategy</td>
<td>23</td>
</tr>
<tr>
<td>5 IMPLEMENTATION</td>
<td>26</td>
</tr>
<tr>
<td>5.1 Types</td>
<td>26</td>
</tr>
<tr>
<td>5.2 Enumeration</td>
<td>27</td>
</tr>
<tr>
<td>5.3 Mapping Rules</td>
<td>28</td>
</tr>
<tr>
<td>5.4 Bypassable Rules</td>
<td>29</td>
</tr>
<tr>
<td>5.5 The Cost Function</td>
<td>31</td>
</tr>
<tr>
<td>5.6 The Search Strategy</td>
<td>33</td>
</tr>
<tr>
<td>6 EXPERIMENTAL RESULTS</td>
<td>35</td>
</tr>
<tr>
<td>6.1 Goal</td>
<td>35</td>
</tr>
<tr>
<td>6.2 Setup</td>
<td>35</td>
</tr>
<tr>
<td>6.3 Experimental Results</td>
<td>37</td>
</tr>
<tr>
<td>6.4 Analysis</td>
<td>37</td>
</tr>
<tr>
<td>7 CONCLUSION</td>
<td>45</td>
</tr>
<tr>
<td>8 FUTURE WORK</td>
<td>46</td>
</tr>
</tbody>
</table>
## LIST OF TABLES
<table>
<thead>
<tr>
<th>Table</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>5-1</td>
<td>Selectivity Factor</td>
</tr>
<tr>
<td>6-1</td>
<td>Cost and Time taken by each algorithm</td>
</tr>
<tr>
<td>Figure</td>
<td>Description</td>
</tr>
<tr>
<td>--------</td>
<td>-------------</td>
</tr>
<tr>
<td>1-1</td>
<td>Query plans for traditional databases</td>
</tr>
<tr>
<td>1-2</td>
<td>Path Network after query 1</td>
</tr>
<tr>
<td>1-3</td>
<td>Path Network after query 2</td>
</tr>
<tr>
<td>1-4</td>
<td>Path Network after query 3</td>
</tr>
<tr>
<td>5-1</td>
<td>Path network before bypassing</td>
</tr>
<tr>
<td>5-2</td>
<td>Final path network with bypassing</td>
</tr>
<tr>
<td>5-3</td>
<td>Final path network without bypassing</td>
</tr>
<tr>
<td>5-4</td>
<td>Example path network for bypassing</td>
</tr>
<tr>
<td>6-1</td>
<td>Framework for testing different query optimization techniques</td>
</tr>
<tr>
<td>6-2</td>
<td>Comparison of FIFO with other selectors</td>
</tr>
<tr>
<td>6-3</td>
<td>Comparison of Random selector with the cost based selectors</td>
</tr>
<tr>
<td>6-4</td>
<td>Comparison of the cost based selectors</td>
</tr>
<tr>
<td>6-5</td>
<td>Comparison of the the average time taken by the selectors</td>
</tr>
<tr>
<td>6-6</td>
<td>Path network after query 11</td>
</tr>
<tr>
<td>6-7</td>
<td>Path network after query 5 for waypoint-count selector</td>
</tr>
<tr>
<td>6-8</td>
<td>Path network after query 5 for cost-based selector</td>
</tr>
</tbody>
</table>
The Datapath system is a novel database that is implemented from the ground-up using a data-centric approach. In this thesis, I describe and evaluate a multi-query optimizer for the Datapath system. Unlike traditional multi-query optimizers that only try to overlap common sub-expressions, I propose an efficient optimization algorithm that minimizes the data (or the overall number of tuples) flowing through the system. Using this objective function, a qualitative and quantitative study is presented comparing the commonly used algorithms against the proposed multi-query optimization algorithm.
CHAPTER 1
INTRODUCTION
1.1 Compute-Centric System
Most computer systems, including databases, are compute-centric. The data is brought onto the processor through the memory hierarchy as required by the computations. For example, consider a computation \( \text{ADD} \ A, \ B \). In typical computer system, the control element of the program (usually the loader) will load the computation on the processor and then figure out that it requires \( A \) and \( B \) for the computation. If \( A \) and \( B \) are not in the cache or the main memory, the control element will fetch them from the disk and load it onto the cache. Furthermore, if \( A \) and \( B \) are not stored in the same memory page, there could be additional overhead in the disk access. Though this model seems natural for most computer systems (for example, scientific and commercial applications), it does not fit well for databases. There are several reasons for this. First, the data access pattern for computations in databases is not uniform. Compared to the databases, most scientific and commercial application are able to utilize locality of the data much more efficiently. Though several algorithms \([17, 19, 23]\) are suggested to improve the memory performance of the databases, but they can only perform as good as the data expected by the computations. This emphasis on the computation is ill-suited for the databases due to large amount of data they handle. Second, the gap between the time taken to push the data through memory hierarchy and the time taken to perform the computation on it has been increasing in the past years. This problem has been further aggravated with the advent of multi-core processors and hence transferring the data through memory hierarchy is becoming a bottleneck for the modern databases \([2]\). In spite of this bottleneck, computations still drive the data in current database systems.
1.2 Data-Centric System
The Datapath system is a prototype system which uses Data-centric approach for analytic query processing. To understand Data-centric approach, let us compare the
Datapath system to the water pipe system. Imagine the tables of the database as an active entity, like tap or some water source that keeps on generating the data, until it is turned off. This data moves through the memory hierarchy, from disk to the cache, onto the processor. We assign different cores of the processor to different relational operators or computation units called as waypoints. The waypoints act as a valve, which filters or merges different data flows and outputs them to other waypoints, until the result is generated. It is important to note that waypoints act only as computation units and have no control over the data they receive. Traditional database systems, however, determine which data is required based on the computation, which is then retrieved by using an access method [21] suggested by the query processor. To put it simply, in Data-centric system, data drives the computation; while in traditional database systems, computation drives the data.
1.3 Compute-Centric Versus Data-Centric
Let us consider a simple example to explain the difference between compute-centric and data-centric design for databases. Consider these three queries are issued by users of the database.
Query 1:
select * from nation, supplier
where n_nationkey = s_nationkey and s_acctbal > 10000
Query 2:
select * from nation, customer
where n_nationkey = c_nationkey and c_acctbal > 1000
Query 3:
select * from supplier, partsupp
where s_suppkey = ps_suppkey and ps_availqty < 500
Traditional databases will first find out what are the computations necessary to evaluate these queries. For example, the first query will have at least two computations
namely, Selection on the supplier table and Join on nation and supplier. These computations are represented as nodes (or the operators) in the query plan. The query optimizer for the traditional databases then tries to optimize these computations to produce an optimized query plan. This plan is physically realized by having one GetNext method for each input to the node of the query plan. The GetNext method depending upon the computation it is associated with, decides what data it should retrieve and also how that data should be retrieved. In other words, the query plans generated by the traditional databases are compute-centric.
Usually traditional databases will produce three separate query plans (see 1-1) for these three queries. This is true even for most multi-query optimizers, since these queries have no common sub-expressions [22]. The figure 1-1 ignores the physical operators such as index, sort, etc.
Figure 1-1. Query plans for traditional databases
The Join1 operator will have the code to fetch the data (GetNext method) and also to perform the computation on it. This means that the same data (from the nation table) is brought twice onto the cache; first for Join1 and then for Join2. Though some databases try to alleviate this problem by using multi-query optimizers and materialized views, it does not solve the problem.
The Datapath system has one plan for all the queries running in the system for maximal reuse of the data. This plan is called as the *path network* and is detailed enough to allow the code to be generated and executed by the execution engine. The path network is optimized to minimize the data paths and not the computations. The waypoints have no control over the data they receive and hence have no analogous GetNext method.
Assume that **query 1** is the first query and initial path network is empty. The query plan for **query 1** will form the new path network as shown in the figure 1-2.

The path manager will now try to overlap **query 2** to reduce the flow of data in the system. The figure 1-3 shows the new path network, where **Join1** and **Join2** are merged together to form **Join1-2**.

The figure 1-4 shows a path network after integrating query 3 into the existing path network shown in the figure 1-3. Notice that the selection waypoint of query 1 acts as a bypass waypoint\(^1\) for query 3.
Figure 1-4. Path Network after query 3
The plan generated by traditional database 1-1 has more data paths. This means that there is much more data being transferred than in the path network. Clearly, most traditional query optimizers are not an ideal choice for the Datapath system.
Multi-query optimizers (MQO) try to alleviate this problem by sharing the result of common sub-expressions between queries [22]. The constraints on the type of data in the Datapath system are more relaxed than what most MQO assume, hence making the problem a little different from multi-query optimization. Also, multi-query optimizers like traditional query optimizers focus on optimizing the computations, while ignoring the data paths. Therefore, traditional multi-query optimizers are also not suitable for the Datapath system.
1.4 Problem Statement
The previous section explained the differences in traditional query optimization techniques and the data-centric query optimization techniques. It also pointed out that
\(^1\) A bypass waypoint simply forwards the data without performing any computation on the data.
latter and not the former is suitable for the Datapath system. Before discussing it further, let us define the problem of Data-centric query optimization:
*Given an input query* \((Q_{n+1})\) *and a path network (with queries* \(Q_i\), *where* \(i = 1\) *to* \(n\)), *create a new path network (with queries* \(Q_j\), *where* \(j = 1\) *to* \(n+1\)) *such that execution time (or the response time) of queries* \(Q_j\) *is minimum.*
This means that the goal is to improve the overall response time of the system and not just the input query. The two intuitive approaches to solve this problem are:
1. *Create a new problem specific algorithm.* For example, create a new data-centric MQO algorithm that uses all the features supported by the Datapath system for optimization.
2. *Use a previously solved problem and transform it into your problem:* This means that we use existing query optimizers to first find an optimal query plan for the input query and then try to merge it onto the existing path network. Since the existing query optimizers has no knowledge of the path network, it will use a local optimization function which may improve the execution time of that query, but not of all the queries in the system. Hence, this is not an ideal choice for implementing the Query Planner.
Since the second approach is not feasible, I use the first approach for this thesis. Let us now discuss, how two queries share a waypoint. Every query contains one or more predicates. These predicates can be either selection, join or top \(^2\) predicates. When we say two queries share a waypoint, it means that one or more predicates of the queries are mapped onto the same waypoint. For a predicate to be mapped onto the same waypoint, it has to satisfy two properties:
1. *Two predicates should be of the same type.* This means that a selection predicate cannot be mapped onto a waypoint with join or group-by predicate.
2. *Both predicates should work on same type of data.* There are various rules, which determine whether two predicates work on same type of data or not. I will discuss these rules later in the thesis. Since the Datapath system is expected to evolve and
\(^2\) The predicates that is not a selection or join predicates qualifies as a top predicate. For example, group-by, projection, order-by, etc are considered as the top predicates.
include more complex queries, these rules are also expected to change over a period of time. Hence, the facility to include new rules and modify existing rules is an important requirement for the Query Planner.
In this thesis, I propose a framework that is specific to the Datapath system, but generic enough to test different strategies used in existing query optimization algorithms. This framework is modularized into four main components: namely **Enumerator**, **Search**, **Coster** and **Mapping rules**. Using this kind of modularization, we test and compare different ways to implement each module. This framework also allows us to incorporate new rules for mapping in the Path network without modifying significant amount of code.
Using the above framework, we propose a solution that would try to minimize the response time of the query. Since data-centric focuses on the data and not the computation, it is obvious that the proposed query optimizer also focuses on the data. It does this in two ways. First, the optimization function in the Coster component is to minimize the flow of data through the system. Second, the problem is presented in form of path network, which makes the mapping easy and intuitive. Also the design of input data structures (which will be discussed later) helps to separate different aspects of query optimization and hence are useful for the framework. It is important to note that the problem of query optimization is NP-hard [13] and hence exhaustive solution is not feasible. For simplest case where there are no queries in the system, our problem becomes a traditional query optimization problem. Hence, we use the strategy that limits the search space by performing a look-ahead search rather than exhaustive search in the Search component. This will be discussed in depth in the chapter 5.
CHAPTER 2
RELATED WORK
Selinger et al. [21] laid the foundation for optimizing single queries in the database system. Most query optimizers use a cost model to search through the search space determined by their search strategies. Various search strategies have been proposed for single query optimization [4, 7, 10, 14–16, 27]. Moreover, different query optimization schemes were proposed to achieve different optimization goals, namely minimizing response time of the input query, minimizing the memory usage, maximizing the throughput of the system, etc. Most single query optimizers focus on trying to minimize the response time of input query, whereas multi-query optimizers [22] try to improve the throughput of the system. Instead of optimizing each query independently, multi-query optimizers try to optimize the global query plan that represents all the queries in the system to exploit common sub-expressions in multiple queries. A multiple-query graph is generally used to represent this global query plan [3, 18]. Sellis [22] proved that multi-query optimization would lead to substantial savings over single query optimization. Since multi-query optimization is a NP-hard problem, Sellis [22] suggested using an A* search directed by a heuristic function rather than an exhaustive solution. Later, this heuristic function was replaced by a more informed cost function which improved the performance of the optimizer [24]. Roy et al. [20] suggested a greedy heuristic algorithm that tried to maximize sharing by materializing some partial results on the disk. Dalvi et al. [6] extended this algorithm by using pipelining to reduce the cost of materialization. Toroslu and Cosar [26] proposed a dynamic programming scheme for multi-query optimizers.
Most multi-query optimizers try to overlap only common sub-expressions in multiple queries. Hall [11] suggested detecting common sub-expression within single query. Chen and Dunham [5] allow for partial overlap of selection predicates by leaving all projection operations to the final stages. They argue that pushing projections up is bad for nested loop join but good for hash join [9].
Most multi-query optimization techniques are not integrated with the existing query optimizers. Hall [11] suggests evaluating common sub-expression as a pre-processing step; whereas Subramanian and Venkataraman [25] suggests it as a post-processing step of traditional query optimization. This would allow the MQO techniques to be integrated with the existing query optimizers and hence provide a practical solution. Roy et al. [20] also provide a practical algorithm by modifying the Volcano search strategy [10].
Like the Datapath system, the StagedDB system focus of sharing the access to the data and not the computation. Both the systems group the computations (or the execution requests) of different queries that share the same data. The StagedDB uses the stages to group the computations, whereas the Datapath system uses the waypoints. So, the optimizer of the StagedDB is expected to solve the similar problem (if not the same problem) as the Path Optimizer. However, the decision of sharing the data is pushed down to the execution engine. The execution engine of the StagedDB system takes most of the decisions by monitoring each relational operators or the stages to detect an overlap. This makes sharing of the data opportunistic in the StagedDB system. As a result, the optimizer for the StagedDB is similar to traditional query optimizers [12]. Also, the level of sharing supported by the execution engine of the StagedDB system is less as compared to that of the Datapath system. The cooperative scans [28] also share the data in concurrent scans. This is analogous to sharing of the table-scans in the Datapath system. Apart from the tablescans, the cooperative scans do not support any sharing of the data. In essence, the cooperative scans only try to minimize the disk access and not the accesses to the cache. Though both cooperative scans and the StagedDB system focus to some extent on sharing of the data (rather than computations), they do not fully exploit the level of data-sharing as as compared to the Datapath system.
The two main components on the Datapath system are the Query Planner and the execution engine. The Query Planner is a module that is responsible for generating a path network that can be used by the execution engine. It is very similar to traditional multi-query optimizers in the sense that both incorporate the new query into the global execution plan or the path network. However, they differ in the underlying optimization principle. The Query Planner is intrinsically a data-centric multi-query optimizer. As stated earlier, it tries to minimize the flow of the data in the system. In this thesis, I propose that the overall number of tuples transferred through the memory hierarchy characterizes the flow of the data in the system. However, the overall number of tuples transferred depends on various factors in the system, some of which are difficult to predict. These factors include the cache block size, the page size, the current state of the existing queries, swapping of pages by the operating system, competing processes for the memory bus and other resources, and some other optimization policies implemented by the compiler as well as the operating system. Modeling these factors for the optimization process is beyond the scope of this thesis. Hence, all the existing queries are assumed to have processed no tuples. Though this seems to be a pessimistic assumption, it makes sense in the case of batch query processing. Using this assumption and ignoring the operating system dynamics, I propose that minimizing the number of tuples in the path network will reduce the flow of the data in the system.
Since multi-query optimizers are designed for compute-centric databases, they try to overlap common sub-expressions. It is important to note that though overlapping common sub-expressions reduces the flow of the data in some cases, it may not be true for all cases. In a case where there is a plan with more flow but less computations and another plan with less flow but more computations, traditional multi-query optimizers will chose the former while the Query Planner will chose the latter. In addition, due to inherent design
principle, traditional multi-query optimizers do not exploit all the properties that data
centric databases can offer. Most practical multi-query optimizers and also the Query
Planner do not use an exhaustive approach, so it is difficult to prove that the Query
Planner will always perform either better or same as the existing multi-query optimizer.
However, I have created a simple compute-centric cost function that tries to minimize the
computations but which still expects a data-centric execution engine. As a part of my
thesis, I prove that my cost function outperforms the compute-centric cost function. This
is discussed in more detail in the experimental results section (See 6).
The Query Planner consist of three main components, namely the Parser, the Path
Optimizer and the Translator. The Parser gets a SQL query and performs type-checking
and other validations. If the query is valid, it forwards the query to the Path Optimizer.
The Path Optimizer first transforms the query into a graph called as query description.
The query description contains no information about the ordering of joins. As discussed
earlier, the path network is a graph that represents the overall execution plan of all the
queries in the system or the global query plan. The Path Optimizer then tries to integrate
the query description onto the path network. It does so incrementally by considering one
predicate at a time from the query description and trying to integrate it onto the path
network. It is important to note that this integration is non-destructive. This means that
the edges in the existing path network are not modified. The details of this algorithm will
be discussed later. The Path Optimizer uses an object called the network integrator to
maintain the state of the algorithm. The network integrator object contains a partially
integrated path network and a partial query description. The final state of the Path
Optimizer is a network integrator object that contains a fully integrated path network and
an empty query description.
To summarize:
1. Data-centric query optimization is different than compute-centric query optimization.
2. This thesis uses a data-centric approach to multi-query optimization.
3. The goal of the Path Optimizer is to minimize the number of tuples in the path network.
4. The proposed algorithm (which will be discussed in depth later) is incremental, non-destructive, non-exhaustive and modular (to separate different aspects of query optimization).
CHAPTER 4
DESIGN
4.1 The Network Integrator Class
The design and implementation of the algorithm for adding a new query to the existing path network relies fundamentally on a class called the "NetworkIntegrator" class. The constructor for this class takes as input two objects:
1. The existing path network
2. A representation of the new query that is to be integrated into the network (Query description)
The job of this class is to integrate the new query into the path network. However, for reasons that I will discuss subsequently, this class does not encode any notion of "search". In fact, it is quite unintelligent. All this class does is to provide the machinery necessary to integrate the query into the network: the class does not guide the integration in any way. That is done via an external algorithm that makes use of the class.
The NetworkIntegrator class works as follows. At all times, an instance of this class contains a certain "state of integration". Initially, after the constructor is called, the new query is totally separate from the existing path network inside of the NetworkIntegrator object. Thus, initially, the two are totally un-integrated. Eventually, the query and the network will be totally integrated, in which case the instance encapsulates a valid path network that totally contains the new query and could be directly executed by the system. An instance of the NetworkIntegrator class may also hold an intermediate level of integration, where the new query is only partially integrated into the existing path network.
4.2 The Enumerator Method
The most important method of the NetworkIntegrator class is the "Enumerate" method. A call to foo.Enumerate() on a NetworkIntegrator object foo returns a set of many new NetworkIntegrator objects. Every NetworkIntegrator object bar that is in this return set is "slightly more integrated" than foo. That is, in bar some small additional
part of the new query has been inserted into the existing path network compared to
the extent to which the query was in the network in foo. The fact that many different
NetworkIntegrator objects are returned from a call to foo.Enumerate() allows for the
Enumerate method to return many possible ways to more tightly couple the new query
with the existing network in foo. In fact, a call to foo.Enumerate() generally returns all
possible ways to perform one more step of the integration, regardless of how desirable
those steps are.
4.3 The Cost Function
To help in differentiating among the possible ways to perform the integration, the
NetworkIntegrator class also has a ”Coster” method. This method measures the goodness
of the current (possibly partial) integration. This method returns an integer value that
denotes the number of tuples in the path network. foo.Coster() can also take into account
classical query optimization considerations, such as the join ordering for the new query
in the network. If the join ordering is poor, then foo.Coster() might return a larger value
compared to an integration with a high-quality join ordering.
It is important to note that while costing a partially integrated path network,
returning the number of tuples in partially integrated path network is not enough. If cost
function only approximates the number of tuples in partially integrated path network,
then the optimizer will always join the smaller tables first. This might lead to local
optimum while ignoring global optimum solutions in some case. Hence, the cost function
is accompanied by a mini-search that tries to predict the final path network with a very
simple search. This predicted path network is then costed and the number of tuples for it
is returned rather than the partially integrated path network.
4.4 The Search Strategy
The reason for defining the "NetworkIntegrator" class is that it totally decouples the
search strategy (that is, the way in which a high-quality integration is obtained) from
the integration mechanism, which is embodied by the NetworkIntegrator class. Given an
implementation of the NetworkIntegrator class, almost any search strategy can be used. For example, the following pseudo-code would implement a greedy search strategy, using a NetworkIntegrator object foo:
```plaintext
while (temp <- foo.Enumerate ()) is not empty:
bestcost = inf
for bar in temp, do:
if bar.GetCost () < bestCost
bestCost <- bar.GetCost ()
nextStep <- bar
end if
end for
foo <- nextStep
end while
```
Or, one could extend the greedy strategy to always keep the 10 best solutions so far. This would allow for a broader search, and could be done by adding a priority queue to the loop. In the following, I assume that the declaration:
```plaintext
PriorityQ Q (10)
```
returns a priority queue that has 10 slots in it. Any time that more than an 11 item is inserted into the queue, the item with the worst score is removed from the queue. Given this, the following pseudo-code implements a slightly more intelligent search strategy:
```plaintext
PriorityQ Q (10)
temp <- foo.Enumerate ()
for bar in temp, do:
Q.insert (bar, bar.GetCost ())
```
---
1 Note that the pseudo code is intended to express the design and not the implementation.
while (TRUE)
PriorityQ NewQ (10)
while (Q.Remove (foo))
temp <- foo.Enumerate ()
if temp is empty:
return foo as the best network
end if
for bar in temp, do:
NewQ.insert (bar, bar.GetCost ())
end for
end while
Q <- NewQ
end while
CHAPTER 5
IMPLEMENTATION
5.1 Types
The network integrator consists of two objects, namely the path network and the query description. Both the path network and the query description are of type graph. The graph is a network of waypoints and is represented using the adjacency list structure. To simplify the code and interaction with the execution engine, each waypoint is identified by an identifier which is generated by the Query Manager component\(^1\). The waypoints are stored in a hash table with identifier as the key for faster access. Each waypoint also contains a list of predicates.
The current implementation only supports Select-Project-Join (SPJ) queries. It does not support sub queries, but can be extended easily by treating the sub queries as a new query and pipelining its result to the main SPJ query. Each predicate is associated with the query identifier. The predicate can be of the following type:
1. **The join predicate**: It is of the form
\[\text{Table1.Attribute1 operator Table2.Attribute2}\].
2. **The selection predicate**: There are three types of selection predicates. The first type is of the form \[\text{Table1.Attribute1 operator constant}\], the second type is of the form \[\text{Table1.Attribute1 operator Table1.Attribute2}\] and the third type is an Empty selection which simply bypasses the data without any computation.
3. **The table scan predicate**: The job of the table scan waypoint is to scan the table and push the data through the memory hierarchy. There is only one table scan waypoint per table. However, the table scan waypoint can contain many table scan predicates each representing different queries.
4. **The top predicate**: This is a big waypoint which is pushed at the top of the query plan that performs aggregation, projection and other non-join operations.
---
\(^1\) Each query and the waypoint in the system has an identifier associated with it. The job of the query manager is to generate and maintain these identifiers.
5.2 Enumeration
The *enumerate* method gets a network integrator object and returns a list of next possible network integrator objects. This method does not in any way affect the search strategy. For example, the search strategy such as look-ahead can enumerate more than once (depending on the look-ahead depth) before deciding which network integrator object should direct the search. To find next possible network integrator objects, the *enumerate* method gets every remaining predicate $P_{QD}$ in the query description and tries to perform following three operations on every waypoint $W_{PN}$ in the path network. Let $P_{PN}$ be any predicate in the waypoint $W_{PN}$ and $W_{QD}$ be the waypoint that has the predicate $P_{QD}$.
1. **Mapping**: If the predicate $P_{QD}$ can be mapped onto the predicate $P_{PN}$, then the predicate $P_{QD}$ is added to the list of predicates of the waypoint $W_{PN}$. The rules for mapping the predicates are discussed later in the section 5.3.
2. **Bypass**: If the predicate $P_{QD}$ cannot be mapped onto the predicate $P_{PN}$, then it tries to find out whether they are bypassable or not. The rules for bypassing a waypoint is discussed in the section 5.4. If the predicates are bypassable, then a new predicate $P_{Bypassable}$, it created and added to the waypoint $W_{PN}$. The Path Optimizer also recursively checks for the bypassable parents and adds the bypass predicates to them.
3. **New waypoint**: Irrespective of whether the predicates $P_{QD}$ and $P_{PN}$ are mappable or not, a new waypoint is created with the predicate $P_{QD}$ in the path network.
The detailed algorithm for enumeration is given below (see Algorithm 1).
**Algorithm 1: Enumeration Algorithm**
**Input:** network integrator object \((PN, QD)\)
**Output:** list of network integrator objects
Let \(PN\) = Input Path Network;
and \(QD\) = Input Query Description;
and \(returnList\) = list of network integrator objects to be returned (initially empty);
**foreach** predicate \(P_{QD}\) in the query description \(QD\) **do**
**foreach** waypoint \(W_{PN}\) in the path network \(PN\) **do**
Let \(P_{PN}\) be any predicate of \(W_{PN}\);
if \(is\text{Mappable}(P_{QD}, P_{PN})\) then
Create a deep copy of the path network \(PN\);
Map \(P_{QD}\) onto \(W_{PN-Copy}\) of the copy;
Add PN-Copy to the returnList;
end
else if \(is\text{Bypassable}(P_{QD}, P_{PN})\) then
Create a deep copy of the path network \(PN\);
Add the bypass predicates in the child waypoints;
Map \(P_{QD}\) onto \(W_{PN-Copy}\) of the copy;
Add PN-Copy to the returnList;
end
Create a deep copy of the path network \(PN\);
Add a new waypoint with the predicate \(P_{QD}\) in the PN-Copy;
Add PN-Copy to the returnList;
end
end
5.3 Mapping Rules
The two predicates \(P_1\) and \(P_2\) can be mapped if they satisfy following criteria:
1. Both the predicates are of the same type. For example, if \( P_1 \) is a selection predicate and \( P_2 \) is a join predicate, they cannot be mapped.
2. If both the predicates are table scan or selection predicates and work on the same table, then they can be mapped else they cannot be mapped. For example, if \( P_1 \) is predicate of the form `nation.n_name = 'US'` and \( P_2 \) is predicate of the form `orders.o_orderstatus = 'F'`, then they cannot be mapped because they have different tables.
3. If both the predicates are join predicates, the left hand side table and attribute of the predicate \( P_1 \) should be same as either left or right hand side table and attribute of the predicate \( P_2 \). For example, the predicate `lineitem.l_suppkey = supplier.s_suppkey` can be mapped onto the predicate `lineitem.l_suppkey = partsupp.ps_suppkey`.
4. To keep the algorithm simple, the top predicates are not mappable.
### 5.4 Bypassable Rules
In some cases, bypassing a waypoint is helpful to reduce the data flow in the path network. For example, consider a path network shown in the figure 5-1, that has the join of lineitem and orders followed by the join of lineitem and supplier.

Figure 5-1. Path network before bypassing
Say, if the new query is the join of lineitem and partsupp, then the figure 5-2 shows the path network with bypass waypoints where as the figure 5-3 shows the path network without bypassing. Clearly, the former path network has less data flow than the latter path network.
Figure 5-2. Final path network with bypassing
Figure 5-3. Final path network without bypassing
Figure 5-4. Example path network for bypassing
Only left hand side tables can be bypassed. This means if the new query had a join of orders and partsupp, then we cannot bypass. Bypassing rules are applied recursively, hence the tables involved in the new query should be on left stem of the child. For example, consider the path network shown in figure 5-4. Only a query with join of Tbl1 and Tbl5 can be bypassed for Join F. All other tables are right hand side tables for at least one join. Though Tbl3 is on left hand side of Join B, but it is on right hand side of Join D, hence it cannot be consider for bypassing.
5.5 The Cost Function
Given a partially integrated path network, the cost function first converts it to a fully integrated path network by performing a mini-search. Mini-search is a simple function that uses very simple heuristics to find the fully integrated path network. It is important to note that this fully integrated path network is only used to improve the costing and does not affect the search strategy. Once a fully integrated path network is found, the costing is performed.
The detailed algorithm for costing is given below (see Algorithm 2).
**Algorithm 2: Cost Algorithm**
**Input:** A Network Integrator object
**Output:** An Integer Cost
Let PN = Input Path Network and QD = Input Query Description;
Let Full-PN = Mini-Search(PN, QD) and H = Hashtbl of (Waypoint, Flow);
**foreach** waypoint W in Full-PN **do**
Let I be the set of input waypoints and F be the output flow of W;
**foreach** input Iₖ in the set I **do**
| if Waypointₖ not present in H then |
| Add (Waypointₖ, Flowₖ) in H; |
**end**
**end**
if W is a join waypoint then
**foreach** predicate P in the waypoint W **do**
| Let S be the selectivity factor of P; |
| if Iᵢ and Iⱼ are the inputs for P then |
| Fᵢ = S * Iᵢ * Iⱼ; |
| end |
| end |
| F = max(Fᵢ); |
**end**
else if W is a selection waypoint then
**foreach** predicate P in the waypoint W **do**
| Let Sᵢ be the selectivity factor of P; |
| end |
| F = Input * (1 - (1 - S₁) * (1 - S₂) * ... * (1 - Sₖ)); |
**end**
Return the sum of all the flows in the path network Full – PN.
Here we make a simple assumption that the tuples in the join predicate with the maximum flow subsumes the tuples in the remaining join predicates of the same waypoint. However, this assumption does not apply to all the cases, it provides a good approximation of the data flow in the system.
The selectivity factor for each predicate is calculated using the statistics provided by the Statistics module and the method described in [21] and [8]. The table 5-1 gives the selectivity factor for various cases.
Table 5-1. Selectivity Factor
<table>
<thead>
<tr>
<th>Type of predicate</th>
<th>Condition</th>
<th>Selectivity factor</th>
</tr>
</thead>
<tbody>
<tr>
<td>Selection</td>
<td>σ_{R.A=const}</td>
<td>\frac{1}{ValueCount(R.A)}</td>
</tr>
<tr>
<td>Selection</td>
<td>σ_{R.A<const}</td>
<td>\frac{1}{3}</td>
</tr>
<tr>
<td>Join</td>
<td>△_{R.A=S.B}</td>
<td>\frac{1}{max(ValueCount(R.A), ValueCount(S.B))}</td>
</tr>
</tbody>
</table>
5.6 The Search Strategy
The search strategy used in this thesis is a look-ahead search with user-specified look-ahead depth. The search function is a recursive function that uses enumerate method and cost function to find the final path network. It is important to note that these three function are independent of each other and any of them can be replace by an equivalent function without affecting the others. For example, the look-ahead search can be replaced by a greedy or exhaustive search without affecting the enumerate or cost function.
\footnote{In table 5-1, ValueCount(R.A) means number of distinct values of attribute A in relation R.}
The detailed algorithm for the search is given below (see Algorithm 3).
<table>
<thead>
<tr>
<th>Algorithm 3: Search Algorithm</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Input:</strong> List of Network Integrator objects: lni</td>
</tr>
<tr>
<td><strong>Output:</strong> A fully integrated path network</td>
</tr>
</tbody>
</table>
```plaintext
foreach Path network PN in lni do
if Is PN fully integrated then
Return PN;
end
else
Perform Look-Ahead on PN;
Let newLNI be list of new network integrator objects from look-ahead;
Recursively call this algorithm using newLNI;
end
end
```
CHAPTER 6
EXPERIMENTAL RESULTS
6.1 Goal
Using the experiment, I compare the proposed algorithm that uses a look-ahead search, mini-search (while costing) and data-centric cost function with other family of algorithms. For comparison, I use an objective function that counts the number of tuples in the path network. This function has a bias towards the data-centric cost function. In fact, the better way to compare these algorithms would be to run the queries for different path networks on the Datapath system. However, the execution engine of the Datapath system is not fully implemented and hence I use the above objective function. Also, I compare the family of algorithms based on the time taken to generate the path network.
6.2 Setup
For the sake of comparing different search techniques with the proposed algorithm, I have created a framework that treats query optimization as a state-space search problem. Using this framework, the Path Optimizer searches for the solution by using a top-down approach on the search tree.
The framework takes a configuration object that specifies three important parameters:
1. **Search algorithm**: The search algorithm can be exhaustive, greedy or look-ahead. The search algorithm takes a list of network integrator objects and returns a list of next possible network integrator objects.
2. **Selector function**: The selector function takes as input a list of network integrator objects and returns the best possible network integrator objects depending on the algorithm. The current framework supports two blind selector functions (i.e. FIFO and Random) and two cost based selector functions.
3. **Cost function**: The framework allows two cost based selectors, namely the proposed data-centric cost function which counts the number of tuples and a compute-centric cost function that counts the number of waypoints or the computations.
It is important to note that every search algorithm calls the `enumerate` method. The exhaustive search algorithm recursively calls enumerates on all possible network integrator objects.
objects. The greedy search algorithm prunes the branches of the search tree based on
the selector function and hence only enumerates a small subset of the possible network
integrator objects. A look-ahead search however, does not take an immediate greedy
decision before pruning, but enumerates until few extra levels of the search tree. This
improves the quality of the result found by the look-ahead search. It is important to note
that a look-ahead search with zero depth simulates a pure greedy approach, whereas a
look-ahead search with an infinite depth simulates an exhaustive search. The figure 6-1
shows different modules of the framework and their interfaces.
![Diagram of the framework with labels: Input: Existing Path network and query description, ni Search(Ini), ni Selector(Ini), ni – network integrator, Ini – list of network integrator objects, Mapping Rules, Bypassing Rules, While (I isIntegrationDone), Ini Enumerate(ni), Least cost ini, Statistics.]
Figure 6-1. Framework for testing different query optimization techniques
The Path Optimizer is tested on 8 TPC-H queries¹. These queries are randomly
shuffled and are incrementally given to the Path Optimizer. The same sequence of queries
are also given to different combinations of the search algorithms, selector functions and
the cost functions. The framework is tested on ten random input orderings and the
cost of final path network and also the time taken by each algorithm is recorded into a
¹ The TPC-H query 2, 3, 5, 10, 11, 18, 20 and 21 are tested using the given framework.
comma-separated-value (csv) file. The framework also generates a PDF file which displays the final path network for each path network using GraphViz software[1].
6.3 Experimental Results
The table 6-1 shows the cost and the time taken by each algorithm.
The figure 6-2 compares the average cost of the FIFO selector with that of other selectors.

Figure 6-2. Comparison of FIFO with other selectors
The figure 6-3 compares the average cost of the Random selector with the average cost of the cost-based selectors.
The figure 6-4 compares the average cost of the cost-based selectors.
The figure 6-5 compares the average time taken by all the selectors.
6.4 Analysis
The above results show that the exhaustive search always gives the best results, while greedy search usually gives the worst results. Also, the look-ahead search gives the results very similar to the exhaustive search. For less than eight input queries, the
Figure 6-3. Comparison of Random selector with the cost based selectors
Figure 6-4. Comparison of the cost based selectors
Table 6-1. Cost and Time taken by each algorithm
<table>
<thead>
<tr>
<th>Search</th>
<th>Selector</th>
<th>Avg cost</th>
<th>Max cost</th>
<th>Min cost</th>
<th>Avg time</th>
<th>Max time</th>
<th>Min time</th>
</tr>
</thead>
<tbody>
<tr>
<td>Exhaustive</td>
<td>Costbased with mini-search</td>
<td>3308260720</td>
<td>4339400090</td>
<td>2146320100</td>
<td>180.13</td>
<td>312.22</td>
<td>80.91</td>
</tr>
<tr>
<td>Exhaustive</td>
<td>Costbased without mini-search</td>
<td>3449952840</td>
<td>4339400095</td>
<td>2912333459</td>
<td>162.5</td>
<td>312.27</td>
<td>85.99</td>
</tr>
<tr>
<td>Exhaustive</td>
<td>Waypoint count</td>
<td>4395383130</td>
<td>8972215000</td>
<td>1440000400</td>
<td>25.903</td>
<td>73.17</td>
<td>3.37</td>
</tr>
<tr>
<td>Exhaustive</td>
<td>FIFO</td>
<td>2.05728E+12</td>
<td>8.1005E+12</td>
<td>1440000555</td>
<td>33.904</td>
<td>104.25</td>
<td>4.17</td>
</tr>
<tr>
<td>Exhaustive</td>
<td>Random</td>
<td>14768863045</td>
<td>7421866790</td>
<td>1520010980</td>
<td>41.712</td>
<td>119.29</td>
<td>3.98</td>
</tr>
<tr>
<td>Greedy</td>
<td>Costbased with mini-search</td>
<td>3746172230</td>
<td>4769866765</td>
<td>3348026765</td>
<td>36.827</td>
<td>74.72</td>
<td>10.85</td>
</tr>
<tr>
<td>Greedy</td>
<td>Costbased without mini-search</td>
<td>3507063135</td>
<td>3640986771</td>
<td>3251026765</td>
<td>36.997</td>
<td>75.28</td>
<td>10.87</td>
</tr>
<tr>
<td>Greedy</td>
<td>Waypoint count</td>
<td>22552508025</td>
<td>65898400180</td>
<td>2572666700</td>
<td>0.493</td>
<td>0.56</td>
<td>0.305</td>
</tr>
<tr>
<td>Greedy</td>
<td>FIFO</td>
<td>2.96523E+12</td>
<td>1.60001E+13</td>
<td>4.91044E+11</td>
<td>0.692</td>
<td>0.8</td>
<td>0.407</td>
</tr>
<tr>
<td>Greedy</td>
<td>Random</td>
<td>64181229885</td>
<td>94817668050</td>
<td>16000632860</td>
<td>0.643</td>
<td>0.84</td>
<td>0.409</td>
</tr>
<tr>
<td>Look-ahead</td>
<td>Costbased with mini-search</td>
<td>3385487380</td>
<td>4470200090</td>
<td>2629520100</td>
<td>71.268</td>
<td>109.94</td>
<td>33.27</td>
</tr>
<tr>
<td>Look-ahead</td>
<td>Costbased without mini-search</td>
<td>3444960100</td>
<td>4554400090</td>
<td>2713720100</td>
<td>71.061</td>
<td>110.68</td>
<td>33.18</td>
</tr>
<tr>
<td>Look-ahead</td>
<td>Waypoint count</td>
<td>15058316550</td>
<td>32314505050</td>
<td>8640000000</td>
<td>0.426</td>
<td>0.52</td>
<td>0.281</td>
</tr>
<tr>
<td>Look-ahead</td>
<td>FIFO</td>
<td>2.23372E+12</td>
<td>9.6E+12</td>
<td>6480604050</td>
<td>0.536</td>
<td>0.63</td>
<td>0.322</td>
</tr>
<tr>
<td>Look-ahead</td>
<td>Random</td>
<td>45932428745</td>
<td>79600156560</td>
<td>2800056210</td>
<td>0.612</td>
<td>0.69</td>
<td>0.372</td>
</tr>
</tbody>
</table>
look-ahead depth of 1 is sufficient in most cases and performs as good as the depth of 2 or 3. The time taken by an algorithm depends upon the number of network integrator object it enumerates. Hence, exhaustive search takes a lot more time than the look-ahead
or greedy search. Though greedy search takes less time, it does not perform as good as the look-ahead search (see table 6-1). Therefore, the proposed algorithm uses the look-ahead search.
Also, the costing of a network integrator object is a time-consuming operation. In fact, time taken by blind-selectors and exhaustive search is almost equal to the time taken by the data-centric cost-based selectors using a greedy search.
Though cost based selectors take more time than the blind selectors, they usually provide the path network with orders of magnitude less number of tuples than the blind selectors. Due to the ordering of folding function, the FIFO selector tries to select the path network with extra waypoints. In fact, FIFO acts as a single query optimizer because it always tries to introduce new flows in the network and hence produces worst results. The figure 6-2 shows that mapping waypoints provides significant gain over single query optimization. Random and WaypointCount (compute-centric) cost function are both bad. However, compute-centric (or the waypoint count) cost-based selector performs well for exhaustive search (but not better than data-centric function). This is because
the exhaustive search takes the decision at the end after all the enumeration has been completed. Also, lower number of waypoints generally have less flow, especially for TPCH queries where joins are usually done on similar tables and only on primary keys. For look-ahead search, compute-centric (or the waypoint count) cost-based selector does not perform well (see figure 6-4). Hence, the proposed algorithm uses the data-centric cost function rather than blind selectors or compute-centric (or the waypoint count) cost-based selector.
The above results show that statistically data-centric cost-based selector performs better than waypoint-count cost based selector. The example below explains the reason for this behaviour. Consider the test case where TPC-H query 11 is the first query and TPC-H query 5 is the second query.\(^2\)
Query 11:
```
select *
from partsupp, supplier, nation
where
ps_suppkey = s_suppkey and s_nationkey = n_nationkey
and n_name = '[NATION]'
```
Query 5:
```
select *
from customer, orders, lineitem, supplier, nation, region
where
c_custkey = o_custkey and l_orderkey = o_orderkey
and l_suppkey = s_suppkey and c_nationkey = s_nationkey
and s_nationkey = n_nationkey and n_regionkey = r_regionkey
```
\(^2\) The query 5 and 11 are simplified to work for the optimizer. For example, the projection and aggregation operators are ignored.
and r_name = 'REGION' and o_orderdate >= 99990101
For query 11 both data-centric and waypoint-count selectors produce same path network. This path network is shown in the figure 6-6. But when query 5 is integrated onto the path network with query 11, the path network generated by waypoint-count selector is shown in the figure 6-7 and that generated by the data-centric selector is shown in the figure 6-8\(^3\). Note that both path network have same number of waypoints. So, waypoint-count selector treats both of them equally good and choses 6-7. In the path network 6-7, orders and customer tables are joined after lineitem. It is clear that having this join lower down the query plan is a better choice as it produces less flow. The data-centric selector is cognizant of this fact and hence choses 6-8. Also, the above experimental results attest that the path network selected by data-centric selector has lower flow than the waypoint-count selector.
\[\begin{array}{c}
p_{s\_suppkey} = s\_suppkey (Q: 11) \\
\text{Selection (Q: 11)} \\
p_{n\_nationkey} = n\_nationkey (Q: 11) \\
\text{Selection (Q: 11)} \\
partsupp (Q: 11) \\
\text{Supplier (Q: 11)} \\
nation (Q: 11) \\
\end{array} \]
Figure 6-6. Path network after query 11
Mini-search performs well for exhaustive and look-ahead but not for greedy. This is because it tries to predict the future join ordering and does not simply join the smaller
\(^{3}\) The dotted edges represents less flow than the dashed edges and the dashed edges has less flow than the solid edges.
Figure 6-7. Path network after query 5 for waypoint-count selector
Figure 6-8. Path network after query 5 for cost-based selector
tables first. However, since this is only a prediction based on some simple heuristics, it does not always work for greedy strategies. Also, mini-search does not incur any significant overhead with respect to time. Hence, the proposed algorithm uses mini-search.
CHAPTER 7
CONCLUSION
Since no conventional multi-query optimizers are suitable for the data-centric databases (like the Datapath system), I have proposed an algorithm that optimizes the queries for the Datapath system. I have also tested and compared various search strategies against the proposed algorithm using a data-centric cost function. The experimental results show that the proposed algorithm produces a good path network (or global query plan) in reasonable amount of time.
CHAPTER 8
FUTURE WORK
The Path Optimizer only supports the mapping of join and selection predicates. I plan to introduce mapping rules for the top predicate (i.e group-by and order-by) and also modify the path optimizer to support sub-queries.
Also, the Path Optimizer assumes that all the queries start their execution at the same time. Though this assumption simplifies the optimization process, it does not account for the state of execution engine. Also, the Path optimizer relies only on the Statistics module for the cost function and hence is not adaptive. The Path Optimizer could be improved by considering the feedback regarding the state of execution engine and also the execution time for each waypoint from the execution engine.
The cost function assumes that the predicate with maximum number of tuples subsumes the predicates with fewer tuples. Hence, the cost function ignores the extra tuples that are not part of the larger predicate but increases the flow of data through the path network.
Also, I intend to improve the performance of the algorithm so that it can produce a reasonable path network in less time. The current algorithm only integrates one query at a time. This could easily be modified to produce a good path network for batch of queries by reordering the input queries.
REFERENCES
BIOGRAPHICAL SKETCH
Niketan R. Pansare received his Bachelor of Engineering degree in Information Technology from Veermata Jijabai Institute of Technology in 2006. He then received his Master of Science degree in Computer Engineering from the University of Florida in Fall 2009. His primary research is focused on Database and Machine Learning.
|
{"Source-Url": "http://ufdcimages.uflib.ufl.edu:80/UF/E0/02/51/40/00001/pansare_n.pdf", "len_cl100k_base": 13222, "olmocr-version": "0.1.50", "pdf-total-pages": 49, "total-fallback-pages": 0, "total-input-tokens": 88822, "total-output-tokens": 16458, "length": "2e13", "weborganizer": {"__label__adult": 0.0003459453582763672, "__label__art_design": 0.0004100799560546875, "__label__crime_law": 0.0003879070281982422, "__label__education_jobs": 0.003215789794921875, "__label__entertainment": 9.709596633911131e-05, "__label__fashion_beauty": 0.00017392635345458984, "__label__finance_business": 0.0005140304565429688, "__label__food_dining": 0.00036406517028808594, "__label__games": 0.0006728172302246094, "__label__hardware": 0.0011310577392578125, "__label__health": 0.0005383491516113281, "__label__history": 0.0003592967987060547, "__label__home_hobbies": 0.00011789798736572266, "__label__industrial": 0.0004849433898925781, "__label__literature": 0.0004382133483886719, "__label__politics": 0.0002551078796386719, "__label__religion": 0.0004696846008300781, "__label__science_tech": 0.0965576171875, "__label__social_life": 0.0001251697540283203, "__label__software": 0.0181121826171875, "__label__software_dev": 0.87451171875, "__label__sports_fitness": 0.00021839141845703125, "__label__transportation": 0.00047898292541503906, "__label__travel": 0.0002036094665527344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59276, 0.04027]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59276, 0.40179]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59276, 0.87742]], "google_gemma-3-12b-it_contains_pii": [[0, 252, false], [252, 252, null], [252, 289, null], [289, 401, null], [401, 2052, null], [2052, 2052, null], [2052, 2196, null], [2196, 3228, null], [3228, 3827, null], [3827, 5923, null], [5923, 7589, null], [7589, 8942, null], [8942, 9848, null], [9848, 11167, null], [11167, 13526, null], [13526, 15366, null], [15366, 17517, null], [17517, 19567, null], [19567, 21717, null], [21717, 23939, null], [23939, 24213, null], [24213, 26141, null], [26141, 28249, null], [28249, 29440, null], [29440, 29751, null], [29751, 31754, null], [31754, 33372, null], [33372, 34623, null], [34623, 36184, null], [36184, 36328, null], [36328, 37391, null], [37391, 38451, null], [38451, 39962, null], [39962, 40483, null], [40483, 42562, null], [42562, 44125, null], [44125, 45108, null], [45108, 45232, null], [45232, 47812, null], [47812, 49017, null], [49017, 50394, null], [50394, 51933, null], [51933, 52064, null], [52064, 52327, null], [52327, 52812, null], [52812, 54121, null], [54121, 56532, null], [56532, 58931, null], [58931, 59276, null]], "google_gemma-3-12b-it_is_public_document": [[0, 252, true], [252, 252, null], [252, 289, null], [289, 401, null], [401, 2052, null], [2052, 2052, null], [2052, 2196, null], [2196, 3228, null], [3228, 3827, null], [3827, 5923, null], [5923, 7589, null], [7589, 8942, null], [8942, 9848, null], [9848, 11167, null], [11167, 13526, null], [13526, 15366, null], [15366, 17517, null], [17517, 19567, null], [19567, 21717, null], [21717, 23939, null], [23939, 24213, null], [24213, 26141, null], [26141, 28249, null], [28249, 29440, null], [29440, 29751, null], [29751, 31754, null], [31754, 33372, null], [33372, 34623, null], [34623, 36184, null], [36184, 36328, null], [36328, 37391, null], [37391, 38451, null], [38451, 39962, null], [39962, 40483, null], [40483, 42562, null], [42562, 44125, null], [44125, 45108, null], [45108, 45232, null], [45232, 47812, null], [47812, 49017, null], [49017, 50394, null], [50394, 51933, null], [51933, 52064, null], [52064, 52327, null], [52327, 52812, null], [52812, 54121, null], [54121, 56532, null], [56532, 58931, null], [58931, 59276, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59276, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59276, null]], "pdf_page_numbers": [[0, 252, 1], [252, 252, 2], [252, 289, 3], [289, 401, 4], [401, 2052, 5], [2052, 2052, 6], [2052, 2196, 7], [2196, 3228, 8], [3228, 3827, 9], [3827, 5923, 10], [5923, 7589, 11], [7589, 8942, 12], [8942, 9848, 13], [9848, 11167, 14], [11167, 13526, 15], [13526, 15366, 16], [15366, 17517, 17], [17517, 19567, 18], [19567, 21717, 19], [21717, 23939, 20], [23939, 24213, 21], [24213, 26141, 22], [26141, 28249, 23], [28249, 29440, 24], [29440, 29751, 25], [29751, 31754, 26], [31754, 33372, 27], [33372, 34623, 28], [34623, 36184, 29], [36184, 36328, 30], [36328, 37391, 31], [37391, 38451, 32], [38451, 39962, 33], [39962, 40483, 34], [40483, 42562, 35], [42562, 44125, 36], [44125, 45108, 37], [45108, 45232, 38], [45232, 47812, 39], [47812, 49017, 40], [49017, 50394, 41], [50394, 51933, 42], [51933, 52064, 43], [52064, 52327, 44], [52327, 52812, 45], [52812, 54121, 46], [54121, 56532, 47], [56532, 58931, 48], [58931, 59276, 49]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59276, 0.1893]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
8cfbbee312753787435055a5feb17b47eec3ef60
|
Live Update for Device Drivers
Michael M. Swift, Damien Martin-Guillerez, Muthukaruppan Annamalai, Brian N. Bershad, and Henry M. Levy
Department of Computer Science and Engineering
University of Washington, Seattle, WA 98195 USA
{mikesw,muthu,bershad,levy}@cs.washington.edu,
Damien.Martin-Guillerez@eleves.bretagne.ens-cachan.fr
Abstract
As commodity operating systems become more reliable and fault-tolerant, the availability of a system will be determined not by when it crashes, but instead by when it must be shutdown and rebooted due to software maintenance [12, 21]. While many system components can be upgraded on-line, critical low-level components, such as device drivers and other kernel extensions, cannot be updated without rebooting the entire operating system.
In this paper, we present Live Update, a mechanism that allows device drivers to be updated without rebooting the system. Unlike other on-line update mechanisms, our system supports existing drivers “as is”. Thus, thousands of existing device drivers can be updated transparently. In experiments we show that Live Update can upgrade existing drivers without rebooting and that the system imposes very little performance overhead.
1 Introduction
Commodity operating systems, such as Linux and Windows, are becoming more reliable. Each successive release provides more functionality with fewer crashes than the previous [21][20][5]. This reliability trend is enabled by a combination of natural maturity and recent technologies that eliminate bugs automatically [7][2] or that tolerate failure when it occurs [29][9][18][25]. However, even with these improvements, operating systems require scheduled downtime for maintenance of certain components [21][12]. For example, components the OS itself depends on, such as storage drivers, generally cannot be replaced without rebooting. Thus, scheduled downtime promises to be the ultimate limiter of system availability because operating systems cannot replace all running code on-line.
This problem is compounded by the increasing rate of software updates. Previously, manufacturers had to distribute a CD or floppy disk to release an update. Now, Internet services such as Windows Update [19], Apple’s Software Update [1], and Red Hat Network [23] greatly lower the cost and complexity of releasing updates. While improving the average quality of running software, frequent software updates may in fact decrease the availability of many systems when updates need to reboot the system [26].
Device drivers represent a large portion of this problem because they are both critical to OS operation and frequently updated. For example, Linux IDE storage drivers, needed by the OS for virtual memory swapping, were updated more than 67 times in three years. Furthermore, updating device drivers is inherently risky, because a faulty device driver may prevent the system from booting. To achieve high availability, operating systems must be able to replace critical device drivers without rebooting the entire system.
This paper presents a new mechanism, called Live Update, that updates device drivers in place without rebooting the operating system. Our mechanism uses shadow drivers [28] to reinitialize the updated driver transparently to the operating system and applications. In addition, the shadow driver transfers the state of the old driver to the new driver automatically, ensuring that driver requests will continue to execute correctly after the update. Live Update improves availability by updating drivers without rebooting the OS, updating drivers without restarting applications that use an updated driver, and rolling back driver updates that do not work.
Updating drivers on-line presents three major challenges. First, there are thousands of existing drivers, many of which will eventually require an update. To make Live Update practical, we need to be able to update these drivers without any work on the part of the drivers’ authors. Previous systems for updating modules on-line require that a skilled programmer write code to transfer data between the old and new modules [8][6][15][22]. In contrast, our system uses the pre-existing driver interface to transfer state between driver versions, allowing it to update drivers on-line without driver modifications. Second, an updated device driver may not be compatible with the running version and could cause applications
or the OS to crash. Thus, Live Update must ensure that an update is safe and does not contain incompatibilities that could compromise system reliability. Lastly, device drivers can be critical to overall system performance, so the update mechanism must impose little overhead when not actively applying an update.
We implemented Live Update for sound, network, and storage drivers in a version of the Linux operating system. Our results show that Live Update (1) minimally impacts system performance, (2) allows transparent, on-line upgrade between a wide range of driver versions, and (3) can be used without changing existing drivers.
The rest of this paper describes the design, implementation and performance of Live Update. The following section reviews previous approaches to updating code on-line. Section 3 discusses the unique issues that arise when updating device drivers. Section 4 describes the design and implementation of Live Update. Section 5 presents experiments that evaluate the effectiveness and performance of our system, and Section 6 summarizes our work.
2 Related Work
Updating code on-line has long been a goal of high availability systems. Live Update focuses on updating a single OS component type, the device driver. By focusing on driver updates, we can leverage the properties of drivers to transparently resolve a major source of downtime while maintaining a low runtime overhead. Previous approaches differ from our work in terms of the programmer’s responsibility and the update mechanisms and granularity. We discuss each of these in turn.
In terms of responsibility, previous on-line update systems typically require a programmer to provide code to facilitate the update. Some systems use compiler support for updating programs [17, 15]. While the program code itself need not change, a programmer must provide a function to translate data formats when they change. Other systems require that updatable code use special calling conventions [8], inherit from an “updatable” base class [16, 22], use an “updating” framework [27], or identify safe update locations in the code [14]. By leveraging the properties of the code being updated, a system can reduce the programmer’s role. For example, one system updates event handlers by running old and new versions in parallel until their outputs converge [10]. However, this approach still requires that a programmer write code to transfer the configuration of a handler.
In contrast, our system can update existing, unmodified modules without code specific to an individual module. We leverage the common interfaces of device drivers to automatically capture and transfer their state between versions. By centralizing the code for update in an operating system service, we eliminates the need to modify existing drivers.
In the past, two major mechanisms have been used to update code. The system can launch a copy of a running process with the new code, on the same hardware [13] or on additional hardware [24], and then copy in the state of the existing process. Or, the system can retain running code and redirect callers of an updated procedure to the new version. Redirection has been provided by programming frameworks that incorporate wrapper functions [8] [17, 27], class hierarchies mandating dynamically dispatched functions [16, 22, 6], and compilers that produce only indirect function calls [17, 15]. Live Update similarly redirects callers at updated drivers using wrapper functions. However, Live Update redirects calls both into and out of drivers to prevent a driver from calling the OS during an update, thereby concealing the update from the OS itself.
Previous systems have enabled update with varying granularity. Several systems replace single functions or lists of functions on-line [17, 8, 15]. Object-oriented approaches update an entire class [16, 4, 22]. Update mechanisms for modularized systems replace a single module at a time [27]. Because device drivers consist of multiple modules joined by internal interfaces, Live Update replaces entire drivers. This approach allows changes in the interfaces between driver modules, which increases the variety of updates that can be applied on-line.
Partial reboots, which avoid the need to reboot an entire system, have been proposed as a general technique for building highly available fault-tolerant systems [3, 4]. Partial reboots of device drivers avoid a whole-system reboot when a driver fails [29, 28]. Unlike previous work, where partial reboots were used to repair failed components, our system uses partial reboots to update components instead. The system shuts down the current driver and starts the new driver transparently to the driver’s callers.
3 Issues
Device drivers have unique characteristics that influence the design of an on-line update system. Drivers are commonly implemented as a set of modules that can be dynamically loaded into the OS kernel. They are organized into classes that share a common programming interface. The common interface allows the kernel and applications to access the device without being aware of the device’s specific characteristics. For example, all sound card drivers share a common interface, allowing a sound-playing application to access the sound card without having to manage the card itself.
The need to update existing unmodified driver code raises several design issues. First, the update system must
rely on the existing capabilities of drivers, such as dynamic loading, to initialize the new driver. As well, the update system must be responsible for transferring driver state because there is no code in existing drivers to transfer state between driver versions.
Second, because drivers assume exclusive access to devices and require access to the device to initialize, the old driver must be disabled while the new driver initializes. Thus, the device is unavailable during an update. Any portion of the update process that depends on a device being present (e.g., loading the new driver off a disk when updating the disk driver) must be performed before the old driver is disabled.
Finally, an updated driver may offer substantially different services or support different interfaces. For example, a new version of a driver may remove functions or capabilities provided by the prior version. The update system must be able to detect this situation and disallow the update.
4 Live Update: Design and Implementation
Live Update reflects a systems-oriented approach to updating device drivers on-line. Rather than relying on drivers to update themselves, Live Update is a service that updates drivers on their behalf. Three principles guide the design:
1. No new code. It is impractical to write new code for each driver.
2. Be transparent. Updates to drivers should be invisible to applications, the operating system, and even drivers.
3. Safety first. The system may disallow an update if it is not compatible with running code.
Our system must work with existing drivers because it is too hard, expensive, and error-prone to add on-line update support to drivers. With a systems-oriented approach, a single implementation can be deployed and used immediately with a large number of existing drivers. Thus, we centralize the update code in a single system service. As a common facility, the update code can be thoroughly examined and tested for faults. In contrast, practical experience has shown us that many drivers do not receive such scrutiny, and hence are more likely to fail during an update.
These principles limit the applicability of Live Update. Our solution only applies to drivers that can load and unload dynamically. If the driver cannot, then Live Update cannot replace the driver. Furthermore, our design only applies to drivers that share a common calling interface. A driver that uses a proprietary or ad-hoc interface cannot be automatically updated without additional code specialized to that driver. Finally, if the new driver supports dramatically different capabilities, then the update will fail because the scale of change cannot be hidden from the OS and applications.
Because of these limitations, we consider Live Update to be an optimization and preserve the possibility of falling back to a whole-system reboot if necessary.
4.1 Design Overview
Our system updates a driver by loading the new code into memory, shutting down the old driver, and starting the new driver. During the update, the Live Update system impersonates the driver, ensuring that its unavailability is hidden from applications and the OS. As the new driver starts, the system attaches it to the resources of the old driver and verifies that the new driver is compatible with the old driver. If it is not compatible, then the system can roll back the update. In essence, Live Update replaces the driver code and then reboots the driver.
In a whole-system reboot, the ephemeral state of a driver is lost. When only the driver is rebooted, though, the new driver must preserve the ephemeral state of the old driver, such as configuration parameters, so that application and OS requests can be processed correctly. Furthermore, the reboot must be concealed from applications, as they are generally unprepared to handle driver failures. Rather, they are written with the conventional failure model that drivers and the operating system either fail together or not at all, and therefore do not attempt to handle a driver failure.
Live Update uses shadow drivers [28] to safely reboot an updated device driver without impacting applications or the OS. A shadow driver is a kernel agent that is responsible for (1) rebooting a device driver, (2) restoring the driver’s state after a reboot, and (3) concealing the driver reboot from the OS and applications. Shadow drivers operate in two modes: passive and active. In passive mode, the shadow driver observes all communication between the driver and the kernel. During a driver reboot, the shadow switches to active mode, in which it shuts down and restarts the driver while impersonating the driver to the OS. Shadow drivers are normally in passive mode and only switch to active mode during a reboot.
A shadow driver is a “class driver,” aware of the interface to the drivers it shadows but not of their implementations. A single shadow driver implementation can reboot any driver in the class. Hence, an operating system can leverage a few implementations of shadow drivers to reboot a large number of device drivers. In addition, implementing a shadow driver does not require a detailed understanding of the internals of the drivers it shadows.
Table 1: Live Update process for updating a device driver.
<table>
<thead>
<tr>
<th>Update Steps</th>
</tr>
</thead>
<tbody>
<tr>
<td>1. Capture driver state</td>
</tr>
<tr>
<td>2. Load new code</td>
</tr>
<tr>
<td>3. Impersonate driver</td>
</tr>
<tr>
<td>4. Disable/unload old driver</td>
</tr>
<tr>
<td>5. Initialize new driver</td>
</tr>
<tr>
<td>6. Transfer driver state</td>
</tr>
<tr>
<td>7. Enable new driver</td>
</tr>
</tbody>
</table>
Rather, it requires only an understanding of those drivers’ interactions with the kernel.
Table 1 lists the steps of updating a driver. The process begins when a driver is initially loaded and the system starts capturing its state and ends after the driver reboots and the new driver begins processing requests. We now describe each of the update steps in more detail.
4.2 Capturing Driver State
The state of a device driver consists of the state it receives from hardware and the state it receives from the kernel. From hardware, a driver receives persistent data and environmental parameters, such as the speed of a network link, which need not be explicitly preserved when a driver is updated. From the kernel, the driver receives configuration and I/O requests. While configuration changes must persist across an update, completed I/O requests are forgotten by drivers and have little impact on future requests. Hence, they need not be retained after a driver update. As a result, the state of a driver is determined by the history of configuration requests it receives and the requests it is currently processing.
Live Update captures the state of a device driver by observing the communication between the driver and the kernel. When a driver loads, Live Update interposes wrappers on all function calls between the driver and the kernel. The wrappers serve two purposes: they provide taps that mirror communication to the shadow, and they provide a layer of indirection between a driver and the kernel that allows Live Update to redirect calls to a new driver. We discuss redirection in Section 4.6. From the taps, the shadow records information necessary to unload the old driver and initialize the new driver to a point where it can process requests correctly.
Each function call between the driver and the kernel invokes a tap. The tap first calls the function and then calls the shadow with the function’s parameters and result. From this communication, the shadow tracks the kernel objects currently in use by a driver in an object tracker. For example, the shadow records the I/O memory regions used by the driver. The shadow also records open connections to the driver and pending requests that the driver is processing. To capture the configuration of the driver, the shadow logs requests that set the driver’s options or parameters. From the information in the object tracker and log, the shadow driver can restore the driver’s internal state after a reboot. A sample shadow driver capturing driver state is shown in Figure 1.
4.3 Loading Updated Drivers
A system operator begins an update by loading the new driver code. As discussed in Section 3, the services of a driver are not available while it is rebooting. To avoid circular dependencies that could arise if updates require the services of the driver being updated, an operator must pre-load the new driver version into memory. As a result, the system can update disk drivers that store their own updates.
Live Update logically replaces entire drivers. When a driver consists of multiple independent modules, though, the system only replaces modules whose memory images change. In addition to updated modules, the system reloads modules that call into updated modules, in order to link them against the new code. As an optimization, Live Update reuses unchanged modules from memory.
By replacing the entire driver, the interfaces between a driver’s modules can be updated.
Figure 1 shows the new version loaded in memory alongside the existing version. Once the new code is in memory, an operator notifies Live Update to replace the driver. Because both versions are in memory during an update, the system can revert to the old driver if the update fails.
4.4 Impersonating the Driver
When an operator triggers an update, the shadow driver switches to active mode. The taps block direct communi-
cation between the kernel and the driver and instead route all requests to the shadow. The shadow driver acts as the kernel to the driver and as the driver to the kernel, and the details of updating a driver are left to the shadow. Communication in active mode is illustrated in Figure 2.
In active mode, the shadow impersonates the driver by handling requests on the driver’s behalf. The shadow may suspend some callers, but because drivers may take significant time to start, the shadow cannot suspend all callers without negatively impacting applications. Depending on the type of request, the shadow itself responds, either using information from the log or by queuing the request and returning to the caller immediately. The shadow driver later submits queued requests to the driver after the reboot completes. Thus, the shadow masks the unavailability of the driver, ensuring that the OS and applications continue to execute correctly.
4.5 Unloading the Old Driver
While impersonating the driver, the shadow begins the driver reboot by shutting down the old driver. The shadow disables the driver, waits for kernel threads to finish using the driver, and then releases the driver’s resources on its behalf. Thus, even a driver with bugs in its unload code can be updated safely.
The shadow releases the majority of the kernel objects it tracked. A few objects – those that the kernel uses to call the driver – must be retained in order to conceal the driver’s reboot from the kernel. For example, the shadow retains function pointers used by the kernel to call the driver.
In addition to releasing kernel objects, the shadow resets the old driver to its initial state so it can be used for rolling back an update. The shadow copies back the old driver’s initial code and data from clean versions saved when the driver was loaded. This process resets the old driver to the same state as the new driver, allowing it to be restarted if the update fails.
4.6 Initializing the New Driver
Once the old driver is unloaded, the shadow driver initializes the new driver with the same sequence of calls that the kernel makes when initializing a driver. By making these calls itself, the shadow conceals the driver’s initialization from the kernel proper. As the driver initializes, it calls into the kernel to register and acquire resources. Taps direct these calls to the shadow, which handles the calls on the kernel’s behalf by connecting the new driver to the old driver’s resources and registration. For example, when a driver calls to register itself with the kernel, the shadow updates the existing driver object in the kernel to reference the new driver instance.
The shadow faces two major challenges in initializing the new driver: identifying and updating the existing kernel objects that the new driver requests, and ensuring that the new driver is compatible with the old driver. We now discuss each of these challenges in detail.
4.6.1 Updating References
When the new driver requests a resource from the kernel or provides a resource to the kernel, the shadow driver must locate the corresponding resource belonging to the old driver. Once located, the shadow updates the resource to reference the new driver and returns it to the driver. The shadow must locate the corresponding resource from the old driver, and then safely update it to reference the new driver.
In most cases, drivers uniquely identify their kernel resources, which allows the shadow to locate the old driver’s corresponding resource. For example, drivers provide a unique name, device number, or MAC address when registering with the kernel, and unique memory addresses when requesting I/O regions. The shadow uses the unique identifier and resource type to locate the old driver’s resource in the object tracker.
Once located, the shadow updates the kernel resource to reflect differences between the old and new driver. For example, the new driver may provide additional functions or capabilities. Typically, the shadow relies on the indirection provided by wrappers to leave kernel objects unchanged. For example, the shadow updates wrappers to point to the new driver’s functions instead of changing function pointers in the kernel. Otherwise, the shadow updates the kernel object directly.
In some cases the driver passes a resource to the kernel without unique identification. The shadow updates these references after the new driver finishes initializing by repeating the calls to the driver that generated the resource in the first place. For example, when the kernel
opens a connection to a sound card driver, the driver returns a table of function pointers with no identifying device name or number. To transfer these function tables to the new driver, the shadow calls into the new driver to re-open every connection. The new driver returns its function table, allowing the shadow to update the connection’s table to point to the new driver.
4.6.2 Detecting Incompatibilities
A major problem when updating unmodified code is ensuring that an update is compatible with the running code. If an update is not compatible, then applying it may cause the OS and applications to fail. Incompatibilities arise when a new driver version implements different functions (e.g., higher-performance methods), different interfaces (e.g., a new management interface), or different options for an existing function. Complicating matters, applications may expose incompatibilities long after a new driver starts, for example, when an application attempts to use capabilities that it queried from the old driver. To avoid update-induced failures, the shadow must detect whether the update could cause callers to function incorrectly.
Drivers express their capabilities in two ways. When a driver passes a function table to the kernel, the set of functions in the table describe the abilities of the driver. Drivers also express their capabilities through feature fields. For example, network drivers pass a bit-mask of their features to the kernel, which includes the ability to offload TCP checksumming and do scatter/gather I/O. The shadow considers an update compatible only if a new driver provides at least the same capabilities as the old driver.
The shadow checks compatibility when transferring references to the new driver. For example, when a new driver registers and provides a table of function pointers, the shadow checks whether it implements at least the functions that the old driver provided. If so, the shadow updates the wrapper functions to reference the new driver. The shadow also checks whether the new driver provides at least same interfaces to the kernel as the old driver. For a driver with features that can be queried by applications, the shadow explicitly queries the new driver’s features during an update and compares them against the old driver’s features.
Live Update can either roll back an incompatible update, or continue with the update and fail any request that would reveal the incompatibility. These options allow an operator to prioritize an important update (for example, one that prevents unauthorized use of the system) over compatibility. Lower-priority incompatible updates can still be applied with a whole-system reboot.
For some driver updates, these rules are overly conservative. For example, if a driver provides a function or capability that is never used, an update need not provide that function. However, it is impossible for the shadow to know if an application will ever try to call the function in the future, and hence we use conservative checks.
4.7 Transferring Driver State
While previous on-line update systems require applications to transfer their own state between versions, Live Update transfers driver state automatically, without the involvement of driver writers. As previously discussed, a shadow driver captures the state of a driver by monitoring its communication with the kernel. Once the new driver has initialized, the shadow driver transfers the old driver’s state into the new driver using the same calls into the driver that it previously monitored. The shadow re-opens connections to the driver, replays its log of configuration requests, and resubmits requests that were in progress when the driver was updated. Once the shadow completes these calls, the new driver can process new requests as the old driver would have prior to updating.
4.8 Enabling the New Driver
After the reboot completes, the shadow switches back to passive mode and restores direct communication, enabling the new driver to begin processing requests. At this time the shadow submits any requests that it queued during the update. An operator may leave the old version in memory if she desires the opportunity to later roll back the update. Or, she may discard the old driver once the update completes. The system state after an update is shown in Figure 3.
4.9 Implementation Summary
Live Update updates device drivers by replacing their code and rebooting the driver. Before an update, it loads
driver code into memory to avoid circular dependencies. During an update, shadow drivers hide the driver’s unavailability from applications and the OS by handling requests on the driver’s behalf.
Live Update calls existing driver interfaces to initialize the new driver and transfer the state of the current driver. As the new driver initializes, the shadow driver connects it to the resources of the old driver. The shadow reassigns kernel structures referencing the old driver to the new driver. Once the new driver has initialized, the shadow driver transfers in the state of the old driver by replaying its log of configuration requests and by reopening connections to the driver. Finally, the shadow dynamically detects whether the new and old drivers are compatible by comparing the capabilities of the new and old drivers. If the new driver is not compatible, either the update or the action that would reveal the incompatibility can be canceled. Essentially, Live Update takes a systems-oriented approach to updating device drivers and provides a centralized service to update unmodified drivers.
5 Evaluation
We implemented Live Update in the Linux 2.4.18 operating system kernel. Based on a set of experiments using existing, unmodified device drivers and applications, our results show that Live Update (1) can apply most released driver updates, (2) can detect when an update is incompatible with the running code and prevent application failures by rolling back the update, and (3) imposes only a minimal performance overhead.
The experiments were run on a 3 GHz Pentium 4 PC with 1 GB of RAM and a single 80 GB, 7200 RPM IDE disk drive. We built and tested three shadow drivers for three device-driver classes: sound card, network interface controller, and IDE storage device. To ensure that Live Update worked consistently across device driver implementations, we tested it on seven different Linux drivers, shown in Table 2. Although we present detailed results for only one driver in each class (emu10k1, e1000, and ide-disk), behavior across all drivers was similar.
Of these three classes of drivers, only IDE storage drivers require a full system reboot in Linux to be updated. However, updating members of the other two classes, sound and network, disrupts applications. Live Update improves the availability of applications using these drivers, because they need not be restarted when a driver is updated.
In the rest of this section, we answer two questions about our Live Update implementation:
1. Effectiveness. Can Live Update transparent update existing drivers, and can it detect and roll back incompatible updates?
2. Performance. What is the performance overhead of our mechanism during normal operation (i.e., in the absence of updates), and are updates significantly faster than rebooting the whole system?
5.1 Effectiveness
To be effective, the Live Update system must hide updates from the applications and the OS, apply to most driver updates, and be able to detect and handle incompatible updates.
Because Live Update depends on shadow drivers to conceal updates, it shares their concealment abilities. Previous work on shadow drivers demonstrated that shadow drivers could conceal driver reboots from all tested applications in a variety of scenarios. We therefore only examine the latter two requirements: whether Live Update can apply existing driver updates and whether it can detect and roll back incompatible updates.
Applicability to Existing Drivers
We tested whether Live Update can update existing drivers by creating a set of different versions of the drivers. We compiled past versions of each driver, which we obtained either from the Linux kernel source code or
from vendors’ web sites. For drivers that consist of multiple modules, we created separate updates for each module and updated the modules independently. Because the driver interface in the Linux kernel changes frequently, we selected only those drivers that compile and run correctly on the 2.4.18 Linux kernel. Table 3 shows the modules comprising each of our tested drivers and the number of updates for each module.
We applied each driver update from oldest to newest while an application used the driver. For the sound driver, we played an mp3 file. For the network drivers, we performed a network file copy, and for the IDE storage driver we compiled a large program. For each update, we recorded whether the driver was successfully updated and whether the application and OS continued to run correctly. If the update process, the application or OS failed, we consider the update a failure.
The results, shown in Table 3, demonstrate that Live Update successfully applied 90 out of 91 updates. In just one case, when updating the e1000 driver from version 4.1.7 to 4.2.17, the shadow was unable to locate the driver’s I/O memory region when the new driver initialized. This is because the new driver used a different kernel API to request the region, which prevented the shadow from finding the region in the object tracker. The new driver failed to initialize, causing Live Update to roll back the update. The file-copy application, however, continued to run correctly using the old driver.
This single failure of Live Update demonstrates the complexity of transferring kernel resources between driver versions. Shadow drivers use a unique identifier to locate the resource of an old driver that corresponds to a new driver’s request. For example, interrupt handlers are identified by the interrupt line number. When implementing shadow drivers, we chose unique identifiers for some kernel resources that depend on the APIs for requesting the resource. When a driver changes APIs, the shadow cannot locate the old driver’s resources during an update. Ideally, the identifier should be independent of the API used to request the resource. In practice, this is difficult to achieve within the existing Linux kernel API, where there are many resources that can be accessed through several different APIs.
**Compatibility Detection**
While we found no compatibility problems when applying existing driver updates, compatibility detection is nonetheless critical for ensuring system stability. To test whether the Live Update can detect an incompatible update, we created a new version of each of our three drivers that lacks a capability of the original driver. We created *emu10k1-test*, a version of the *emu10k1* driver that supports fewer audio formats. The shadow detects the sound driver’s supported formats by querying the driver’s capabilities after it initializes. From the *e1000* driver we created *e1000-test*, a version that removes the ability to do TCP checksumming in hardware. The driver passes a bit-mask of features to the kernel when it registers, so this change should be detected during the update. Finally, we created *ide-disk-test*, a version of *ide-disk* that removes the ioctl function. This change should be detected during the update, when the driver registers and provides the kernel with a table of function pointers.
For each test driver, we first evaluate whether compatibility detection is necessary by updating to the test driver with the compatibility checks disabled. Similarly to the previous tests, we ran an application that used the driver at the time of update. Next, we applied the same update with compatibility checking enabled. For each test, we recorded whether the system applies the update and whether the application continued to run correctly.
With compatibility checking disabled, all three drivers updated successfully. The sound application failed, though, because it used a capability of the old driver that the new driver did not support. The disk and network applications continued to execute correctly. The kernel checks the driver’s capabilities on every call to disk and network drivers, so it gracefully handles the change in drivers. In contrast, with compatibility checking enabled, Live Update detected all three driver updates as incompatible and rolled back the updates. The applications in these tests continued to run correctly.
These tests demonstrate that compatibility checking is important for drivers whose capabilities are exposed to applications. The sound application checks the driver’s capabilities once, when starting, and then assumes the capabilities do not change. In contrast, only the kernel is aware of the network and disk drivers’ capabilities. Unlike the sound application, the kernel checks the driver capabilities before every invocation of the driver, and hence the compatibility check during update is not important.
### 5.2 Performance
Because updates are infrequently applied, an on-line update system must not degrade performance during the intervals between updates. Live Update introduces overhead from its taps, which interpose on every function call between the kernel and drivers, and from the shadow driver, which must track and log driver information. In addition, updates must be applied quickly to achieve high availability.
To evaluate performance cost of Live Update, we produced two OS configurations based on the Linux 2.4.18 kernel:
1. **Linux-Native** is the unmodified Linux kernel.
Table 4: The applications and workloads used for testing Live Update performance.
<table>
<thead>
<tr>
<th>Device Driver</th>
<th>Application Activity</th>
</tr>
</thead>
</table>
| Sound (emu10k1 driver) | • mp3 player (zinf) playing 128kb/s audio
| | • audio recorder (audacity) recording from microphone |
| Network (e1000 driver) | • network send (netperf) over TCP/IP
| | • network receive (netperf) over TCP/IP |
| Storage | • compiler (make/gcc) compiling 788 C files
| | • database (mySQL) processing the Wisconsin Benchmark
Figure 4: Comparative application performance on Linux-LU relative to Linux-Native. The X-axis crosses at 80%.
2. Linux-LU is a version of Linux that includes shadow drivers and Live Update.
We selected a variety of common applications that use our three device driver classes and measured their performance. The application names and behaviors are shown in Table 4.
Different applications have different performance metrics of interest. For the sound driver, we measured the available CPU while the programs ran. For the network driver, throughput is a more useful metric; therefore, we ran the throughput-oriented network send and network receive benchmarks. For the IDE storage driver, we measured elapsed time to run the applications in Table 4. We repeated all measurements several times and they showed a variation of less than one percent.
Figure 4 shows the performance of Linux-LU relative to Linux-Native. The figure makes clear that Live Update imposes only a small performance penalty compared to running on Linux-Native. Across all six applications, performance on Linux-LU averaged 99% of the performance on Linux-Native, demonstrating that Live Update imposes little overhead.
The overhead of Live Update can be explained in terms of frequency of communication between the driver and the kernel. On each driver-kernel call, the shadow driver may have to log a request or track an object. For example, the kernel calls the driver approximately 1000 times per second when running audio recorder, each of which causes the shadow to update its log. For the most disk-intensive of the IDE storage applications, the database benchmark, the kernel and driver interact only 290 times per second. On the other hand, the network send benchmark transmits 45,000 packets per second, causing 45,000 packets to be tracked. While throughput decreases only slightly, the additional work increases the CPU overhead per packet by 34%, from on $3\mu s$ on Linux-Native to $4\mu s$ on Linux-LU.
Another important aspect of performance is the duration of time when the driver is not available during an update. For each of our three drivers, we measured the delay from when the shadow starts impersonating the device driver until it enables the new driver. The delay for the $e1000$ and ide-disk drivers was approximately 5 seconds, almost all of which is due to the time the driver spends probing hardware. The $emu10k1$ updates much faster and is unavailable for only one-tenth of a second. In contrast, rebooting the entire system can take minutes when including the time to restart applications.
In this section we showed that Live Update could improve availability by updating device drivers without rebooting the OS. For drivers that the OS can replace online, such as sound and network drivers, Live Update was able to update the driver without impacting running applications. We also showed that Live Update was able to automatically roll back updates that failed due to compatibility problems. Furthermore, the overall performance impact of Live Update during normal operation is negligible, suggesting that it could be used across a wide range of applications and environments where high availability is important.
6 Conclusions
While operating systems themselves are becoming more reliable, their availability will ultimately be limited by scheduled maintenance required to update system software. In this paper we presented a system for updating device drivers on-line that allows critical system drivers, such as storage and networking drivers, to be replaced without impacting the operating system and applications, or more importantly, availability.
Live Update leverages shadow drivers [28] to update driver code in-place with no changes to the driver itself. The system loads the new driver code, reboots the driver, and transfers kernel references from the old driver to the new driver. To ensure that applying an update will not re-
1The $e1000$ driver is particularly slow at recovery. The other network drivers we tested recovered in less than a second.
duce reliability due to changes in the driver, Live Update checks the new driver for compatibility, and can rollback incompatible updates. In testing, we found that Live Update could apply 99% of our existing driver updates and had almost no impact on performance.
References
[24] M. E. Segal and O. Frieder. On-the-fly program...
|
{"Source-Url": "http://pages.cs.wisc.edu/~swift/papers/live-update.pdf", "len_cl100k_base": 8264, "olmocr-version": "0.1.53", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 33942, "total-output-tokens": 10417, "length": "2e13", "weborganizer": {"__label__adult": 0.0004379749298095703, "__label__art_design": 0.0003666877746582031, "__label__crime_law": 0.0002543926239013672, "__label__education_jobs": 0.0007505416870117188, "__label__entertainment": 0.00012052059173583984, "__label__fashion_beauty": 0.0001800060272216797, "__label__finance_business": 0.00034689903259277344, "__label__food_dining": 0.0003960132598876953, "__label__games": 0.0011615753173828125, "__label__hardware": 0.00750732421875, "__label__health": 0.0006136894226074219, "__label__history": 0.0003170967102050781, "__label__home_hobbies": 0.00011289119720458984, "__label__industrial": 0.00045990943908691406, "__label__literature": 0.0003440380096435547, "__label__politics": 0.0001819133758544922, "__label__religion": 0.0005087852478027344, "__label__science_tech": 0.10943603515625, "__label__social_life": 6.341934204101562e-05, "__label__software": 0.0277862548828125, "__label__software_dev": 0.84765625, "__label__sports_fitness": 0.00025177001953125, "__label__transportation": 0.0006976127624511719, "__label__travel": 0.0002065896987915039}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47739, 0.02553]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47739, 0.1086]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47739, 0.88442]], "google_gemma-3-12b-it_contains_pii": [[0, 4422, false], [4422, 9851, null], [9851, 15062, null], [15062, 19230, null], [19230, 23801, null], [23801, 28283, null], [28283, 32008, null], [32008, 37518, null], [37518, 42117, null], [42117, 46667, null], [46667, 47739, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4422, true], [4422, 9851, null], [9851, 15062, null], [15062, 19230, null], [19230, 23801, null], [23801, 28283, null], [28283, 32008, null], [32008, 37518, null], [37518, 42117, null], [42117, 46667, null], [46667, 47739, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47739, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47739, null]], "pdf_page_numbers": [[0, 4422, 1], [4422, 9851, 2], [9851, 15062, 3], [15062, 19230, 4], [19230, 23801, 5], [23801, 28283, 6], [28283, 32008, 7], [32008, 37518, 8], [37518, 42117, 9], [42117, 46667, 10], [46667, 47739, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47739, 0.07471]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
1da1a894cb87915b6c2616b52450d6f100d48af0
|
Fairness Testing: Testing Software for Discrimination
Sainyam Galhotra Yuriy Brun Alexandra Meliou
University of Massachusetts, Amherst
Amherst, Massachusetts 01003-9264, USA
{sainyam, brun, ameli}@cs.umass.edu
ABSTRACT
This paper defines software fairness and discrimination and develops a testing-based method for measuring if and how much software discriminates, focusing on causality in discriminatory behavior. Evidence of software discrimination has been found in modern software systems that recommend criminal sentences, grant access to financial products, and determine who is allowed to participate in promotions. Our approach, Themis, generates efficient test suites to measure discrimination. Given a schema describing valid system inputs, Themis generates discrimination tests automatically and does not require an oracle. We evaluate Themis on 20 software systems, 12 of which come from prior work with explicit focus on avoiding discrimination. We find that (1) Themis is effective at discovering software discrimination, (2) state-of-the-art techniques for removing discrimination from algorithms fail in many situations, at times discriminating against as much as 98% of an input subdomain, (3) Themis optimizations are effective at producing efficient test suites for measuring discrimination, and (4) Themis is more efficient on systems that exhibit more discrimination. We thus demonstrate that fairness testing is a critical aspect of the software development cycle in domains with possible discrimination and provide initial tools for measuring software discrimination.
CCS CONCEPTS
• Software and its engineering → Software testing and debugging
KEYWORDS
Discrimination testing, fairness testing, software bias, testing
1 INTRODUCTION
Software has become ubiquitous in our society and the importance of its quality has increased. Today, automation, advances in machine learning, and the availability of vast amounts of data are leading to a shift in how software is used, enabling the software to make more autonomous decisions. Already, software makes decisions in what products we are led to buy [53], who gets a loan [62], self-driving car actions that may lead to property damage or human injury [32], medical diagnosis and treatment [74], and every stage of the criminal justice system including arraignment and sentencing that determine who goes to jail and who is set free [5, 28]. The importance of these decisions makes fairness and nondiscrimination in software as important as software quality.
Unfortunately, software fairness is undervalued and little attention is paid to it during the development lifecycle. Countless examples of unfair software have emerged. In 2016, Amazon, Inc. used software to determine the parts of the United States to which it would offer free same-day delivery. The software made decisions that prevented minority neighborhoods from participating in the program, often when every surrounding neighborhood was allowed to participate [36, 52]. Similarly, software is being used to compute risk-assessment scores for suspected criminals. These scores — an estimated probability that the person arrested for a crime is likely to commit another crime — are used to inform decisions about who can be set free at every stage of the criminal justice system process, from assigning bond amounts, to deciding guilt, to sentencing. Today, the U.S. Justice Department’s National Institute of Corrections encourages the use of such assessment scores. In Arizona, Colorado, Delaware, Kentucky, Louisiana, Oklahoma, Virginia, Washington, and Wisconsin, these scores are given to judges during criminal sentencing. The Wisconsin Supreme Court recently ruled unanimously that the COMPAS computer program, which uses attributes including gender, can assist in sentencing defendants [28]. Despite the importance of these scores, the software is known to make mistakes. In forecasting who would reoffend, the software is “particularly likely to falsely flag black defendants as future criminals, wrongly labeling them this way at almost twice the rate as white defendants; white defendants were mislabeled as low risk more often than black defendants” [5]. Prior criminal history does not explain this difference: Controlling for criminal history, recidivism, age, and gender shows that the software predicts black defendants to be 77% more likely to be pegged as at higher risk of committing a future violent crime than white defendants [5].
Going forward, the importance of ensuring fairness in software will only increase. For example, “it’s likely, and some say inevitable, that future AI-powered weapons will eventually be able to operate with complete autonomy, leading to a watershed moment in the
history of warfare: For the first time, a collection of microchips and software will decide whether a human being lives or dies” [34]. In fact, in 2016, the U.S. Executive Office of the President identified bias in software as a major concern for civil rights [27]. And one of the ten principles and goals Satya Nadella, the CEO of Microsoft Co., has laid out for artificial intelligence is “AI must guard against bias, ensuring proper, and representative research so that the wrong heuristics cannot be used to discriminate” [61].
This paper defines causal software discrimination and proposes Themis, a software testing method for evaluating the fairness of software. Our definition captures causal relationships between inputs and outputs, and can, for example, detect when sentencing software behaves such that “changing only the applicant’s race affects the software’s sentence recommendations for 13% of possible applicants.” Prior work on detecting discrimination has focused on measuring correlation or mutual information between inputs and outputs [79], discrepancies in the fractions of inputs that produce a given output [18, 19, 39–42, 87–89, 91], or discrepancies in output probability distributions [51]. These approaches do not capture causality and can miss discrimination that our causal approach detects, e.g., when the software discriminates negatively with respect to a group in one setting, but positively in another. Restricting the input space to real-world inputs [1] may similarly hide software discrimination that causal testing can reveal. Unlike prior work that requires manually written tests [79], Themis automatically generates test suites that measure discrimination. To the best of our knowledge, this work is the first to automatically generate test suites to measure causal discrimination in software.
Themis would be useful for companies and government agencies relying on software decisions. For example, Amazon.com, Inc. received strong negative publicity after its same-day delivery algorithm made racially biased decisions. Politicians and citizens in Massachusetts, New York, and Illinois demanded that the company offer same-day delivery service to minority neighborhoods in Boston, New York City, and Chicago, and the company was forced to reverse course within mere days [72, 73]. Surely, the company would have preferred to test its software for racial bias and to develop a strategy (e.g., fixing the software, manually reviewing and modifying racist decisions, or not using the software) prior to deploying it. Themis could have analyzed the software and detected the discrimination prior to deployment. Similarly, a government may need to set nondiscrimination requirements on software, and be able to evaluate if software satisfies those requirements before mandating it to be used in the justice system. In 2014, the U.S. Attorney General Eric Holder warned that steps need to be taken to prevent the risk-assessment scores injecting bias into the courts: “Although these measures were crafted with the best of intentions, I am concerned that they inadvertently undermine our efforts to ensure individualized and equal justice [and] they may exacerbate unwarranted and unjust disparities that are already far too common in our criminal justice system and in our society.” [5]. As with software quality, testing is likely to be the best way to evaluate software fairness properties.
Unlike prior work, this paper defines discrimination as a causal relationship between an input and an output. As defined here, discrimination is not necessarily bad. For example, a software system designed to identify if a picture is of a cat should discriminate between cats and dogs. It is not our goal to eliminate all discrimination in software. Instead, it is our goal to empower the developers and stakeholders to identify and reason about discrimination in software. As described above, there are plenty of real-world examples in which companies would prefer to have discovered discrimination earlier, prior to release. Specifically, our technique’s job is to identify if software discriminates with respect to a specific set of characteristics. If the stakeholder expects cat vs. dog discrimination, she would exclude it from the list of input characteristics to test. However, learning that the software frequently misclassifies black cats can help the stakeholder improve the software. Knowing if there is discrimination can lead to better-informed decision making.
There are two main challenges to measuring discrimination via testing. First, generating a practical set of test inputs sufficient for measuring discrimination, and second, processing those test inputs’ executions to compute discrimination. This paper tackles both challenges, but the main contribution is computing discrimination from a set of executions. We are aware of no prior testing technique, neither automated nor manual, that produces a measure of a software system’s causal discrimination. The paper also contributes within the space of efficient test input generation for the specific purpose of discrimination testing (see Section 4), but some prior work, specifically in combinatorial testing, e.g., [6, 44, 47, 80], may further help the efficiency of test generation, though these techniques have not been previously applied to discrimination testing. We leave a detailed examination of how combinatorial testing and other automated test generation can further improve Themis to future work.
This paper’s main contributions are:
1. Formal definitions of software fairness and discrimination, including a causality-based improvement on the state-of-the-art definition of algorithmic fairness.
3. A formal analysis of the theoretical foundation of Themis, including proofs of monotonicity of discrimination that lead to provably sound two-to-three orders of magnitude improvements in test suite size, a proof of the relationship between fairness definitions, and a proof that Themis is more efficient on systems that exhibit more discrimination.
4. An evaluation of the fairness of 20 real-world software instances (based on 8 software systems), 12 of which were designed with fairness in mind, demonstrating that (i) even when fairness is a design goal, developers can easily introduce discrimination in software, and (ii) Themis is an effective fairness testing tool.
Themis requires a schema for generating inputs, but does not require an oracle. Our causal fairness definition is designed specifically to be testable, unlike definitions that require probabilistic estimation or knowledge of the future [38]. Software testing offers a unique opportunity to conduct causal experiments to determine statistical causality [67]: One can run the software on an input (e.g., a defendant’s criminal record), modify a specific input characteristic (e.g., the defendant’s race), and observe if that modification causes a change in the output. We define software to be causally
fair with respect to input characteristic \( \chi \) if for all inputs, varying the value of \( \chi \) does not alter the output. For example, a sentence-recommendation system is fair with respect to race if there are no two individuals who differ only in race but for whom the system’s sentence recommendations differs. In addition to capturing causality, this definition requires no oracle — the equivalence of the output for the two inputs is itself the oracle — which helps fully automate test generation.
The rest of this paper is structured as follows. Section 2 provides an intuition to fairness measures and Section 3 formally defines software fairness. Section 4 describes Themis, our approach to fairness testing. Section 5 evaluates Themis. Finally, Section 6 places our work in the context of related research and Section 7 summarizes our contributions.
## 2 SOFTWARE FAIRNESS MEASURES
Suppose a bank employs loan software to decide if loan applicants should be given loans. Loan inputs are each applicant’s name, age, race, income, savings, employment status, and requested loan amount, and the output is a binary “give loan” or “do not give loan”. For simplicity, suppose age and race are binary, with age either <40 or >40, and race either green or purple.
Some prior work on measuring and removing discrimination from algorithms [18, 19, 39–42, 88, 89, 91] has focused on what we call group discrimination, which says that to be fair with respect to an input characteristic, the distribution of outputs for each group should be similar. For example, the loan software is fair with respect to age if it gives loans to the same fractions of applicants <40 and >40. To be fair with respect to multiple characteristics, for example, age and race, all groups with respect to those characteristics — purple <40, purple >40, green <40, and green >40 — should have the same outcome fractions. The Calders-Verwer (CV) score [19] measures the strength of group discrimination as the difference between the largest and the smallest outcome fractions; if 30% of people <40 get the loan, and 40% of people >40 get the loan, then loan is 40% – 30% = 10% group discriminating.
While group discrimination is easy to reason about and measure, it has two inherent limitations. First, group discrimination may fail to observe some discrimination. For example, suppose that loan produces different outputs for two loan applications that differ in race, but are otherwise identical. While loan clearly discriminates with respect to race, the group discrimination score will be 0 if loan discriminates in the opposite way for another pair of applications. Second, software may circumvent group discrimination detection. For example, suppose loan recommends loans for a random 30% of the purple applicants, and the 30% of the green applicants who have the most savings. Then the group discrimination score with respect to race will deem loan perfectly fair, despite a clear discrepancy in how the applications are based on race.
To address these issues, we define a new measure of discrimination. Software testing enables a unique opportunity to conduct causal experiments to determine statistical causation [67] between inputs and outputs. For example, it is possible to execute loan on two individuals identical in every way except race, and verify if changing the race causes a change in the output. Causal discrimination says that to be fair with respect to a set of characteristics, the software must produce the same output for every two individuals who differ only in those characteristics. For example, the loan software is fair with respect to age and race if for all pairs of individuals with identical name, income, savings, employment status, and requested loan amount but different race or age characteristics, loan either gives all of them or none of them the loan. The fraction of inputs for which software causally discriminates is a measure of causal discrimination.
Thus far, we have discussed software operating on the full input domain, e.g., every possible loan application. However, applying software to partial input domains may mask or effect discrimination. For example, while software may discriminate on some loan applications, a bank may care about whether that software discriminates only with respect to applications representative of their customers, as opposed to all possible human beings. In this case, a partial input domain may mask discrimination. If a partial input domain exhibits correlation between input characteristics, it can effect discrimination. For example, suppose older individuals have, on average, higher incomes and larger savings. If loan only considers income and savings in making its decision, even though it does not consider age, for this population, loan gives loans to a higher fraction of older individuals than younger ones. We call the measurement of group or causal discrimination on a partial input domain apparent discrimination. Apparent discrimination depends on the operational profile of the system system’s use [7, 58]. Apparent discrimination is important to measure. For example, Amazon.com, Inc. software that determined where to offer free same-day delivery did not explicitly consider race but made race-correlated decisions because of correlations between race and other input characteristics [36, 52]. Despite the algorithm not looking at race explicitly, Amazon.com, Inc. would have preferred to have tested for this kind of discrimination.
## 3 FORMAL FAIRNESS DEFINITIONS
We make two simplifying assumptions. First, we define software as a black box that maps input characteristics to an output characteristic. While software is, in general, more complex, for the purposes of fairness testing, without loss of generality, this definition is sufficient: All user actions and environmental variables are modeled as input characteristics, and each software effect is modeled as an output characteristic. When software has multiple output characteristics, we define fairness with respect to each output characteristic separately. The definitions can be extended to include multiple output characteristics without significant conceptual reformulation. Second, we assume that the input characteristics and the output characteristic are categorical variables, each having a set of possible values (e.g., race, gender, eye color, age ranges, income ranges). This assumption simplifies our measure of causality. While our definitions do not apply directly to non-categorical input and output characteristics (such as continuous variables, e.g., int and double), they, and our techniques, can be applied to software with non-categorical input and output characteristics by using binning (e.g., age<40 and age>40). The output domain distance function (Definition 3.3) illustrates one way our definitions can be extended to continuous variables. Future work will extend our discrimination measures directly to a broader class of data types.
A characteristic is a categorical variable. An input type is a set of characteristics, an input is a valuation of an input type (assignment of a value to each characteristic), and an output is a single characteristic.
**Definition 3.1 (Characteristic).** Let \( L \) be a set of value labels. A characteristic \( \chi \) over \( L \) is a variable that can take on the values in \( L \).
**Definition 3.2 (Input type and input).** For all \( n \in \mathbb{N} \), let \( L_1, L_2, \ldots, L_n \) be sets of value labels. Then an input type \( X \) over those value labels is a sequence of characteristics \( X = (\chi_1, \chi_2, \ldots, \chi_n) \), where for all \( i \leq n \), \( \chi_i \) is a characteristic over \( L_i \).
An input of type \( X \) is \( k = (l_1 \in L_1, l_2 \in L_2, \ldots, l_n \in L_n) \), a valuation of an input type.
We say the sizes of input \( k \) and of input type \( X \) are \( n \).
Discrimination can be measured in software that makes decisions.
When the output characteristic is binary (e.g., “give loan” vs. “do not give loan”) the significance of the two different output values is clear.
When outputs are not binary, identifying potential discrimination requires understanding the significance of differences in the output. For example, if the software outputs an ordering of hotel listings (that may be influenced by the computer you are using, as was the case when software used by Orbitz led Apple users to higher-priced hotels [53]), domain expertise is needed to compare two outputs and decide the degree to which their difference is significant.
The **output domain distance function** encodes this expertise, mapping pairs of output values to a distance measure.
**Definition 3.3 (Output domain distance function).** Let \( L_o \) be a set of value labels. Then for all \( l_{o1}, l_{o2} \in L_o \), the output distance function is \( \delta: L_o \times L_o \rightarrow [0,1] \) such that \( l_{o1} = l_{o2} \Rightarrow \delta(l_{o1}, l_{o2}) = 0 \).
The output domain distance function generalizes our work beyond binary outputs. For simplicity of exposition, for the remainder of this paper, we assume software outputs binary decisions — a natural domain for fairness testing. While true or false outputs (corresponding to decisions such as “give loan” vs. “do not give loan”) are easier to understand, the output domain distance function enables comparing non-binary outputs in two ways. First, a **threshold output domain distance function** can determine when two outputs are dissimilar enough to warrant potential discrimination. Second, a **relational output domain distance function** can describe how different two inputs are and how much they contribute to potential discrimination. Definitions 3.5, 3.6, 3.8, and 3.7 can be extended to handle non-binary outputs by changing their exact output comparisons to fractional similarity comparisons using an output domain distance function, similar to the way inputs have been handled in prior work [24].
**Definition 3.4 (Decision software).** Let \( n \in \mathbb{N} \) be an input size, let \( L_1, L_2, \ldots, L_n \) be sets of value labels, let \( X = (\chi_1, \chi_2, \ldots, \chi_n) \) be an input type, and let \( K \) be the set of all possible inputs of type \( X \). Decision software is a function \( S: K \rightarrow \{\text{true, false}\} \). That is, when software \( S \) is applied to an input \( k \in L_1, l_2 \in L_2, \ldots, l_n \in L_n \), it produces true or false.
The **group discrimination score** varies from 0 to 1 and measures the difference between fractions of input groups that lead to the same output (e.g., the difference between the fraction of green and purple individuals who are given a loan).
This definition is based on the CV score [19], which is limited to a binary input type or a binary partitioning of the input space. Our definition extends to the more broad categorical input types, reflecting the relative complexity of arbitrary decision software. The group discrimination score with respect to a set of input characteristics is the maximum frequency with which the software outputs true minus the minimum such frequency for the groups that only differ in those input characteristics. Because the CV score is limited to a single binary partitioning, that difference represents all the encoded discrimination information in that setting. In our more general setting with multiple non-binary characteristics, the score focuses on the range — difference between the maximum and minimum — as opposed to the distribution. One could consider measuring, say, the standard deviation of the distribution of frequencies instead, which would better measure deviation from a completely fair algorithm, as opposed to the maximal deviation for two extreme groups.
**Definition 3.5 (Univariate group discrimination score \( \hat{d} \)).** Let \( K \) be the set of all possible inputs of size \( n \in \mathbb{N} \) of type \( X = (\chi_1, \chi_2, \ldots, \chi_n) \) over labels \( L_1, L_2, \ldots, L_n \). Let software \( S: K \rightarrow \{\text{true, false}\} \).
For all \( i \leq n \), fix one characteristic \( \chi_i \). That is, let \( m = |L_i| \) and for all \( m \leq m \), let \( K_{\chi_i} \) be the set of all inputs with \( \chi_i = \chi_i \). \( K_{\chi_i} \) is the set of all inputs with the \( \chi_i \)th characteristic fixed to be \( l_{\chi_i} \)\). Let \( \rho_m \) be the fraction of inputs \( k \in K_{\chi_i} \) such that \( S(k) = \text{true} \).
And let \( P = \{\rho_{l_1}, \rho_{l_2}, \ldots, \rho_{l_m}\} \).
Then the univariate group discrimination score with respect to \( \chi_i \), denoted \( \hat{d}_{\chi_i}(S) \), is \( \max(P) - \min(P) \).
For example, consider loan software that decided to give loan to 23% of green individuals, and to 65% of purple individuals. When computing loan’s group discrimination score with respect to race, \( \hat{d}_{\text{race}} \) (loan) = 0.65 - 0.23 = 0.42.
The multivariate group discrimination score generalizes the univariate version to multiple input characteristics.
**Definition 3.6 (Multivariate group discrimination score \( \hat{d} \)).** For all \( \alpha, \beta, \ldots, \gamma \leq n \), fix the characteristics \( \chi_\alpha, \chi_\beta, \ldots, \chi_\gamma \). That is, let \( m_\alpha = |L_\alpha|, m_\beta = |L_\beta|, \ldots, m_\gamma = |L_\gamma| \), let \( m_\alpha \leq m_\beta \leq m_\beta, \ldots, m_\gamma \leq m_\gamma \), and \( m = m_\alpha \times m_\beta \times \cdots \times m_\gamma \), let \( K_{\chi_\alpha, \chi_\beta, \ldots, \chi_\gamma} \) be the set of all inputs with \( \chi_\alpha = l_{\chi_\alpha}, \chi_\beta = l_{\chi_\beta}, \ldots, \chi_\gamma = l_{\chi_\gamma} \). \( K_{\chi_\alpha, \chi_\beta, \ldots, \chi_\gamma} \) is the set of all inputs with the \( \chi_\alpha \) characteristic fixed to be \( l_{\chi_\alpha} \), \( \chi_\beta \) characteristic fixed to be \( l_{\chi_\beta} \), and so on.) Let \( \rho_{m_\alpha, m_\beta, \ldots, m_\gamma} \) be the fraction of inputs \( k \in K_{\chi_\alpha, \chi_\beta, \ldots, \chi_\gamma} \) such that \( S(k) = \text{true} \). And let \( P \) be an unordered sequence of all \( \rho_{m_\alpha, m_\beta, \ldots, m_\gamma} \).
Then the multivariate group discrimination score with respect to \( \chi_\alpha, \chi_\beta, \ldots, \chi_\gamma \), denoted \( \hat{d}_{\chi_\alpha, \chi_\beta, \ldots, \chi_\gamma}(S) \) is \( \max(P) - \min(P) \).
**Our causal discrimination score** is a stronger measure of discrimination, as it seeks out causality in software, measuring the fraction of inputs for which changing specific input characteristics causes the output to change [67]. The causal discrimination score identifies changing which characteristics directly affects the output. As a result, for example, while the group and apparent discrimination scores penalize software that gives loans to different fractions of green and purple individuals who are given a loan.
individuals of different races, the causal discrimination score penalizes software that gives loans to individuals of one race but not to otherwise identical individuals of another race.
Definition 3.7 (Multivariate causal discrimination score $\bar{d}$). Let $K$ be the set of all possible inputs of size $n \in \mathbb{N}$ of type $X = \langle \chi_1, \chi_2, \ldots, \chi_n \rangle$ over label values $L_1, L_2, \ldots, L_n$. Let software $S: K \rightarrow \{\text{true}, \text{false}\}$. For all $a, \beta, \ldots, y \leq n$, let $\chi_a, \chi_{a'}, \ldots, \chi_y$ be input characteristics.
Then the causal discrimination score with respect to $\chi_a, \chi_{a'}, \ldots, \chi_y$, denoted $\bar{d}_{\chi_a, \chi_{a'}, \ldots, \chi_y}(S)$ is the fraction of inputs $k \in K$ such that there exists an input $k' \in K$ such that $k$ and $k'$ differ only in the input characteristics $\chi_a, \chi_{a'}, \ldots, \chi_y$, and $S(k) \neq S(k')$. That is, the causal discrimination score with respect to $\chi_a, \chi_{a'}, \ldots, \chi_y$ is the fraction of inputs for which changing at least one of those characteristics causes the output to change.
Thus far, we have measured discrimination of the full input domain, considering every possible input with every value of every characteristic. In practice, input domains may be partial. A company may, for example, care about whether software discriminates only with respect to their customers (recall Section 2). Apparent discrimination captures this notion, applying group or causal discrimination score measurement to a subset of the input domain, which can be described by an operational profile [7, 58].
Definition 3.8 (Multivariate apparent discrimination score). Let $K \subseteq K$ be a subset of the input domain to $S$. Then the apparent group discrimination score is the group discrimination score applied to $K$, and the apparent causal discrimination score is the causal discrimination score applied to $K$ (as opposed to applied to the full $K$).
Having defined discrimination, we now define the problem of checking software for discrimination.
Definition 3.9 (Discrimination checking problem). Given an input type $X$, decision software $S$ with input type $X$, and a threshold $0 \leq \theta \leq 1$, compute all $X' \subseteq X$ such that $\bar{d}_{X'}(S) \geq \theta$ or $\bar{d}_{X'}(S) \geq \theta$.
### 4 THE THEMIS SOLUTION
This section describes Themis, our approach to efficient fairness testing. To use Themis, the user provides a software executable, a desired confidence level, an acceptable error bound, and an input schema describing the format of valid inputs. Themis can then be used in three ways:
1. Themis generates a test suite to compute the software group or causal discrimination score for a particular set of characteristics. For example, one can use Themis to check if, and how much, a software system discriminates against race and age.
2. Given a discrimination threshold, Themis generates a test suite to compute all sets of characteristics against which a software group or causally discriminates more than that threshold.
3. Given a manually-written or automatically-generated test suite, or an operational profile describing an input distribution [7, 58], Themis computes the apparent group or causal discrimination score for a particular set of characteristics. For example, one can use Themis to check if a system discriminates against race on a specific population of inputs representative of the way the system will be used. This method does not compute the score’s confidence as it is only as strong as the developers’ confidence that test suite or operational profile is representative of real-world executions.
Measuring group and causal discrimination exactly requires exhaustive testing, which is infeasible for nontrivial software. Solving the discrimination checking problem (Definition 3.9) further requires measuring discrimination over all possible subsets of characteristics to find those that exceed a certain discrimination threshold. Themis addresses these challenges by employing three optimizations: (1) test caching, (2) adaptive, confidence-driven sampling, and (3) sound pruning. All three techniques reduce the number of test cases needed to compute both group and causal discrimination. Section 4.1 describes how Themis employs caching and sampling, and Section 4.2 describes how Themis prunes the test suite search space.
#### 4.1 Caching and Approximation
**GroupDiscrimination** (Algorithm 1) and **CausalDiscrimination** (Algorithm 2) present the Themis computation of multivariate group and causal discrimination scores with respect to a set of characteristics. These algorithms implement Definitions 3.6 and 3.7, respectively, and rely on two optimizations. We first describe these optimizations and then the algorithms.
Adaptive, confidence-driven sampling. Precisely computing the group and causal discrimination scores requires executing a large set of tests. However, a lot of this computation is repetitive: tests relevant to group discrimination are also relevant to causal discrimination, and tests relevant to one set of characteristics can also be relevant to another set. This redundancy in fairness testing allows Themis to exploit caching to reuse test results without re-executing tests. Test caching has low storage overhead and offers significant runtime gains.
Adaptive, confidence-driven sampling. Since exhaustive testing is infeasible, Themis computes approximate group and causal discrimination scores through sampling. Sampling in Themis is adaptive, using the ongoing score computation to determine if a specified margin of error $\varepsilon$ with a desired confidence level $\text{conf}$ has been reached. Themis generates inputs uniformly at random using an input schema, and maintains the proportion of samples ($p$) for which the software outputs true (in $\text{GroupDiscrimination}$) or for which the software changes its output (in $\text{CausalDiscrimination}$).
The margin of error for $p$ is then computed as:
$$\text{error} = z^* \sqrt{\frac{p(1-p)}{r}}$$
where $r$ is the number of samples so far and $z^*$ is the normal distribution score for the desired confidence level. Themis returns if $\text{error} < \varepsilon$, or generates another test otherwise.
GroupDiscrimination (Algorithm 1) measures the group discrimination score with respect to a subset of its input characteristics $X'$. As per Definition 3.6, GroupDiscrimination fixes $X'$ to particular values (line 2) to compute what portion of all tests with $X'$ values fixed produce a true output. The while loop (line 5) generates random input assignments for the remaining input characteristics (line 7), stores them in the test suite, and measures the count of positive outputs. The algorithm executes the test, if that execution is not already cached (line 9); otherwise, the algorithm retrieves the software output from the cache (line 12). After passing the minimum sampling threshold (line 16), it checks if $\varepsilon$ error margin is achieved with the desired confidence (line 18). If it is, GroupDiscrimination terminates the computation for the current group and updates the max and min values (lines 20–21).
CausalDiscrimination (Algorithm 2) similarly applies test caching and adaptive sampling. It takes a random test $k_0$ (line 4) and tests if changing any of its $X'$ characteristics changes the output. If $k_0$ result is not cached (line 6), the algorithm executes it and caches the result. It then iterates through tests $k$ that differ from $k_0$ in one or more characteristics in $X'$ (line 11). All generated inputs are stored in the test suite. The algorithm typically only needs to examine a small number of tests before discovering causal discrimination for the particular input (line 18). In the end, CausalDiscrimination returns the proportion of tests for which the algorithm found causal discrimination (line 25).
4.2 Sound Pruning
Measuring software discrimination (Definition 3.9) involves executing GroupDiscrimination and CausalDiscrimination over each subset of the input characteristics. The number of these executions grows exponentially with the number of characteristics. Themis relies on a powerful pruning optimization to dramatically reduce the number of evaluated characteristics subsets. Pruning is based on a fundamental monotonicity property of group and causal discrimination: if a software $\mathcal{S}$ discriminates over threshold $\theta$ with respect to a set of characteristics $X'$, then $\mathcal{S}$ also discriminates over threshold $\theta$ with respect to all superset of $X'$. Once Themis discovers that $\mathcal{S}$ discriminates against $X'$, it can prune testing all supersets of $X'$.
Next, we formally prove group (Theorem 4.1) and causal (Theorem 4.2) discrimination monotonicity. These results guarantee that Themis pruning strategy is sound. DiscriminationSearch (Algorithm 3) uses pruning in solving the discrimination checking problem. As Section 5.4 will evaluate empirically, pruning leads to, on average, a two-to-three order of magnitude reduction in test suite size.
**Theorem 4.1 (Group discrimination monotonicity).** Let $X$ be an input type and let $\mathcal{S}$ be a decision software with input type $X$. Then for all sets of characteristics $X', X'' \subseteq X$, $X' \supseteq X'' \implies \tilde{d}_{X'}(\mathcal{S}) \leq \tilde{d}_{X''}(\mathcal{S})$.
**Proof.** Let $\tilde{d}_{X'}(\mathcal{S}) = 0'$. Recall (Definition 3.6) that to compute $\tilde{d}_{X'}(\mathcal{S})$, we partition the space of all inputs into equivalence classes
such that all elements in each equivalence class have identical value labels assigned to each characteristic in $X'$. Then, compute the frequencies with which inputs in each equivalence class lead $S$ to a true output, and finally compute the difference between the minimum and maximum of these frequencies. Let $\bar{p}'$ and $\bar{p}''$ be those maximum and minimum frequencies, and $\bar{K}'$ and $\bar{K}''$ be the corresponding equivalence classes of inputs.
Now consider the computation of $\bar{d}(\bar{S}) = d_X(\bar{S})$. Note that the equivalence classes of inputs for this computation will be strict subsets of the equivalence classes in the $d_X$ computation. In particular, the equivalence subset $\bar{K}'$ will be split into several equivalence classes, which we call $\bar{K}'_1, \bar{K}'_2, \ldots$. There are two possibilities: (1) either the frequency with which the inputs in each of these subclasses lead $S$ to a true output equals the frequency of $\bar{K}'$, or (2) some subclasses have lower frequencies and some have higher than $\bar{K}'$ (since when combined, they must equal that of $\bar{K}'$). Either way, the maximum frequency of the $\bar{K}'_1, \bar{K}'_2, \ldots$ subclasses is $\geq \bar{K}'$. And therefore, the maximum overall frequency $\bar{p}''$ for all the equivalence classes in the computation of $d_X'\prime$ is $\geq \bar{p}'$. By the same argument, the maximum overall frequency $\bar{p}'''$ for all the equivalence classes in the computation of $d_X''\prime$ is $\geq \bar{p}'$. Therefore, $\bar{d}(\bar{S}) = (\bar{p}'' - \bar{p}''') \geq (\bar{p}' - \bar{p}) \leq \theta'$, and therefore, $\bar{d}(\bar{S}) = d_X(\bar{S})$.
**Theorem 4.3 (Causal Discrimination Monotonicity).** Let $X$ be an input type and let $S$ be a decision software with input type $X$. Then for all sets of characteristics $X', X'' \subseteq X$, $X' \supseteq X'' \supseteq X' \Rightarrow d_X(S) \geq d_X(\bar{S})$.
**Proof.** Recall (Definition 3.7) that the causal discrimination score with respect to $X'$ is the fraction of inputs for which changing the value of at least one characteristic in $X'$ changes the output. Consider $K'$, the entire set of such inputs for $X'$, and similarly $K''$, the entire set of such inputs for $X''$. Since $X'' \supseteq X'$, every input in $K'$ must also be in $K''$ because if changing at least one characteristic in $X'$ changes the output and those characteristics are also in $X''$. Therefore, the fraction of such inputs must be no smaller for $X''$ than for $X'$, and therefore, $X'' \supseteq X' \Rightarrow \bar{d}_X(S) \geq d_X(\bar{S})$.
A further opportunity for pruning comes from the relationship between group and causal discrimination. As Theorem 4.3 shows, if software group discriminates against a set of characteristics, it must causally discriminate against that set as well.
**Theorem 4.3.** Let $X$ be an input type and let $S$ be a decision software with input type $X$. Then for all sets of characteristics $X' \subseteq X$, $\bar{d}_X(S) \leq \bar{d}_X(\bar{S})$.
**Proof.** Let $\bar{d}_X(S) = \theta$. Recall (Definition 3.6) that to compute $\bar{d}_X(S)$, we partition the space of all inputs into equivalence classes such that all elements in each equivalence class have identical value labels assigned to each characteristic in $X'$. It is evident that same equivalence class inputs have same values for characteristics in $X'$ and the ones in different equivalence classes differ in at least one of the characteristics in $X'$.
Now, $\bar{d}_X(S) = \theta$ means that for $\theta$ fraction of inputs, the output is true, and after changing just some values of $X'$ (producing an input in another equivalence class), the output is false. This is because if there were $\theta' < \theta$ fraction of inputs with a different output when changing the equivalence classes, then $\bar{d}_X(S)$ would have been $\theta'$. Hence $\bar{d}_X(S) > \theta$.
5 EVALUATION
In evaluating Themis, we focused on two research questions:
**RQ1:** Does research on discrimination-aware algorithm design (e.g., [18, 40, 88, 91]) produce fair algorithms?
**RQ2:** How effective do the optimizations from Section 4 make Themis at identifying discrimination in software?
To answer these research questions, we carried out three experiments on twenty instances of eight software systems that make financial decisions.\(^1\) Seven of the eight systems (seventeen out of the twenty instances) are written by original system developers; we reimplemented one of the systems (three instances) because original source code was not available. Eight of these software instances use standard machine learning algorithms to infer models from datasets of financial and demographic data. These systems make no attempt to avoid discrimination. The other twelve instances are taken from related work on devising discrimination-aware algorithms [18, 40, 88, 91]. These software instances use the same datasets and attempt to infer discrimination-free solutions. Four of them focus on not discriminating against race, and eight against gender. Section 5.1 describes our subject systems and the two datasets they use.
\(^1\)We use the term system instance to mean instantiation of a software system with a configuration, using a specific dataset. Two instances of the same system using different configurations and different data are likely to differ significantly in behavior and in their discrimination profile.
5.1 Subject Software Systems
Our twenty subject instances use two financial datasets. The Adult dataset (also known as the Census Income dataset) contains financial and demographic data for 45K individuals; each individual is described by 14 attributes, such as occupation, number of work hours, capital gains and losses, education level, gender, race, marital status, age, country of birth, income, etc. This dataset is well vetted: it has been used by others to devise discrimination-free algorithms [18, 88, 89], as well as for non-discrimination purposes [3, 43, 86]. The Statlog German Credit dataset contains credit data for 1,000 individuals, classifying each individual as having "good" or "bad" credit, and including 20 other pieces of data for each individual, such as gender, housing arrangement, credit history, years employed, credit amount, etc. This dataset is also well vetted: it has been used by others to devise discrimination-free algorithms [18, 89], as well as for non-discrimination purposes [25, 31].
We use a three-parameter naming scheme to refer to our software instances. An example of an instance name is $A_{\text{race}}$. The "A" refers to the system used to generate the instance (described next). The "census" refers to the dataset used for the system instance. This value can be "census" for the Adult Census Income dataset or "credit" for the Statlog German Credit dataset. Finally, the "race" refers to a characteristic the software instance attempts to not discriminate against. In our evaluation, this value can be "race" or "gender" for the census dataset and can only be "gender" for the credit dataset. Some of the systems make no attempt to avoid discrimination and their names leave this part of the label blank.
Prior research has attempted to build discrimination-free systems using these two datasets [18, 40, 88, 91]. We contacted the authors and obtained the source code for three of these four systems, $A$ [88], $C$ [18], and $D$ [91], and reimplemented the other, $B$ [40], ourselves. We verified that our reimplementation produced results consistent with the evaluation of the original system [40]. We additionally used standard machine learning libraries as four more discrimination-unaware software systems $E$, $F$, $G$, and $H$, on these datasets. We used scikit-learn [68] for $E$ (naive Bayes), $G$ (logistic regression), and $H$ (support vector machines), and a publicly available decision tree implementation [90] for $F$ and for our reimplementation of $B$.
The four discrimination-free software systems use different methods to attempt to reduce or eliminate discrimination:
- $A$ is a modified logistic regression approach that constrains the regression's loss function with the covariance of the characteristics' distributions that the algorithm is asked to be fair with respect to [88].
- $B$ is a modified decision tree approach that constrains the splitting criteria by the output characteristic (as the standard decision tree approach does) and also the characteristics that the algorithm is asked to be fair with respect to [40].
- $C$ manipulates the training dataset for a naive Bayes classifier. The approach balances the dataset to equate the number of inputs that lead to each output value, and then tweaks the dataset by introducing noise of flipping outputs for some inputs, and by introducing weights for each datapoint [18].
- $D$ is a modified decision tree approach that balances the training dataset to equate the number of inputs that lead to each output value, removes and repeats some inputs, and flips output values of inputs close to the decision tree's decision boundaries, introducing noise around the critical boundaries [91].
5.2 Race and Gender Discrimination
We used Themis to measure the group and causal discrimination scores for our twenty software instances with respect to race and, separately, with respect to gender. Figure 1 presents the results. We make the following observations:
- **Themis is effective.** Themis is able to (1) verify that many of the software instances do not discriminate against race and gender, and (2) identify the software that does.
- **Discrimination is present even in instances designed to avoid discrimination.** For example, a discrimination-aware decision tree approach trained not to discriminate against gender, $B_{\text{gender}}$, had a causal discrimination score over 11%; more than 11% of the individuals had the output flipped just by altering the individual’s gender.
- **The causal discrimination score detected critical evidence of discrimination missed by the group score.** Often, the group and causal discrimination scores conveyed the same information, but there were cases in which Themis detected causal discrimination even though the group discrimination score was
low. For example, for \( \text{B census gender} \) the causal score was more than 21x higher than the group score (11.27% vs. 0.52%).
- **Today’s discrimination-aware approaches are insufficient.** The \( \text{B census gender} \) approach was designed to avoid a variant of group discrimination (as are other discrimination-aware approaches), but this design is, at least in some conditions, insufficient to prevent causal discrimination. Further, focusing on avoiding discriminating against one characteristic may create discrimination against another, e.g., \( \text{B census race} \) limits discrimination against gender but discriminates against race with a causal score of 38.40%.
- **There is no clear evidence that discrimination-aware methods outperform discrimination-unaware ones.** In fact, the discrimination-unaware approaches typically discriminated less than their discrimination-aware counterparts, with the exception of logistic regression.
### 5.3 Computing Discriminated-Against Characteristics
To evaluate how effective Themis is at computing the discrimination checking problem (Definition 3.9), we used Themis to compute the sets of characteristics each of the twenty software instances discriminates against causally. For each instance, we first used a threshold of 75% to find all subsets of characteristics against which the instance discriminated. We next examined the discrimination with respect to each of the characteristics in those sets individually. Finally, we checked the causal discrimination scores for pairs of those characteristics that are sensitive, as defined by prior work \[18, 40, 88, 91\] (e.g., race, age, marital status, etc.). For example, if Themis found that an instance discriminated causally against [capital gains, race, marital status], we checked the causal discrimination score for [capital gains, race], [race, marital status], and then [race, marital status]. Figure 2 reports which sensitive characteristics each instance discriminates against by at least 5%.
Themis was able to discover significant discrimination. For example, \( \text{B census gender} \) discriminates against gender, marital status, and race with a causal score of 77.2%. That means for 77.2% of the individuals, changing only the gender, marital status, or race causes the output of the algorithm to flip. Even worse, \( \text{B census race} \) discriminates against country and race with a causal score of 98.1%.
It is possible to build an algorithm that appears to be fair with respect to a characteristic in general, but discriminates heavily against that characteristic when the input space is partitioned by another characteristic. For example, an algorithm may give the same fraction of white and black individuals loans, but discriminate against black Canadian individuals as compared to white Canadian individuals. This is the case with \( \text{B census gender} \), for example, as its causal discrimination score against gender is 11.2%, but against gender, marital status, and race is 77.2%. Prior work on fairness has not considered this phenomenon, and these findings suggest that the software designed to produce fair results sometimes achieved fairness at the global scale by creating severe discrimination for certain groups of inputs.
This experiment demonstrates that Themis effectively discovers discrimination and can test software for unexpected software discrimination effects across a wide variety of input partitions.
### 5.4 Themis Efficiency and the Pruning Effect
Themis uses pruning to minimize test suites (Section 4.2). We evaluated the efficiency improvement due to pruning by comparing the number of test cases needed to achieve the same confidence...
and error margin 0.05. For each technique, we show the number of tests needed without pruning divided by the number of tests needed with pruning, and the resulting factor reduction in the number of tests. For example, Themis needed 3,413 tests to find sets of characteristics that $\mathbf{B_{credit}}$ discriminated with a score of more than $\theta = 0.7$, but only 10 tests when we reduced $\theta$ to 0.6. Similarly, the number of tests for $\mathbf{F_{gender}}$ dropped from 920 to 10 when lowering $\theta$ from 0.6 to 0.5. This confirms that Themis is more efficient when the benefits of fairness testing increase because the software discriminates more.
5.5 Discussion
In answering our two research questions, we found that (1) State-of-the-art approaches for designing fair systems often miss discrimination and Themis can detect such discrimination via fairness testing. (2) Themis is effective at finding both group and causal discrimination. While we did not evaluate this directly, Themis can also measure apparent discrimination (Definition 3.8) via a developer-provided test suite or operational profile. (3) Themis employs provably sound pruning to reduce test suite size and becomes more effective for systems that discriminate more. Overall, pruning reduced test suite sizes, on average, to two to three orders of magnitude.
6 RELATED WORK
Software discrimination is a growing concern. Discrimination shows up in many software applications, e.g., advertisements [75], hotel bookings [53], and image search [45]. Yet software is entering domains in which discrimination could result in serious negative consequences, including criminal justice [5, 28], finance [62], and hiring [71]. Software discrimination may occur unintentionally, e.g., as a result of implementation bugs, as an unintended property of self-organizing systems [11, 13, 15, 16], as an emergent property of component interaction [12, 14, 17, 49], or as an automatically learned property from biased data [18, 19, 39–42, 88, 89, 91].
Some prior work on measuring fairness in machine learning classifiers has focused on the Calders-Verwer (CV) score [19] to measure discrimination [18, 19, 39–42, 87–89, 91]. Our group discrimination score generalizes the CV score to the software domain with more complex inputs. Our causal discrimination score goes beyond prior work by measuring causality [67]. An alternate definition of discrimination is that a “better” input is never deprived of the “better” output [24]. That definition requires a domain expert to create a distance function for comparing inputs; by contrast, our definitions are simpler, more generally applicable, and amenable to optimization techniques, such as pruning. Reducing discrimination (CV score) in classifiers [18, 40, 88, 91], as our evaluation has shown, often fails to remove causal discrimination and discrimination against certain groups. By contrast, our work does not attempt to remove discrimination but offers developers a tool to identify and measure discrimination, a critical first step in removing it. Problem-specific discrimination measures, e.g., the contextual

bandits problem, have demonstrated that fairness may result in otherwise suboptimal behavior [38]. By contrast, our work is general and we believe that striving for fairness may be a principal requirement in a system’s design.
Counterfactual fairness requires output probability distributions to match for input populations that differ only in the label value of a sensitive input characteristic [51]. Counterfactual fairness is related to causal fairness but can miss some instances of discrimination, e.g., if loan shows preferential treatment for some purple inputs, but at the same time against some other similar purple inputs.
FairTest, an implementation of the unwarranted associations framework [79] uses manually written tests to measure four kinds of discrimination scores: the CV score and a related ratio, mutual information, Pearson correlation, and a regression between the output and sensitive inputs. By contrast, our approach generates tests automatically and measures causal discrimination.
Causal testing computes pairs of similar inputs whose outputs differ. However, input characteristics may correlate, e.g., education correlates with age, so perturbing some characteristics without perturbing others may create inputs not representative of the real world. FairML [1] uses orthogonal projection to co-perturb characteristics, which can mask some discrimination, but find discrimination that is more likely to be observed in real-world scenarios, somewhat analogously to our apparent discrimination measure.
Combinatorial testing minimizes the number of tests needed to explore certain combinations of input characteristics. For example, all-pairs testing generates tests that evaluate every possible value combination for every pair of input characteristics, which can be particularly helpful when testing software product lines [6, 44, 46, 47]. The number of tests needed to evaluate every possible value pair can be significantly smaller than the exhaustive testing alternative since each test can simultaneously contribute to multiple value pairs [22, 44, 80]. Such combinatorial testing optimizations are complementary to our work on discrimination testing. Our main goal is to develop a method to process test executions to measure software discrimination, whereas that is not a goal of combinatorial testing. Advances in combinatorial testing, e.g., using static or dynamic analyses for vacuity testing [8, 33] or to identify configuration options that cannot affect a test’s output [48], can directly improve efficiency of discrimination testing by identifying that changing a particular input characteristic cannot affect a particular test’s output, and thus no causal discrimination is possible with respect to that particular input. We leave such optimizations to future work.
It is possible to test for discrimination software without explicit access to it. For example, AdFisher [23] collects information on how changes in Google ad settings and prior visited webpages affect the ads Google serves. AdFisher computes a variant of group discrimination, but it could be integrated with Themis and its algorithms to measure causal discrimination.
Themis measures apparent discrimination by either executing a provided test suite, or by generating a test suite following a provided operational profile. Operational profiles [58] describe the input distributions likely to be observed in the field. Because developer-written test suites are often not as representative of field executions as developers would like [81], operational profiles can significantly improve the effectiveness of testing by more accurately representing real-world system use [7, 50] and the use of operational profiles has been shown to more accurately measure system properties, such as reliability [35]. The work on operational profiles is complementary to ours: Themis uses operational profiles and work on more efficient test generation from operational profiles can directly benefit discrimination testing. Meanwhile no prior work on operational profile testing has measured software discrimination.
Causal relationships in data management systems [54, 55] can help explain query results [57] and debug errors [82–84] by tracking and using data provenance [56]. For software systems that use data management, such provenance-based reasoning may aid testing for causal relationships between input characteristics and outputs. Our prior work on testing software that relies on data management systems has focused on data errors [59, 60], whereas this work focuses on testing fairness.
Automated testing research has produced tools to generate tests, including random testing, such as Randoop [63, 64], NightHawk [4], JCrash [20], CarFast [65], and T3 [69]; search-based testing, such as EvoSuite [29], TestFul [9], and eToC [78]; dynamic symbolic execution tools, such as DSC [37], Symbolic PathFinder [66], jCUTE [70], Seeker [76], Symstra [85], and Pex [77], among others; and commercial tools, such as Agitar [2]. The goal of the generated tests is typically finding bugs [29] or generating specifications [21]. These tools deal with more complex input spaces than Themis, but none of them focus on testing fairness and they require oracles whereas Themis does not need oracles as it measures discrimination by comparing tests’ outputs. Future work could extend these tools to generate fairness tests, modifying test generation to produce pairs of inputs that differ only in the input characteristics being tested. While prior work has tackled the oracle problem [10, 26, 30] typically using inferred pre- and post-conditions or documentation, our oracle is more precise and easier to compute, but is only applicable to fairness testing.
7 CONTRIBUTIONS
We have formally defined software fairness testing and introduced a causality-based measure of discrimination. We have further described Themis, an approach and its open-source implementation for measuring discrimination in software and for generating efficient test suites to perform these measurements. Our evaluation demonstrates that discrimination in software is common, even when fairness is an explicit design goal, and that fairness testing is critical to measuring discrimination. Further, we formally prove soundness of our approach and show that Themis effectively measures discriminations and produces efficient test suites to do so. With the current use of software in society-critical ways, fairness testing research is becoming paramount, and our work presents an important first step in merging testing techniques with software fairness requirements.
ACKNOWLEDGMENT
This work is supported by the National Science Foundation under grants no. CCF-1453474, IIS-1453543, and CNS-1744471.
|
{"Source-Url": "http://people.cs.umass.edu/~brun/pubs/pubs/Galhotra17fse.pdf", "len_cl100k_base": 13175, "olmocr-version": "0.1.50", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 51847, "total-output-tokens": 14245, "length": "2e13", "weborganizer": {"__label__adult": 0.0003459453582763672, "__label__art_design": 0.00032711029052734375, "__label__crime_law": 0.00119781494140625, "__label__education_jobs": 0.0013446807861328125, "__label__entertainment": 6.783008575439453e-05, "__label__fashion_beauty": 0.00014698505401611328, "__label__finance_business": 0.0003058910369873047, "__label__food_dining": 0.0002810955047607422, "__label__games": 0.0009617805480957032, "__label__hardware": 0.0005855560302734375, "__label__health": 0.00041961669921875, "__label__history": 0.0002206563949584961, "__label__home_hobbies": 7.927417755126953e-05, "__label__industrial": 0.0002675056457519531, "__label__literature": 0.00028228759765625, "__label__politics": 0.0004668235778808594, "__label__religion": 0.0002799034118652344, "__label__science_tech": 0.0257110595703125, "__label__social_life": 0.0001176595687866211, "__label__software": 0.0163116455078125, "__label__software_dev": 0.94970703125, "__label__sports_fitness": 0.00019919872283935547, "__label__transportation": 0.0003457069396972656, "__label__travel": 0.0001437664031982422}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61244, 0.01855]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61244, 0.83672]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61244, 0.89111]], "google_gemma-3-12b-it_contains_pii": [[0, 4758, false], [4758, 11898, null], [11898, 18912, null], [18912, 26908, null], [26908, 31768, null], [31768, 36579, null], [36579, 42059, null], [42059, 46884, null], [46884, 50609, null], [50609, 54470, null], [54470, 61244, null], [61244, 61244, null], [61244, 61244, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4758, true], [4758, 11898, null], [11898, 18912, null], [18912, 26908, null], [26908, 31768, null], [31768, 36579, null], [36579, 42059, null], [42059, 46884, null], [46884, 50609, null], [50609, 54470, null], [54470, 61244, null], [61244, 61244, null], [61244, 61244, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61244, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61244, null]], "pdf_page_numbers": [[0, 4758, 1], [4758, 11898, 2], [11898, 18912, 3], [18912, 26908, 4], [26908, 31768, 5], [31768, 36579, 6], [36579, 42059, 7], [42059, 46884, 8], [46884, 50609, 9], [50609, 54470, 10], [54470, 61244, 11], [61244, 61244, 12], [61244, 61244, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61244, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-01
|
2024-12-01
|
f8f8f27ad7e8a2e57a4787b629bcd5da3be86fd8
|
A Graph based architectural (re)configuration language
Conference Item
How to cite:
For guidance on citations see FAQs.
© [not recorded]
Version: Accepted Manuscript
Link(s) to article on publisher’s website:
http://dx.doi.org/doi:10.1145/503209.503213
Copyright and Moral Rights for the articles on this site are retained by the individual authors and/or other copyright owners. For more information on Open Research Online’s data policy on reuse of materials please consult the policies page.
oro.open.ac.uk
ABSTRACT
For several different reasons, such as changes in the business or technological environment, the configuration of a system may need to evolve during execution. Support for such evolution can be conceived in terms of a language for specifying the dynamic reconfiguration of systems. In this paper, continuing our work on the development of a formal platform for architectural design, we present a high-level language to describe architectures and for operating changes over a configuration (i.e., an architecture instance), such as adding, removing or substituting components or interconnections. The language follows an imperative style and builds on a semantic domain established in previous work. Therein, we model architectures through categorical diagrams and dynamic reconfiguration through algebraic graph rewriting.
1. INTRODUCTION
One of the topics that is raising increased interest in the Software Architecture community is the ability to specify how an architecture evolves over time, in particular at run-time, in order to adapt to new requirements, new business rules or new environments, to failures, and to mobility. This topic raises several issues [26], among which:
modification time and source Architectures may change before execution, or at run-time (called dynamic reconfiguration). Runtime changes may be triggered by the current state or topology of the system (called programmed reconfiguration [7]) or may be requested unexpectedly by the user (called ad-hoc reconfiguration [7]).
modification operations The four fundamental operations are addition and removal of components and connections. Although their names vary, those operators are provided by most reconfiguration languages (like [7,20,15]). In programmed reconfiguration, the changes to perform are given with the initial architecture, but they may be executed when the architecture has already changed. Therefore it is necessary to query at run-time the state of the components and the topology of the architecture.
modification constraints Often changes must preserve several kinds of properties: structural (e.g., the architecture has a ring structure), functional, and behavioural (e.g., real-time constraints).
system state The new system must be in a consistent state.
There is a growing body of work on architectural reconfiguration, some of it related to specific Architecture Description Languages (ADL) [4,18,25,1], and some of a formal, ADL-independent nature [13,19,22,28]. As we argued in [29], most of the proposals exhibit one of the following drawbacks.
- Arbitrary reconfigurations are not possible (e.g., only component replication is allowed).
- The languages used for the representation of computations are at a low level of abstraction (e.g., process calculi). They do not capture some of the abstractions used by programmers and often lead to cumbersome specifications.
- The combination of reconfiguration and computation, needed for run-time change, leads to additional formal constructs. This often results in a proposal that is not uniform, or has complex semantics, or does not make the relationship between reconfiguration and computation clear enough.
To overcome these disadvantages, we have proposed in the last ESEC/FSE an algebraic approach [29], using categorical diagrams to represent architectures, the double-pushout graph transformation approach [6] to specify reconfigurations, and a program design language with explicit state to describe computations [17]. In [30] we have further refined and extended the work, using typed graphs to represent simple topological invariants for the reconfiguration process. We have shown that our approach has several advantages over previous work, avoiding the drawbacks mentioned above:
- Architectures, reconfigurations, and connectors are represented and manipulated in a graphical yet mathematical rigorous way at the same language-independent level of abstraction, resulting in a uniform framework based simply on diagrams and their colimits (a universal categorical construction).
The chosen program design language is at a high level of abstraction, allowing a more intuitive representation of program state and computations.
Computations and reconfigurations are kept separate but related in an explicit, simple, and direct way through the colimit construction.
Typed graphs provide a simple and declarative notion of modification constraints.
Several practical problems—maintaining the constraints during reconfiguration, transferring the state during replacement, removing components in a quiescent state [15], adding components properly initialized—are easily handled.
However, the work presented was meant as an investigation into solid formal foundations for dynamic reconfiguration. It was not meant as an actual specification language. In fact, as argued in [27], describing certain kinds of transformations using only graph rewriting rules can be quite cumbersome, because it leads to heavy use of dummy nodes and arcs to control the exact way in which rewriting rules are to be applied. Unfortunately, ADLs either do not handle reconfiguration (like [24]) or they provide only a few basic reconfiguration constructs (like [25] [11] [12] [26]) making it hard or impossible to express moderately complex reconfigurations. Therefore we turned to work in Distributed Systems, in which the technological aspects of reconfiguration have been investigated for a long time.
Two of the most elegant and expressive approaches we found are Gerel [7] and reconfiguration programming [23]. Both allow the description of very complex reconfigurations in a relatively easy way, combining the usual programming language constructs (like selection and iteration) with specialised reconfiguration commands. However, approaches like these lack a formal basis, and they do not have an explicit notion of the system’s software architecture in which the reconfiguration occurs. Taking a distributed systems perspective, some approaches describe reconfigurations at a low level of abstraction, usually (dis)connecting components on a port by port basis.
In this paper we try to make a bridge between the rigour of formal approaches, the abstractions of Software Architecture approaches, and the pragmatics of Distributed Systems approaches, by presenting a language to describe architectures and complex reconfigurations in a straightforward way, while keeping the algebraic foundations laid out in our previous work. We are more interested in what are the necessary constructions needed for an effective but formal reconfiguration language, than in the actual language itself. Therefore, this paper only presents a minimal language with one specialised construct for each task (iteration, removing components, interconnecting components, querying the configuration, etc.).
The running example is taken from banking. We consider customers and accounts, in a one-to-one relationship. Besides a normal kind of accounts, there may also exist salary accounts, in which its owner gets her/his salary deposited every month. For normal accounts, it is not possible to withdraw more than the current balance, but a salary account may be overdrawn up to the salary amount. Of course, such a benefit has a price, to be paid in terms of interest calculated over the period and amount the account is below zero. Therefore, when such an account is created, or when an existing normal account becomes a salary account, the customer must explicitly state how much credit s/he wants. The credit must not exceed the salary, and in particular it may be zero, i.e., the customer may wish not to take advantage of having credit. The bank is not interested in accounts that have an average balance below zero. In those cases, the policy is to return those accounts automatically to their normal status, to prevent the financial situation of the account, and the debt of the customer towards the bank, of getting worse.
We start by summarising COMMUNITY, the program design language used to describe computations. We then introduce the language fragment to describe architectures and their constraints. Finally, in Section 4 we present the remaining of the language, in order to describe reconfigurations.
2. COMMUNITY
COMMUNITY programs are in the style of UNITY programs [3], but they also combine elements from IP [11]. However, COMMUNITY has a richer coordination model and, even more important, it requires interaction between components to be made explicit. In this way, the coordination aspects of a system can be separated from the computational aspects and externalised, making explicit the gross modularisation of the system in terms of its components and its interactions.
In this section, we summarise the syntax of COMMUNITY programs and introduce a notation for describing system configurations. Each configuration can be transformed into a single, semantically equivalent, program that represents the whole system. Finally, we discuss refinement of COMMUNITY programs. The formal definitions and proofs were presented in [17],[18].
2.1 Designs
COMMUNITY is independent of the actual data types used and, hence, we assume there are pre-defined sorts and functions given by a fixed algebraic signature in the usual sense. For the purpose of examples, we consider an algebraic signature containing sorts bool (booleans), nat (natural numbers) and int (integers) with the usual operations.
A COMMUNITY design consists of a set of typed variables and a set of actions. There are input, output and private variables. Input variables are read-only. Output and private variables are called local variables and cannot be changed by the environment. A design with input variables is open in the sense that it needs to be connected to other components of the system to read data, as explained in Section 2.2.
There are private and shared actions, but our example only uses the latter. Each action has a name, two guards, and a set of non-deterministic assignments. The safety and progress guards are propositions over the local variables and establish an interval in which the enabling condition of the action must lie, the safety guard being the lower bound. When the guards are equivalent we write only one of them. At each execution step, one of the actions whose enabling condition holds of the current state is selected, and its assignments are executed atomically in parallel. A non-deterministic assignment $l :\in E$ assigns to $l$ one of the elements of set $E$. We abbreviate $v :\in \{l\}$ as $v := l$, and we write skip to denote the absence of assignments.
For our example, we need the following designs. The first simply describes the basic functionality of an account: it lets money to be
deposited and withdrawn without any limits. There is also a variable to store the account number. No action changes the variable because its value remains fixed while the account exists. There is an action to calculate the average balance of the account, but for the moment it is irrelevant how and when the average is computed.
design NormalAccount
in amount : nat
out balance, avgbal, number : int
do deposit: true → balance := balance + amount
[] withdraw: true → balance := balance - amount
[] average: true, false → avgbal :∈ int
The second design describes a salary account, which adds to ‘NormalAccount’ a variable to store the credit given to this account, i.e., the salary deposited in it every month. The safety guard of action ‘withdraw’ is changed accordingly.
design SalaryAccount
in amount : nat
out balance, avgbal, number, salary : int
do deposit: true → balance := balance + amount
[] withdraw: balance - amount ≥ salary
→ balance := balance - amount
[] average: true, false → avgbal :∈ int
The next design models the behaviour of a customer. S/he chooses some value and then invokes one of the two operations.
design Customer
out value : nat
prv ready : bool
do deposit: ready, false → ready := false
[] withdraw: ready, false → ready := false
[] choose: ¬ready, false → value :∈ nat || ready := true
2.2 Configurations
In COMMUNITY, the model of interaction between components is based on action synchronisation and the interconnection of input variables of a component with output variables of other components. Although these are common forms of interaction, COMMUNITY, unlike other program design languages, requires interaction between components (name bindings) to be made explicit.
Connecting a design $D_1$ with a design $D_2$ is done through a channel: a set of bindings $i_1,j_1…i_2,j_2$, where each $i_1,j_1$ is a non-private variable or a set of shared actions of design $D_1$. In the first case, $i_2,j_2$ must be a non-private variable of $D_2$, of the same sort as $i_1,j_1$, and the pair $i_1,j_1$ denotes that the two variables are to be shared. In the second case, $i_2,j_2$ must be a set of shared actions of $D_2$. Moreover, every shared action of the involved designs can appear at most once in the channel definition. Intuitively, a pair
$\{a_1,1,…,a_1,n\} -\{a_2,1,…,a_2,m\}$
states that any action $a_1,j_1$ of $D_1$ must occur simultaneously (i.e., synchronise) with some action $a_2,j_2$ of $D_2$ and vice versa.
For example, the channel
$\{\text{value-amount, deposit-deposit, withdraw-withdraw}\}$
to connect a customer directly to a normal account, allows the customer to withdraw unlimited funds anytime, a highly undesirable situation (for the bank, of course).
A configuration is given by an undirected labelled graph, where each node is labelled by a design, and each arc by a channel, such that: 1) no node is connected to itself; 2) no two output variables are (directly or indirectly) shared.
Such a configuration has a very precise mathematical semantics, given by a diagram in a category whose objects are designs and whose morphisms capture a notion of program superposition. An interconnection between two components is described by a design that just declares the common variables and actions of the components, without introducing any additional behaviour, thus corresponding to the recently proposed notion of duct. This semantics has been presented previously and it is trivial to translate configurations into categorical diagrams. One of the advantages of this categorical semantics is that any diagram corresponding to a configuration can be transformed, by a universal categorical construction called colimit, into a single design that represents the whole system, as proven in.
A run-time configuration is a configuration in which each node, besides being labelled with a design $D_i$, is also labelled with its current state, i.e., with one pair $(l, value)$ for each local variable $l$ of $D_i$. Because local variables cannot be shared among designs, it is not possible for two different nodes to have different values for the same variable. Hence, the colimit of a run-time configuration always exists and is given by the colimit of the underlying configuration together with the disjoint union of all variable-value pairs.
2.3 Refinement
A key factor for architectural description is a notion of refinement that can be used to support abstraction. A design $R$ refines design $P$ if each variable of $P$ is mapped to a variable of $R$ of the same sort and kind (input, output or private), and each action of $P$ is mapped to a set of actions of $R$ of the same kind (private or shared), such that the functionality and interface (i.e., the “binding points”) of $P$ are preserved. The interface is preserved by requiring the mapping of input and output variables to be injective and the image of a shared action to be a non-empty set. To preserve functionality safety guards may not be weakened, progress guards may not be strengthened, and assignments may not be less deterministic.
The concrete syntax to define refinement morphisms is
refinement $Name$: $D_1 → D_2$ $x_1,ix_2,1…,$
end refinement
such that each $x_{1,i}$ is a variable of design $D_1$—and in that case $x_{2,i}$ is a variable of $D_2$—or an action of $D_1$—and in that case $x_{2,i}$ is a set of actions of $D_2$. The identity and inclusion refinement morphisms are implicitly defined (see Section 3.4). For our example, we have the inclusion of ‘NormalAccount’ in ‘SalaryAccount’. Another way of defining refinements is through composition:
refinement $Name$: $D_i → D_{i+1}$ $Name_1 : Name_2 :…; Name_n$
end refinement
with $Name_n$: $D_i → D_{i+1}$ a previously defined refinement or the
Channels can be composed with refinement morphisms. To be more precise, given a channel between designs $D_1$ and $D_2$ and a refinement $D_3$ of $D_2$, one can calculate a channel between $D_1$ and $D_3$ by composing every binding $i_{1,j} : i_{2,j}$ with the mapping $t_{2,j} : t_{3,j}$. Moreover, the colimit of the obtained configuration is a refinement of the colimit of the original configuration.
3. SOFTWARE ARCHITECTURE
An architecture is a class of configurations that exhibit some conceptual unity. An architectural description must therefore include the designs and interactions to be used in those configurations and a set of restrictions on the possible configurations.
We start by describing a construct to specify complex interactions between components, using the primitive mechanisms of action synchronization and variable sharing given by channels. Next we show how to describe conditions on the run-time configurations and finally we present the concrete syntax for architectures.
3.1 Connectors
Although components have always been considered the fundamental building blocks of software systems, the way the components of a system interact may be also determinant on the system properties. Component interactions were recognised also to be first-class design entities and architectural connectors have emerged as a powerful tool for supporting the description of these interactions.
According to [2], an $n$-ary connector consists of $n$ roles and one glue stating the interaction between the roles. The use of a connector in the construction of a particular system is realised by the instantiation of its roles with specific components of the system. Therefore the roles act as “formal parameters”, restricting which components may be linked together through the connector.
In our framework, a connector is represented by a star-shaped configuration, with the glue, in the center, linked to the roles, in the points of the star [9]. Normally, different connectors may use the same designs for roles, because there may exist different kinds of interactions between the same kinds of components. Moreover, the roles are the “interface” of a connector, i.e., they must be publicly known in order to initiate them with the actual components. For these two reasons, we require the designs used for roles to be specified before and outside the specification of connectors. A connector then just specifies the glue and the channels.
For our running example we need a connector with two roles, one to be instantiated with a customer and the other to be instantiated with any account. To make the example more compact, we use for the first role the “Customer” design itself. The second role is
\[
\text{design AnyAccount} \\
\text{in} \quad \text{value} : \text{nat} \\
\text{out} \quad \text{balance} : \text{int} \\
\text{do} \quad \text{credit} : \text{true, false} \rightarrow \text{balance} : \in \text{int} \\
\text{[]} \quad \text{debit} : \text{true, false} \rightarrow \text{balance} : \in \text{int}
\]
As for the connector, its glue contains a private variable to store the amount of credit given to the customer. If the customer is not allowed to overdraw the account, the credit will be zero. The credit is a constant of that particular interaction between the customer and the account that instantiate the roles. Hence, no action of the glue modifies the ‘credit’ variable.
\[
\text{connector Movement(Customer, AnyAccount)} \\
\text{design Movement} \\
\text{in} \quad \text{amount} : \text{nat}; \text{balance} : \text{int} \\
\text{prv} \quad \text{credit} : \text{nat} \\
\text{do} \quad \text{put} : \text{true} \rightarrow \text{skip} \\
\text{[]} \quad \text{get} : \text{balance} - \text{amount} \geq -\text{credit} \rightarrow \text{skip} \\
\text{channel amount-value put-deposit get-withdraw} \\
\text{channel amount-value put-credit get-debit balance-balance}
\]
Notice that the name of a connector is the name of its glue, and that the $i$-th channel describes the bindings between the glue and the $i$-th role.
An $n$-ary connector is applied to $n$ components by defining which component refines which role in which way. Usually, general-purpose connectors (e.g., for asynchronous communication or RPC) have also very general roles (i.e., which impose very little restrictions on the components that instantiate them), because such connectors are supposed to be applicable to a wide class of components. This means that several different component designs may refine the same role. Moreover, for a given role-component pair there may be several different possible refinements. However, for a particular architecture, several of these possibilities may not make sense. Normally, each role is to be refined by only a few component designs and each one of them has to refine the role in only one way. Hence, we require the architect to specify just those refinements that are possible. Identity and inclusion refinement morphisms are always allowed.
For our example, ‘AnyAccount’ can be refined in two ways.
\[
\text{refinement AN: AnyAccount} \rightarrow \text{NormalAccount} \\
\text{value/amount, balance/balance, credit/deposit, debit/withdraw}
\]
\[
\text{end refinement}
\]
\[
\text{refinement AS: AnyAccount} \rightarrow \text{SalaryAccount} \\
\text{AN; inclusion}
\]
\[
\text{end refinement}
\]
Moreover, there is the identity between the ‘Customer’ role and the component design.
3.2 Constraints
The components, connectors, and refinements specified by the architecture only provide the vocabulary to write configurations. In other words, they only impose minimal, syntactic restrictions on the class of configurations for an intended software system.
To describe more complex constraints we use a first-order language where variables are typed by designs or connectors. Such variables range over the nodes of the current run-time configuration, in the case of a connector the referred node being the glue. The connector predicate
\[
\text{ConnectorVar}([\text{RefinementName}_1 \rightarrow \text{ComponentVar}_1, \ldots])
\]
is satisfied if the configuration contains a star-shaped subgraph with the node ConnectorVar connected to the given component nodes.
ComponentVar, through channels obtained by composing the channels from the glue ConnectorVar to the roles with the given refinements from the roles to the components. If it is not relevant how one of the roles is intantiated, both RefinementName and ComponentVar may be the anonymous variable, which we write as in Prolog, using the underscore character. Moreover, we use the usual notation [X] to describe optional syntactic elements. In this case, the name of the refinement is omitted if it is an identity or an inclusion.
Since uniqueness constraints are quite common (e.g., in a token-ring topology, exactly one node has the token at any time), we also use the unique existential quantifier (∃!).
For example, the following formula states that every customer must be connected to exactly one account and vice versa.
\[(\forall c:Customer \exists! m:Movement m(c, _)) \land (\forall a:NormalAccount \exists! m:Movement m(_, AN \rightarrow a)) \land (\forall a:SalaryAccount \exists! m:Movement m(_, AS \rightarrow a))\]
In dynamic reconfiguration, there is an interplay between the topology of the run-time configuration and the state of the nodes. Therefore, constraints may also refer to the local variables of the node designs. Because names of design variables are not global, they must be qualified by the name of the node, for which we use a dot notation: NodeVar.VariableName. For our example, we need to specify that if the customer has a normal account, the withdrawal credit is zero; if s/he has a salary account, the withdrawal credit cannot exceed the salary.
\[(\forall a:NormalAccount; m:Movement m(_, AN \rightarrow a) \Rightarrow m.credit = 0) \land (\forall a:SalaryAccount; m:Movement m(_, AS \rightarrow a) \Rightarrow m.credit \leq a.salary)\]
Constraints may also use (in)equality predicates over node variables. For our example, we require account numbers to be unique.
\[(\forall a1, a2 : NormalAccount a1 \neq a2 \Rightarrow a1.number \neq a2.number) \land (\forall a1, a2 : SalaryAccount a1 \neq a2 \Rightarrow a1.number \neq a2.number) \land (\forall n:NormalAccount; s:SalaryAccount n.number \neq s.number)\]
### 3.3 Configuration Variables
In the same way that components have variables to describe their current state, it is desirable to have variables to store information about the current run-time configuration. Such configuration variables may be typed over the available data sorts, component designs, and connector (i.e., glue) designs. Configuration variables can be used in constraints and are only updated by reconfiguration commands. We achieve a clean separation between computation and (re)configuration because design actions can only use the variables declared in the same design, and because no kind of binding between configuration variables and design variables is allowed.
As an example, consider a token ring architecture, in which each component ‘RingComp’ has a boolean local variable ‘hasToken’ that is true only while the component holds the token. The reconfiguration commands to be presented in Section [4.1] allow one to find the node that currently holds the token, but such an operation is costly, being linear in the size of the ring. It is more efficient to have a configuration variable ‘holder:RingComp’ that refers to that node, and that is updated whenever the token is transferred to another node. The semantics of the variable is given by the constraint
\[\text{holder}.hasToken \land \exists! x:RingComp x.hasToken\]
which states that only the node referred by ‘holder’ has the token.
As for our running example, we use two counters: one for the number of accounts (which is the same as counting the customers), and another for the number of salary accounts. Normally, a person has her or his salary account in the bank s/he likes most. Therefore, the ratio between the two counters is an indication of the percentage of customers that have this bank as their prime choice.
### 3.4 Architectures
Putting all together, an architecture defines: the designs that may be used as components (and roles) and the refinement relationships between them; the designs that may be used only for roles, the connectors, and the refinement morphisms for each role; the configuration variables; and a constraint on the possible configurations.
The architecture for our example illustrates the concrete syntax:
```
architecture Bank
components
design Customer ...
design NormalAccount ...
design SalaryAccount ...
connectors
design AnyAccount ...
connector Movement(Customer, AnyAccount) ...
variables allAccounts, salAccounts : nat
constraint C
end architecture
```
Notice that this architecture has no refinements other than the implicit identities and inclusions.
Within the components and connectors sections, the definitions of designs, refinements, and connectors may appear in any order, as long as a name is not used before it is defined.
A (run-time) configuration is said to be an instance of a given architecture A if:
- all nodes are labelled either with a component or a glue of A;
- each arc connects a component to the glue of a connector;
- each node labelled with the glue of a connector C has exactly as many arcs as the arity of C defined in A, and the i-th arc is labelled by a channel obtained from composing the channel of the glue to the i-th role R_i with one of the possible refinement morphisms between R_i and the component on the other end of the arc.
The second condition prevents two components from being directly connected through a channel, i.e., interactions are only established through connectors. The third condition ensures that each connector was properly applied to components. Notice that the roles only serve to constrain how a connector can be applied; they do not appear in the configuration.
4. RECONFIGURATION
The only possible changes to a configuration are creation and removal of nodes (whether they are components or glues). These basic commands can be combined into more complex changes using sequencing, choice, and iteration operators. Changes can be grouped into scripts, which correspond to procedures in Pascal-like languages. Besides the global configuration variables declared at the architectural level, scripts may declare local configuration variables, and may have configuration variables as parameters. These variables are changed by the scripts and their values are used to compute the new configuration. There is also a command to query the current configuration, returning all tuples of nodes that match some conditions. These nodes can then be processed by the reconfiguration commands.
The semantics of basic reconfiguration commands is given by conditional graph productions over the categorical diagram representing the current run-time configuration. The reconfiguration interpreter executes these productions in the order specified by the scripts and composite commands.
4.1 Commands
As was the case with constraints on the architecture, the reconfiguration language to be presented next makes heavy use of node references, which are variables that are typed by designs. A node reference is undefined if it does not refer to any node of the current run-time configuration. In the following description of the language, \( Node \) stands for such a variable. The state of any node can be accessed using a dotted notation: \( Node.V ar \) refers to the local variable \( V ar \) of node \( Node \). This makes it possible to write arbitrary expressions \( Exp \) involving the operations of the data types used by COMMUNITY and the values of the local variables of the nodes of the current configuration. Of course, \( Exp \) is undefined if at least one of the node references it uses is undefined.
The examples in this subsection assume the existence of the following declarations:
\[
\begin{align*}
n &: \text{NormalAccount}; \\
s &: \text{SalaryAccount}; \\
c &: \text{Customer}; \\
n &: \text{nat}
\end{align*}
\]
4.1.1 Component Creation
The command to create a component node is
\[
[\text{Node} :=] \\
\text{create Design with } l_1 := Exp_1 \parallel l_2 := Exp_2 \ldots
\]
where \( Node \) must be declared of type \( Design \) and \( l_i \) are the local variables of \( Design \). All local variables must be assigned to, in order to correctly initialise the new component. This reconfiguration command does nothing if some expression \( Exp_i \) is undefined. The reference to the created component is stored in \( Node \), if given. The names occurring in \( Exp_i \) are resolved in the context in which this command occurs, not in the context of \( Design \). This makes it possible to use script parameters that have the same names as the local variables of designs, to improve readability of the script.
For example, consider the following command:
\[
\begin{align*}
n &: \text{create NormalAccount with} \\
& \quad \text{balance} := n.\text{balance} \parallel \text{avgbal} := 0 \parallel \text{number} := \text{number}
\end{align*}
\]
This creates a new account, transferring the money from an existing account ‘n’. The number of the new account is given by the value of the variable declared above. After the command, ‘n’ refers to the new account. If ‘n’ is undefined, no component is created (because it is impossible to initialise it), and hence ‘n’ remains undefined.
4.1.2 Component Refinement
A common reconfiguration is to update a component, e.g., to add new functionality, eliminate bugs, or improve efficiency. In our framework, this is achieved through replacement of a component by a refinement (other than the identity) of it. The syntax is
\[
\begin{align*}
[\text{Node} :=] \\
\text{create Design}_2 \text{ as } [\text{Refinement}([\text{Node}_1])] \\
\text{with } l_1 := Exp_1 \parallel \ldots
\end{align*}
\]
where \( Node_2 \) is of type \( Design_2 \) and \( Node_1 \)’s type is some \( Design_1 \).
This command removes \( Node_1 \) and replaces it by a new node \( Node_2 \). For any glue to which \( Node_1 \) was connected, through some channel \( c \), the new node becomes connected to the same glue through a channel that is the composition of \( c \) with \( \text{Refinement} \). Only the new local variables \( l_i \) —i.e., those of \( Design_2 \) that do not correspond to any variable of \( Design_1 \) —are assigned to; the rest of the state of \( Node_2 \) is transferred from \( Node_1 \).
The command does nothing if \( Node_1 \) or some \( Exp_i \) is undefined, otherwise \( Node_2 \) becomes undefined after the execution of the command. If the parentheses and the refinement name are omitted, then \( Design_1 \) and \( Design_2 \) must be different and the refinement is an inclusion.
For example, the command
\[
s := \text{create SalaryAccount as } n \text{ with salary} := 100000
\]
replaces the normal account ‘n’ by a salary account with the same balance, average balance, and account number as ‘n’. Since design ‘SalaryAccount’ only adds one variable to design ‘NormalAccount’, only that variable has to be explicitly initialised.
4.1.3 Connector Creation
The command to create a connector has a slightly different syntax:
\[
\begin{align*}
[\text{Node} :=] \\
\text{apply Connector ([} \text{Refinement}_1 \rightarrow ] \text{Node}_1, \ldots) \\
\text{with } l_1 := Exp_1 \parallel l_2 := Exp_2 \ldots
\end{align*}
\]
where \( l_i \) are the local variables of the glue of the \( \text{Connector} \). This command applies the connector to the given components, creating a node typed by the glue, and linking it to the given components \( Node_1 \) through channels that are obtained by composition of the channels declared in the connector definition with the refinements given by the command. This composition can be calculated at compile time since all information is available. If the refinement name and arrow are absent, this indicates an identity or inclusion morphism.
This command does nothing if some \( Node_1 \) or \( Exp_i \) is undefined, or if the creation of the connector would make output variables to be shared, which would violate the conditions on configurations.
For example, the command
apply Movement(c, AS → s) with credit := s.salary
connects the salary account created above with a customer who has chosen the maximum allowed credit, namely her/his salary. In this example the reference to the new node is not stored in any variable.
4.1.4 Removal
The command to remove a node is remove Node. After this command, Node is undefined. As usual, the command does nothing if Node was already undefined. If Node refers to a glue, then the node and all its attached channels are removed. If Node refers to a component, then it is removed only if it is attached to no channels, because otherwise the resulting configuration would not be an instance of the architecture anymore, since the glues connected to Node would have an arity less than prescribed by the architectural definition.
For example, the command ‘remove c’ (or ‘remove s’) does not change the configuration if it comes right after the connector creation command given above, because customer ‘c’ (resp. account ‘s’) is connected, namely to salary account ‘s’ (resp. customer ‘c’).
4.1.5 Query
The query expression
match {Decl1 | [Decl2] [Configuration] with Condition}}
returns all tuples of nodes Decl1 for which there exist nodes Decl2 such that the current run-time configuration includes the sub-configuration Configuration in a state where Condition holds.
Configuration is just a set of (in)equalities or connector predicates (as defined in Section 3.2) over previously declared node variables, in particular those in Decl1 and Decl2. The scope of those two declaration sequences is just the query expression. Condition is a boolean expression over the operations provided by the available data types, i.e., it may not contain connector predicates or (in)equalities over node references. In other words, Condition tests the state of the current configuration, while Configuration tests its topology.
The with part can be omitted if the condition is a tautology, and Decl2 and Configuration can also be omitted when not necessary, e.g., if we wish just to find in the current run-time configuration all nodes given in Decl1.
For the query expression to be possible, the reconfiguration language must include record types ‘record(Field1; Type1; Field2; Type2; . . .)’ and list types ‘list(Type)’ with the usual operations ‘head’, ‘tail’, ‘cons’, ‘append’, and the empty list constant ∅. The type of the query expression is then ‘list(record(Decl1))’.
By storing the node tuples that match the query in a list, they become amenable to further manipulation, like iteration, sorting, filtering according to other criteria, counting, etc. Moreover, computing once the nodes on which we want to further operate, eliminates the need to use dummy variables to make sure that no operation is performed twice on the same tuple of nodes.
For example, the expression
match {c:Customer | a:SalaryAccount; m:Movement m(c, AS → a) with m.credit = 0}
selects all customers that have a salary account but have chosen not to have any credit. The resulting list can be used for different purposes, e.g., just counting how many customers are in that situation, or transforming those accounts automatically into normal accounts. The latter involves removing the connector and the salary account, creating a normal account with the same balance and number, and then connecting it to the customer. Therefore, a better expression would be
match {c:Customer; a:SalaryAccount; m:Movement | m(c, AS → a) with m.credit = 0}
because it would also return the references to the accounts and movements necessary for the ensuing transformations.
As another example, match {a:SalaryAccount | a ≠ s} returns all salary accounts except the one referred by variable ‘s’. If ‘s’ is undefined, so is the configuration condition, and therefore the query returns the empty list.
4.1.6 Assignment
The assignment Var := Exp updates the configuration variable Var, if Exp is not undefined. Notice that Var is not a local variable of some node, because reconfiguration does not change the state of existing nodes; it only initialises new nodes and removes nodes.
For example, assuming the existence of a function to calculate the length of a list, the assignment
number := length(append(match {a:NormalAccount}, match {a:SalaryAccount}))
would store in ‘number’ how many accounts the bank currently has.
4.1.7 Composite Commands
The basic commands just presented can be combined into composite commands using the sequencing operator ‘;’, the conditional command
if Condition then Command [else Command] end if
and the iteration command
while Condition loop Command end loop
where Command is a basic or composite command, and Condition is as explained in Section 4.1.5.
Since iterating through a list of nodes is so frequent, we introduce the following abbreviation:
for Var in Expression loop Command end loop
Expression is a list, Var must be of the type of the list elements, and this command expands into
\[
\text{NewVar} := \text{Expression}; \\
\text{while NewVar} \neq \emptyset \text{ loop} \\
\text{Var} := \text{head}(\text{NewVar}); \text{NewVar} := \text{tail}(\text{NewVar}); \\
\text{Command} \\
\text{end loop}
\]
For example, to remove all unconnected customers, the command is simply
\[
\text{for } i \in \text{match } \{ \text{c:Customer} \} \text{ loop} \text{ remove } i \text{ end loop}
\]
with ‘i : record(c:Customer)’. In fact, it is guaranteed that remove does nothing if ‘c’ is connected.
4.2 Scripts
A script is a command that has a name so that it can be called from other scripts. A script may have input and output parameters, and private variables, with concrete syntax as for ComMMUNITY designs (see examples below). Scripts may be recursive (e.g., this is useful to process tree topologies) and nested. Only top-level scripts can be called directly by the user. The coordination between computation and reconfiguration is achieved by a reconfiguration interpreter that constantly executes the following loop:
1. Execute one computation step on the run-time configuration.
2. Let the user execute one of the scripts, if s/he wishes.
3. If there is a script called ‘Main’, execute it.
4. Go to step 1.
Step 2 caters for ad-hoc reconfiguration and step 3 handles programmed reconfiguration. By interleaving computation and reconfiguration (as also done in [19]), one can be assured that changes to the configuration will be triggered by changes to the state as soon as needed. Furthermore, the changes performed in step 2 and 3 are committed to the architecture only if, after execution of the called script, the constraints on the architecture are still valid.
Notice that users may only call scripts; they may not write arbitrary commands. This is to prevent them from making changes that would invalidate the architectural invariants. We assume that only system administrators have the necessary overall knowledge of the system to write scripts. Ad-hoc reconfiguration is also coped by letting the set of available scripts change during system life-time. The administrator may hence add, remove or replace scripts at any time.
We now present the scripts for our bank example. We begin with the main script. It is responsible for transforming salary accounts automatically into normal accounts if the average balance is negative, and thereby updates the ‘salAccounts’ counter.
\[
\text{script Main} \\
\text{prv } n : \text{NormalAccount} ; i : \text{record(m:Movement; c:Customer)}
\]
\[
\text{for } i \in \text{match } \{ \text{s:SalaryAccount} \} \text{ with } \text{a.avgbal} < 0 \text{ loop} \\
i := \text{head}(\text{match } \{ \text{m:Movement; c:Customer} | \text{m(c, AS \rightarrow s.a)} \}) \\
n := \text{create NormalAccount} \\
\text{with } \text{balance} := \text{s.a.balance} \\
\text{with } \text{avgbal} := \text{s.a.avgbal} \\
\text{with } \text{number} := \text{s.a.number} \\
\text{remove } i \text{.m; } \\
\text{remove } s.a; \text{salAccounts} := \text{salAccounts} - 1; \\
\text{apply Movement(i.c, AN \rightarrow n) with credit := 0} \\
\text{end loop} \\
\text{end script}
\]
Notice how the state of the salary account is transferred to the normal account.
The next script creates a normal account, with a given number. It also creates a client and connects it to the account. The script does nothing if an account with the given number already exists.
\[
\text{script CreateNormal} \\
\text{in } \text{number} : \text{nat} \\
\text{out } n : \text{NormalAccount} \\
\text{prv } c : \text{Customer} \\
\text{if } \text{match } \{ \text{a:NormalAccount} | \text{with a.number} = \text{number} \} = \emptyset \\
\text{\& match } \{ \text{s:SalaryAccount} | \text{with a.number} = \text{number} \} = \emptyset \\
\text{then} \\
n := \text{create NormalAccount} \\
\text{with } \text{balance} := 0 \\
\text{with } \text{avgbal} := 0 \\
\text{with } \text{number} := \text{number} \\
c := \text{create Customer with value := 0 \& ready := false} \\
\text{apply Movement(c, AN \rightarrow n) with credit := 0} \\
\text{allAccounts := allAccounts + 1} \\
\text{end if} \\
\text{end script}
\]
The third script creates a salary account, given the salary, the credit the customer wishes, and the account number. The script first checks that the credit asked for is less than the salary. Next, it proceeds according to the three possible cases: if a salary account with that number already exists, nothing is done; if a normal account with that number exists, it is refined into a salary account, and the connector is replaced; otherwise, the salary account has to be created from scratch. Just to illustrate calling of scripts, this is done by creating a normal account and then proceeding as in the second case.
\[
\text{script CreateSalary} \\
\text{in } \text{salary, credit, number} : \text{nat} \\
\text{out } s : \text{SalaryAccount} \\
\text{prv } n : \text{NormalAccount} ; l : \text{list(record(n: NormalAccount))} \\
i := \text{match } \{ \text{n:NormalAccount} \} | \text{with n.number} = \text{number} \} = \emptyset \\
\text{\& match } \{ \text{s:SalaryAccount} | \text{with s.number} = \text{number} \} = \emptyset \\
\text{then} \\
l := \text{match } \{ \text{n:NormalAccount} | \text{with n.number} = \text{number} \} \\
\text{if } l = \emptyset \text{ then CreateNormal(number, n)} \\
\text{else } n := \text{head}(l).n \\
\text{end if} \\
i := \text{head}(\text{match } \{ \text{m:Movement c:Customer} | \text{m(c, AN \rightarrow n)} \}) \\
\text{remove i.m; } \\
s := \text{create SalaryAccount as s with salary := salary} \\
\text{create Movement(i.c, AS \rightarrow s) with credit := credit;}
\]
4.3 Semantics
There are two kinds of commands: the basic commands perform the actual reconfiguration, while the composite commands and scripts only control the flow of execution. The semantics we provide to the language consists in translating the basic commands into the graph rewrite rules (also called graph productions) defined in [29][30]. The composite commands then just instruct the graph rewriting machine in which order the rules are to be executed. We do not present the complete translation process, nor do we provide formal definitions. We just sketch the main idea and provide concrete examples. A report with further details is in preparation.
The compilation of the reconfiguration commands into productions proceeds as follows. First, each component and glue design is compiled into a design that adds a new private variable ‘\texttt{NI}’ nat’, such that \texttt{NI} is a name that does not occur in any design given in the architecture. The purpose of the variable is to hold a unique node identifier. For our example, we assume \texttt{NI} is ‘node’.
Second, the compiler generates configuration designs that have only private variables. Each design corresponds to one lexical scoping level (i.e., to one reconfiguration script), and the private variables correspond to the configuration variables that are visible in that level. This means that all those designs include the global configuration variables declared with the architecture. If a configuration variable is a node reference (e.g., \texttt{c:Customer}) then it will be compiled into a variable of type ‘nat’ (e.g., \texttt{c:nat}). That variable will hold zero if the node reference is undefined, otherwise it will hold the value of the \texttt{NI} variable of the referred node. Moreover, all those configuration designs have a variable ‘\texttt{C}: nat’ which counts how many nodes have been globally created, so that each newly created node can get a unique identifier. The name \texttt{C} must of course be different from the names of all configuration variables. For our example we assume \texttt{C} is ‘nodes’. The actual names of the designs must be chosen by the compiler so that it does not conflict with any other design specified in the architecture. For our example, we assume those designs are named ‘\texttt{C_S}’ with \texttt{S} ranging over the script names.
A basic command in script \texttt{s} is translated into a set of graph productions in which the left-hand side always includes ‘\texttt{C_S}’ and any other nodes that are referred by the expressions occurring in the command. The right-hand side includes also those same nodes, but ‘\texttt{C_S}’ is updated with the new values for the configuration variables and for the node counter. The right-hand side also includes any newly created component or glue and omits any removed component or glue.
As an example, we show in Figure 1 the graph production corresponding to the component creation command given in the ‘Main’ script in Section 4.2. Each node is labelled with the design name and with design variable/logical value pairs. According to the definitions in [29][30], the production can only be applied if there is a substitution for the logical variables \texttt{vnodes, vn, bal}, etc., such that the left-hand side graph can be mapped to a subgraph of the current run-time configuration. Notice that if the node reference ‘\texttt{s.a}’ is undefined (i.e., \texttt{sa} = 0), then the production cannot be applied (because ‘node’ is always positive), and the configuration does not change, as required by the description of \texttt{create} in Section 4.1.1. Notice also how \texttt{C_Main} is updated and how the new node is initialised.
Our next example, in Figure 2, is the translation of the connector removal command of script ‘Main’. Notice that one rule is generated for each possible instantiation of the roles. In this case, there are only two possibilities: the first role is instantiated with a customer and the second one is instantiated with a normal or salary account. In the particular context of the execution of script ‘Main’, by the time one of these rules is executed, one has \texttt{vc = cust}. The channel bindings have been omitted from the figure due to space limitations.
The command to replace a component is the most complex one, because one cannot know \texttt{a priori} to which connectors the component to be replaced is attached. Therefore the command is compiled into a set of productions that do the replacement in three phases: the first introduces the new component, the second relinks all connectors to the new component, and the last phase removes the original component. For the second phase, there is one production for each role of each connector that the node to be replaced may instantiate. For example, if there were two connectors \texttt{C_1(R_1, R_2)} and \texttt{C_2(R_3, R_4, R_6)}, and a node \texttt{n_1} of type \texttt{N_1} were to be replaced by a node \texttt{n_2} of type \texttt{N_2}, with refinements from \texttt{R_1, R_4} and \texttt{R_6} to \texttt{N_1}, then there would be three productions, one replacing the first channel of \texttt{C_1} to \texttt{n_1} by a channel from \texttt{C_2} to \texttt{n_2}, another production for the first channel of \texttt{C_2} and the last production for the third channel of \texttt{C_2}. The set of productions generated for this second phase of the replacement is to be applied until no left-hand side can be matched to the current configuration. At that point, the node to be replaced has no connector attached and the single rule for the last phase can be applied: it simply removes the node, updating the node reference given in the command.
As a concrete example, let us take the component refinement command of ‘CreateSalary’. The semantics of this command is given by three productions (Figure 3). The first introduces a new salary account, transfers the state from ‘n’, initialises the ‘salary’ local variable, and updates the node reference ‘s’. The second production rebinds any ‘Movement’ connector that might be attached to ‘n’ to the new node ‘s’. The rebinding is done by moving the channel between the glue and the old node to the new node. The last rule removes the node referred by ‘n’, which becomes undefined (i.e., zero).
5. CONCLUDING REMARKS
Dynamic reconfiguration is an important topic for an increasing number of software systems that must be continuously available while coping with all kinds of changes. However, to our knowledge, there is no work that tackles this problem from the Software Architecture point of view and provides a formally based language that integrates the three aspects argued for in [28]: architectural description, constraint, and modification. This paper is a first step in that direction.
We have provided an approach that is both heterogeneous (for pragmatic reasons) and uniform (for formal reasons). It is heterogeneous because it provides an dedicated, separate sub-language for each aspect: a program design language for computation, a declarative language for constraints, and an operational language for reconfiguration. It is uniform because it uses Category Theory as a semantic foundation both for configurations (taken as categorical diagrams) and reconfiguration (achieved through algebraic graph
rewriting techniques [6]).
The approach also provides a strict separation between computation and (re)configuration, while keeping them explicitly related. This was already done at the formal level in our previous papers [29][30], and the language presented herein complies with that principle: the components do not have access nor can change the configuration variables or call scripts, and the reconfiguration scripts have access but cannot change the state of components. Notice that replacing a component by another one of the same design but with a different state is not what we mean by state change, because there are actually two components involved: the original one is removed and a new one is created.
The main goal of our language is to provide high-level constructs that are suited to the architectural level of description of a system. In particular, interactions are created and removed at the level of connectors, hence guaranteeing that configurations are always instances of the architecture. This contrasts with other approaches which, like the Armani ADL [24], force the designer to write explicit constraints to prevent dangling roles, or, like distributed systems approaches, require reconfiguration scripts to connect the components port by port.
Because our emphasis was on obtaining an integrated language that covers the three aspects (description, constraints, modification), we are aware that other approaches handle some individual aspects better, but in turn they have to sacrifice formality or breadth. For example, Armani allows more complex architectures and connectors. In particular, interactions are created and removed at the level of connectors, hence guaranteeing that configurations are always instances of the architecture. This contrasts with other approaches which, like the Armani ADL [24], force the designer to write explicit constraints to prevent dangling roles, or, like distributed systems approaches, require reconfiguration scripts to connect the components port by port.
Because our emphasis was on obtaining an integrated language that covers the three aspects (description, constraints, modification), we are aware that other approaches handle some individual aspects better, but in turn they have to sacrifice formality or breadth. For example, Armani allows more complex architectures and connectors. In particular, interactions are created and removed at the level of connectors, hence guaranteeing that configurations are always instances of the architecture. This contrasts with other approaches which, like the Armani ADL [24], force the designer to write explicit constraints to prevent dangling roles, or, like distributed systems approaches, require reconfiguration scripts to connect the components port by port.
Therefore, in future work, we want to further investigate which fundamental constructs (not syntactic sugar!) are needed for the various aspects, and how they can be formally grounded on our algebraic framework. Practical feedback from such research will be gathered by incorporating such reconfiguration primitives into a tool [12] being built to construct and manage coordination contracts— which are akin to connectors— among components implementing core business functionalities [3].
Two other issues are also of concern to us. First, we would like to be able to prove whether a given script maintains the architectural invariants. For that purpose we intend to adapt the logic developed in [10]. Second, we want to extend this work to allow the architecture itself to evolve. This means that during some period the configuration is not an instance of any architecture, neither the original nor the new one. This poses interesting problems both for the language design (because the script will be typed by two architectural descriptions) and for the verification of the correctness of such a reconfiguration process. We will look into [14][8] and see how it can be adapted to our framework.
Acknowledgments
We thank Luis Andrade and the anonymous reviewers for their comments.
6. REFERENCES
Figure 2: Semantics of ‘remove i.m’
Figure 3: Semantics of ‘s := create SalaryAccount as n with salary := salary’
|
{"Source-Url": "http://oro.open.ac.uk/1167/2/wermelinger01esec.pdf", "len_cl100k_base": 12764, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 46894, "total-output-tokens": 15508, "length": "2e13", "weborganizer": {"__label__adult": 0.0003101825714111328, "__label__art_design": 0.0007162094116210938, "__label__crime_law": 0.0002435445785522461, "__label__education_jobs": 0.0005626678466796875, "__label__entertainment": 6.657838821411133e-05, "__label__fashion_beauty": 0.00012934207916259766, "__label__finance_business": 0.0001627206802368164, "__label__food_dining": 0.0003273487091064453, "__label__games": 0.0004534721374511719, "__label__hardware": 0.0005221366882324219, "__label__health": 0.00032448768615722656, "__label__history": 0.0002341270446777344, "__label__home_hobbies": 6.723403930664062e-05, "__label__industrial": 0.0002906322479248047, "__label__literature": 0.00028204917907714844, "__label__politics": 0.0002391338348388672, "__label__religion": 0.0004367828369140625, "__label__science_tech": 0.01031494140625, "__label__social_life": 6.216764450073242e-05, "__label__software": 0.004749298095703125, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.0002264976501464844, "__label__transportation": 0.0003948211669921875, "__label__travel": 0.00019228458404541016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63262, 0.01828]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63262, 0.68202]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63262, 0.8807]], "google_gemma-3-12b-it_contains_pii": [[0, 823, false], [823, 4891, null], [4891, 11600, null], [11600, 17384, null], [17384, 23613, null], [23613, 29454, null], [29454, 35765, null], [35765, 40666, null], [40666, 46437, null], [46437, 53770, null], [53770, 59643, null], [59643, 61873, null], [61873, 63262, null]], "google_gemma-3-12b-it_is_public_document": [[0, 823, true], [823, 4891, null], [4891, 11600, null], [11600, 17384, null], [17384, 23613, null], [23613, 29454, null], [29454, 35765, null], [35765, 40666, null], [40666, 46437, null], [46437, 53770, null], [53770, 59643, null], [59643, 61873, null], [61873, 63262, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63262, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63262, null]], "pdf_page_numbers": [[0, 823, 1], [823, 4891, 2], [4891, 11600, 3], [11600, 17384, 4], [17384, 23613, 5], [23613, 29454, 6], [29454, 35765, 7], [35765, 40666, 8], [40666, 46437, 9], [46437, 53770, 10], [53770, 59643, 11], [59643, 61873, 12], [61873, 63262, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63262, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
f273d677a6defdfff2dd000569aa016eadc3289c
|
[REMOVED]
|
{"len_cl100k_base": 13242, "olmocr-version": "0.1.49", "pdf-total-pages": 31, "total-fallback-pages": 0, "total-input-tokens": 59185, "total-output-tokens": 16745, "length": "2e13", "weborganizer": {"__label__adult": 0.0003056526184082031, "__label__art_design": 0.0009055137634277344, "__label__crime_law": 0.00022852420806884768, "__label__education_jobs": 0.00495147705078125, "__label__entertainment": 0.00010001659393310548, "__label__fashion_beauty": 0.00019800662994384768, "__label__finance_business": 0.00028586387634277344, "__label__food_dining": 0.0002684593200683594, "__label__games": 0.00045990943908691406, "__label__hardware": 0.0010519027709960938, "__label__health": 0.0003180503845214844, "__label__history": 0.0003600120544433594, "__label__home_hobbies": 0.0001137852668762207, "__label__industrial": 0.00033926963806152344, "__label__literature": 0.0003466606140136719, "__label__politics": 0.00022721290588378904, "__label__religion": 0.0004477500915527344, "__label__science_tech": 0.028167724609375, "__label__social_life": 0.00012433528900146484, "__label__software": 0.0104827880859375, "__label__software_dev": 0.94921875, "__label__sports_fitness": 0.0002046823501586914, "__label__transportation": 0.0005078315734863281, "__label__travel": 0.00018107891082763672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71305, 0.02722]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71305, 0.55643]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71305, 0.91882]], "google_gemma-3-12b-it_contains_pii": [[0, 1339, false], [1339, 5103, null], [5103, 8886, null], [8886, 12484, null], [12484, 15467, null], [15467, 18546, null], [18546, 19552, null], [19552, 22460, null], [22460, 24411, null], [24411, 26906, null], [26906, 28878, null], [28878, 30871, null], [30871, 33463, null], [33463, 35731, null], [35731, 37841, null], [37841, 39076, null], [39076, 39483, null], [39483, 42226, null], [42226, 43377, null], [43377, 44879, null], [44879, 48012, null], [48012, 49402, null], [49402, 50186, null], [50186, 52452, null], [52452, 54958, null], [54958, 58423, null], [58423, 60329, null], [60329, 64187, null], [64187, 68892, null], [68892, 70278, null], [70278, 71305, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1339, true], [1339, 5103, null], [5103, 8886, null], [8886, 12484, null], [12484, 15467, null], [15467, 18546, null], [18546, 19552, null], [19552, 22460, null], [22460, 24411, null], [24411, 26906, null], [26906, 28878, null], [28878, 30871, null], [30871, 33463, null], [33463, 35731, null], [35731, 37841, null], [37841, 39076, null], [39076, 39483, null], [39483, 42226, null], [42226, 43377, null], [43377, 44879, null], [44879, 48012, null], [48012, 49402, null], [49402, 50186, null], [50186, 52452, null], [52452, 54958, null], [54958, 58423, null], [58423, 60329, null], [60329, 64187, null], [64187, 68892, null], [68892, 70278, null], [70278, 71305, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71305, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71305, null]], "pdf_page_numbers": [[0, 1339, 1], [1339, 5103, 2], [5103, 8886, 3], [8886, 12484, 4], [12484, 15467, 5], [15467, 18546, 6], [18546, 19552, 7], [19552, 22460, 8], [22460, 24411, 9], [24411, 26906, 10], [26906, 28878, 11], [28878, 30871, 12], [30871, 33463, 13], [33463, 35731, 14], [35731, 37841, 15], [37841, 39076, 16], [39076, 39483, 17], [39483, 42226, 18], [42226, 43377, 19], [43377, 44879, 20], [44879, 48012, 21], [48012, 49402, 22], [49402, 50186, 23], [50186, 52452, 24], [52452, 54958, 25], [54958, 58423, 26], [58423, 60329, 27], [60329, 64187, 28], [64187, 68892, 29], [68892, 70278, 30], [70278, 71305, 31]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71305, 0.00697]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
29a16432a2b75b4dcb47a1955fab8e5adafb4fb0
|
Awareness of the low fidelity nature of a MVP – How the initial Technology Acceptance is influenced
Author: Maximilian Möllers
University of Twente
P.O. Box 217, 7500AE Enschede
The Netherlands
ABSTRACT: Through the years, entrepreneurship has gained a scientific perspective. Scholars around the world aim to solve the issues start-ups and scale-up face during their pursuit of growth. Within the Lean Startup, Eric Ries provides guidance to entrepreneurs in order to reduce the time a startup spends on activities which do not contribute to growth. This paper discusses the problems which may arise during early customer tests and investigates solutions in order to solve these problems without spending time on activities which do not contribute to the start-ups’ growth. Ries emphasizes that such early user tests need to be conducted with a certain type of potential customer called early adopter. By taking a look at the characteristics which describe these valuable users, the acceptance of a prototype presented is identified as a crucial factor to such testing phase. However, due to limited resources or varying business concepts many start-ups are forced to build a low quality prototype as suggested in the Lean Startup Methodology. This study found that whether or not the user is aware of the situation, which forced the entrepreneurs to build a low quality prototype, the technology acceptance is not affected. Therefore, we are able to state that any effort in teaching the user about missing features at the current state, will not contribute to the start-ups overall learning process and can be avoided.
Supervisors: PD Dr R. Harms (Rainer)
Keywords
The Lean Startup, Prototyping, Technology Acceptance, User testing, MVP, Adoption
Permission to make digital or hard copies of all or part of this work for personal or classroom use is granted without fee provided that copies are not made or distributed for profit or commercial advantage and that copies bear this notice and the full citation on the first page. To copy otherwise, or republish, to post on servers or to redistribute to lists, requires prior specific permission and/or a fee.
Copyright 2016, University of Twente, The Faculty of Behavioural, Management and Social sciences.
1. INTRODUCTION
Eric Ries’ Lean Startup Methodology (LSM) is not just a success story of a young Entrepreneur but also a well-recognized new perspective on how to systematically manage startups. Ries aim is to build upon the first century of management initiated by Frederic Taylors Scientific Management and to introduce the second century of management, which applies a rather lean methodology to management. This methodology is built on theories such as Lean manufacturing (Toyota) or Design Think and suggests techniques such as validated learning, the minimum viable product (MVP) and pivoting. The main concept of the lean startup methodology is based on the principle of validated learning, meaning to design processes and procedures in such a way that everything that does not contribute to the learning effect can be accounted as waste and therefore should be avoided. Entrepreneurs should consider identification and testing of the most important assumptions of a venture before building a final product which may or may not meet the expectations of the market (Blank 2013). This strategic process should be managed in a scientific way (Ries 2011). The concept of seeing entrepreneurship from a scientific perspective has gained great reputation in the past years. Having different perspectives on strategic entrepreneurship enables a scientific investigation in different Lean Startup Methodologies which today’s corporations also take advantage of (Furr and Dyer 2014, Owens and Obie 2014).
Especially the concept of building a minimum viable product has exceeded the boundaries of startups and scale-ups. The concept is today applied even in corporations all over the world and included in most business schools’ curriculums. Due to the fact that the minimum viable product helps entrepreneurs with starting the learning process as quickly as possible, the concept is well understood by today's entrepreneurs of all kinds (Ries 2011). In order to understand the variety of minimum viable products, Ries states that the appearance of a minimum viable product might even take the form of an advertisement which aims is to proof a concept to actual early prototypes that have missing features and show a range of problems. In particular, this paper will discuss the concept and efficient application of an MVP as well as the consequences of such method on the individuals who are willing to do the initial tests. The core function of the minimum viable product is the fast learning process the prototype facilitates. Therefore, Ries suggests that when low acceptance of the prototype by initial users due to limited functionality or low quality occurs, the entrepreneur might consider an investment into a superior design (Ries 2011). However, the focus of this paper will lie on the analyse of alternative options to expensive and time consuming improvements on the prototype, when low acceptance is present in early stage prototyping.
2. LITERATURE GAP
So far scholars have focused on the concept of building a better mousetrap, meaning optimizing the product and its usability in order to attract more user and potential customers (Rogers 1983). The researchers have taken different approaches into consideration which aim to improve the rate of adoption by such early customers. The five characteristics, Relative advantage, compatibility, complexity, trial ability, and observability which when combined should attract a significant higher amount of early adopters to innovation then by neglecting these factors (Rogers 1983). Furthermore, Rogers notes that the type of innovation, the communication channels, the nature of the social system and the extent of change agent promotion effort also stand in correlation with the rate of adoption of an innovation. The persuasion of such attributes is however conflicting with the core assumptions of a minimum viable product and therefore cannot be applied in order to attract an initial base of customers who are willing to test the entrepreneurs early prototype. Instead of investigating resources into the adoption of users by focusing on a high quality product and service, the existing literature did not take the concept of focusing resources on the development of potential customers into consideration. Meaning, not to neglect user who do not accept the product yet but rather to help them understanding the product and the development process. Ries (2011) mentions the apparition of doubt when a invited test user does not provide the feedback that was initially expected. “If he doesn’t give good feedback he might be not the right customer.” This kind of doubt is a general problem to entrepreneurs who seek opinions from the pool of potential customer at hand (Ries 2011).
2.1 Problem Statement
Entrepreneurs who make use of a minimum viable product as suggested within the lean startup methodology are highly dependent on receiving feedback within the “measure phase”. Feedback is especially important in order to experience validated learning and finally to build an upgraded version of the product based on the new insights. A study conducted by the research institute Standish Group states that there are 3 main reasons why projects are late, over budget or fail to deliver desired functionality. The reasons listed are a lack of user input, incomplete requirements and changing requirements. When a lack of user input occurs and feedback is missing, continuing the cycle might not be possible. In order to ensure a continuous interaction and attraction of new users who are willing to provide this feedback, an improved product or service to attract new user (Rogers 1983). However, this method would contradict the build measure learn cycle by omitting the “learn” aspect which should eventually lead to the decision to improve the prototype. This paper will investigate the possibilities an entrepreneur has in order to find early test user who accept a minimum viable product and are willing to provide the needed feedback.
3. RESEARCH QUESTION
This paper focuses on finding a viable solution to the problem of experiencing a lack of test users. This problem can be caused due to low acceptance of a low quality minimum viable product. In order to do so, this paper will focus on elaborating an alternative to the process of improving the prototypes quality and functionality. Many scholars described different types of prototypes from which one of the more commonly used distinctions differentiates between low fidelity and high fidelity Prototypes (Ruud, 1996). Meaning that the degree of fidelity is dependent on the representativeness of the prototype in regards to the prototypes actual concept. Therefore, test users are introduced to the requirements and difficulties of testing a concept with a prototype in form of a MVP. By giving the user an introduction to the product development phase and the test purpose the aim is to raise the awareness of the low fidelity nature of a minimum viable product as discussed in section 4.1. This paper hypothesizes that, when familiar with the difficulties and requirements of product testing, the test user shows a higher
degree of technology acceptance and therefore is more viable for the initial testing. This concept will be used to tests whether transparency of the entrepreneurial process stimulates people to engage into the product development.
- How does the awareness of the low fidelity nature of the MVP correlate with the user acceptance of the product?
- How does the awareness of the low fidelity nature of the MVP correlate with the perceived usefulness of an MVP?
- How does the recognition of the minimum viable product correlate with the perceived ease of use of the MVP?
3.1 Hypothesis:
When aware of the low fidelity nature of a minimum viable product, initial test users show greater acceptance towards the prototype.
4. THEORETICAL FRAMEWORK
This section provides a general understanding of the different theories and their relation in order to form a generally understood basis for this research. The discussed theories concern the topics of the lean startup methodology, information systems as well as users and prototypes concepts in regard to innovation research.
4.1 The Minimum Viable Product
In order to understand the nature of a prototype such as an MVP and its role within the product development this section will review the literature concerning the concept and different applications of prototyping. Generally speaking, a prototype is a tool which serves as a common ground between customers and developers, so they can understand the application of the product or service in a way which cannot be obtained by reading the functional specifications. Furthermore, a prototype is able to serve for educational purpose so the user gains an understanding about how the tested application works (Bellantone, C.E. and Lanzetta, 1992). Other scholars refer to a prototype as: “... any representation of a (design) idea, regardless of the medium” (Houde&Hill, 1997, p. 369)
In regards to the concept of the minimum viable product (MVP), this form of a prototype can be described as the version of the product that enables the entrepreneur to conduct tests with a minimum amount of effort and the least amount of development time. The minimum viable product shows only the core features which are needed to test the assumptions made concerning a specific market or product. An MVP is built in order to reduce the time spend on building something which is not appreciated by the customer. This form of a prototype is the fastest way to get through the Build measure learn feedback loop with a minimum amount of effort (Ries 2011). The build measure learn cycle, which builds the core of the lean startup model, is generally the process of creating a tool in order to measure assumptions, gathering valuable information concerning the product and finally improving the concept based on the information collected (Ries 2011). It is of crucial importance to set aside traditional professional standards and to make use of the process of validated learning as soon as possible (Ries 2011). Therefore, it is suggested to remove any process, feature or effort which does not contribute directly to the desired learning process. Removing processes and features seems to decrease the quality of the prototype. However, Ries argues that “If we do not know who the customer is, we do not know what quality is.” (Ries, 2011) Especially within a startup, it is risky to assume that the company already knows which attributes are perceived as worthwhile by the customer. Therefore, building an MVP which has limited functionality can be perceived as low quality by the customers (Ries 2011). Entrepreneurs should use the customer's low-quality perception of the MVP as an opportunity to learn what attributes customers care about. (Ries 2011 p.109) In order to define the advantages and disadvantages of such prototype with limited functionality, scholars classified prototypes in regard to the amount of features and functions as low or high fidelity Prototypes (Rudd 1996). The characteristics of an MVP as a low fidelity prototype are discussed in following section (3.2)
4.2 Low/High-Fi Prototype
The fidelity of a prototype is determined by the degree to which the prototype is experienced by the person viewing it, rather than the similarity to the actual application (Tullis 1990). The prototyping literature is highly influenced by Jim Rudd, who emphasizes that there is a clear distinction between two different types of Prototypes. His distinction is based on the fidelity to the original concept of a prototype. Therefore, he distinguishes between a low fidelity and a high fidelity prototype. In his paper “Low vs high-fidelity prototyping debate, 1966” the core concepts and differences between different types of prototypes are discussed in this respect for the first time. Low-fidelity prototypes are generally limited in functionality and the degree of interaction possibilities. Furthermore, the intentions of using a low fidelity prototype are usually to depict concepts, design alternatives, and screen layouts. Furthermore, it is stated that low fidelity prototypes supposed to communicate, educate, and inform, but not to train or serve as a basis from which to code (Rudd 1996).
In order to distinguish the low-fi prototype from a high-fi prototype Rudd’s defined advantages and disadvantages of the high fidelity prototype. This prototype is described to be fully functional and interactive and therefore can be applied for detailed user testing (Rudd 1996). Besides the functionality these types of prototypes can furthermore serve as marketing and sales tools. The disadvantages of this kind of prototype compared to a low fidelity prototype are usually the development costs and the relative high time consumption in the development phase. Defining the characteristics and different design versions of a prototype can help the entrepreneur to identify the most important aspects to focus on while building the prototype. In order to measure whether or not the user is aware of the different stages a prototype can have, survey items were constructed based on the characteristics of a low fidelity prototypes described by Rudd (1996)
4.2.1 Customer expectations in regard to prototyping.
When operating in uncertainty, the competitive landscape and dynamic customer expectations might be changing rapidly. This effect requires firms to seek flexibility in product development. (Zhang, Vonderembse, Cao, 2009) Furthermore today's firms are experiencing increased customer expectations (Sethi et al. 2003). Therefore, applying the concept of a minimum viable product allows the entrepreneur to stay flexible during the prototype developing process. Customer needs serve as input to the process of building a product concept that meet customer expectations (Zhang, Vonderembse, Cao 2009). However, customers often experiencing difficulties when describing their expectations. Therefore, rapid prototyping can serve as a communication tool which gathers customer needs which otherwise remain unknown. By applying this process, the prototypes provide a real feel and touch to its users. (Zhang, Vonderembse, Cao, 2009) Furthermore “product concept flexibility” and “product prototype flexibility” become the foundation for creating customer satisfaction. This satisfaction can be achieved by aligning the coordination of development processes with the customer’s expectations. (Zhang, Vonderembse, Cao, 2009)
The next step in conducting this research is to clarify the optimal user to test the concept with. According to Ries 2011 (Page 94) the most viable group of a social system in regards to testing a prototype are the early adopters. He describes the difficulties in early product testing is to find the early adopter rather than an average customer. (p.68) Ries supports this claim by stating that those early adopters tend to be more forgiving in regards to mistakes and are especially keen to provide feedback.
4.3 Adopter categories
In order to get the most viable feedback on the concept which is represented by the prototypes, not every individual is equally qualified. Ries distinguishes in this regard between a test user and customer. While you can invite any potential customer regardless of his or her attitude towards the product, that person will not become an early adopter just by testing a prototype. However, by identifying and testing with the individual who might become an early adopter in the later product stage, Ries (2011) argues that the feedback received is positively influenced. This section distinguishes the average customer from the early adopter by elaborating the process that describes the adoption of new products by different individuals.
The term early adopter is widely used by today’s innovation researchers, entrepreneurs and marketers, however originated already in 1962 within E.M Rogers’ Diffusion of Innovation. Diffusion is described as a process of communication which aims to reach members of a social system throughout certain communication channels (Rogers, 1995). However other terminology can be found in the literature which refer to the same phenomenon of early customers. One of the most widely read literatures which build upon Rogers ‘Diffusion of Innovation’ is Geoffrey Moore’s Crossing the Chasm. Furthermore, Eric Von Hippel’s research into “lead users” shows great similarity with the concept of early adopters. The term earlyevangelist was used by Steve Blank in order to emphasize the evangelical powers of such early customers.
The concept discussed in this paper is the diffusion of Innovation by Rogers, which divides the mass market into five segments. While Early adopters make 13.5 % of a social system to adopt an innovation there are 4 further types of adopter categories. The first 2.5 % of the social system consists of the so called innovators. Furthermore, Rogers, lists the early majority (34%), the late majority (34%) and finally the laggards (16%). Roger (1995) showed that most distributions of individuals have been found to be normal categorized by the standard deviations from the mean. (see Appendix 11.6) According to Ries 2011 (Page 94) the most viable group of this social system in regards to testing a prototype are the mentioned early adopters. He describes the difficulties in early product testing is to find the early adopter rather than an average customer. In addition, Rogers states that early adopters have the highest degree in regards to opinion leadership within the social system. (Rogers 1995). The early adopters are the individuals who show the greatest need for the product while simultaneously showing a high willingness to give feedback and be more forgiving in regards to mistakes within the product (Ries 2011). The success of an innovation is determined by what the early adopters say and expresses about that particular innovation to the public, what marks the early adopter as highly valuable for the product testing phase (Ries 2011). Furthermore, early adopters accept and even prefer a prototype which might only represent 80% of the final concept. Therefore, it is necessary that new products need to be sold to early adopters first before a successful mass market adoption can be achieved. (Ries, 2011)
By having identified the need for involving early adopters in the initial user tests we can conclude that the acceptance of the prototype by the user is crucial in order to build upon the initial testing. Which means that in order to assess an initial test users influence on the product development, the acceptance of the given innovation by the user needs to be measured.
4.4 Technology Acceptance Model
In order to examine whether the user’s degree of acceptance of the MVP is influenced by the users’ awareness of the low fidelity nature of the MVP, it is necessary to define the term acceptance.
Therefore, the concept of technology acceptance (Davis, Bagozzi & Warshaw 1989) will be taken into account when validating the acceptance of the minimum viable product. This model distinguishes between the perceived usefulness and the perceived ease of use as a cause to either accept or reject a technology based on the behavioral Intention to use the innovation. The technology acceptance model serves the function to represent a causal relationship between a system’s design characteristics and the acceptance and usage in the workplace. The model posits that the behavioral intention to use a system is constructed based on the user’s perceived usefulness and perceived ease of use. Where the perceived usefulness can be described as the degree to which an individual is convinced that using a certain system would enhance the user’s job performance and perceived ease of use which can described as degree to which user believe that using a certain system is free of effort while at the same time the user might perceive the system as useful. The ease of use when compared with the perceived usefulness requires direct experience with the system in order to become well formed. Therefore, the measures are likely to deviate over time while additional features and functions are added to the system. In order to finally assess the actual system,
use and therefore the technology acceptance the behavioral intention to use the system is preconditioned. This factor is constructed by measuring the two indicators of perceived usefulness and perceived ease of use. When both indicators are validated, a behavioral intention to use the system can be assumed (Davis, Bagozzi & Warshaw 1989). The causal relation between the factors is displayed under Figure 1.

**Figure 1**
5. METHODOLOGY
Conducting user evaluation during the early stage of a product or service is generally designed to collect feedback concerning improvement options for design or conceptual aspects. However, for the purpose of this research, we were interested in the user’s general attitude towards the product rather than the mentioned improvement opportunities. Therefore, the focus lies on evaluating how influential an individual’s awareness of the product appears when taking the overall acceptance into consideration. In order to study this issue, the approach of taking an already existing MVP for the research purpose was chosen. By exposing the prototype to initial test user, reactions concerning the acceptance were obtained. A team of student entrepreneurs within the Hardstart foundation at the University of Twente in the Netherlands provided a minimum viable product for test purposes. The team developed an early prototype in order to test the concept of a social gaming platform. The concept was designed in order to provide video game enthusiasts the opportunity to indicate a willingness to collaborate in a video game chosen from a great pool of possible games to play. For further information, see Appendix 11.8.
5.1 Sample
The analysis is based on a sample of in total 33 participants who identified themselves as a user of video gaming software on a regular basis. The participants were approached individually and randomly assigned to either group A (18 participants) or group B (15 participants) with an exception which took the user’s already existing knowledge concerning the state of the prototypes into consideration as explained later in this section. Participants of group A received an introduction to the process of prototyping and the role of an MVP, in order to provide awareness of the low-fi nature of the MVP. Therefore, a standardized introduction text was provided to the participants of group A before the testing. The introduction text can be found under Appendix 11.7. Participants of group B did not receive any form of introduction to role and state of the minimum viable product. Those participant who indicated that he or she were to any extend familiar with the state of the prototype before the testing and introduction process were assigned to group A. Due to existing knowledge about the state of the prototype by 5 participants, the division of the two groups experienced an imbalance.
During the testing phase participants proceeded through three part. While group A was provided with the standardized text in order to ensure awareness of the low fidelity nature of the prototype, group B did not receive an introduction and therefore initiated with a 5 minutes’ test of the prototype. Group A proceeded after the introduction, under the same conditions as the other group, with the 5 minutes’ prototype testing. The prototype testing phase was not guided and therefore the participants were able to get familiar and explore the system independently.
Finally, all participants were asked to answer 36 questions in form of survey items in order to elaborate the perceived usefulness (14 items) and the perceived ease of use (13 items) of the prototype as well as the awareness of the low-fi nature of the MVP (9 items).
5.2 Constructs and variables
The intention to use a prototype was selected as the dependent variable for this study, due to the Technology Acceptance Models (TAM) characteristics of being the most widely researched models in regards to the user acceptance literature. TAM is particularly suited to study user reactions to prototypes due to its beliefs in technology acceptance, e.g., perceived usefulness and perceived ease of use (Davis, Venkatesh 2004). Furthermore, most usability tests focus primarily on a system’s ease of use and therefore usually fail to evaluate the usefulness of the system’s functionality. Consequently, the chances of error detection are decreased when assessing the system’s core requirements (Davis, Venkatesh 2004). Therefore, both factors, perceived ease of use and the perceived usefulness are taken into consideration when assessing the test user’s individual intention to use the system. The two factors were individually analyzed in regards to the influence of the independent variable. As such the awareness of the low fidelity nature of the MVP is assigned as the independent variable. In order to assess a difference in technology acceptance between two groups a general awareness of the state and function of the prototype was analyzed.
5.3 Scale formation process
5.3.1 Dependent Variable: Technology Acceptance
The candidate items designed for measuring the technology acceptance were divided into the perceived usefulness and perceived ease of use of the prototype. The items were formulated by Davis 1989, based on their conceptual definitions, as stated in section 4.4. In order to choose the number of items for the two scales perceived ease of use and perceived usefulness, the Spearman-Brown Prophecy formula was applied, which is used to eliminate reliability errors that might occur from choosing an insufficient amount of items. The estimated items then should also ensure reliability while comparing with existing scales. Therefore, the formula suggests that in order to achieve a reliability of at least .80, ten items are needed per variable (Davis, 1986). In order to allow item elimination, four additional items were generated for the measurement of perceived usefulness and three items for the ease of use measures. Therefore, within each set of items the questions tend to have an overlap within their meaning. This however is due to the fact these items are intended as measure of the same underlying construct.
Davis 1989 furthermore emphasizes that even though there is a chance that different individuals attribute different meanings to a
stated item, the goal in regards to the multi-item approach is to decrease the level of extraneous effects of the listed items. This process allows the other items to cancel out idiosyncrasies, which ultimately results in a purer indication of the chosen conceptual variable. The questionnaire asked participants to rate the extent to which they agree with each statement by choosing a number from one to seven arranged horizontally beneath anchor point descriptions “Entirely Agree,” “Neither Agree nor Disagree,” and “Entirely Disagree.” Find the items in regards to perceived usefulness as well as the items used to measure perceived ease of use under Appendix 11.1. Each individual item is measured on a Likert Scale as indicated via Figure 2.

**Figure 2**
After recoding the negative items of all scales, the importance of each item in regards to the influence on the individual variables was assessed by conducting a factor analysis.
While conducting the reliability measure of the items in regard to the perceived usefulness, a high consistency was observed. With a Cronbach's alpha of 0.916 we are able to accept the reliability of this measure. Also the items measured which relate to the perceived ease of use showed a high consistency in its measure. The cronbach's alpha in this case was an indicator for acceptance with a value of 0.904.
5.3.2 Independent Variable: Awareness of the Low-Fi Nature of the MVP
In order to test the awareness of the low-fidelity nature of the MVP, 9 items were constructed. Source for the constructed items was the paper “Low vs. high-fidelity prototyping debate” by Rudd (1996). The author listed certain characteristics in form of advantages and disadvantages of the prototype design in regards to low and high fidelity which serve as basis for the item construction. (see Appendix 11.5)
The questions are measured on a Likert scale from 0-7 as described for the technology acceptance measures. Find the items in regard to awareness testing in Appendix 11.1.
While analysing the factors of the scale in regards to the awareness of the low fidelity nature of the MVP, no sufficient reliability between all items was found. However, 3 subgroups were identified which showed internal consistency. The first group identified consists of 2 items within a total of 9 items (1,4), the second sub group showed 3 items (2,3,8) and the third subgroup included 4 items (5,6,7,9). Whilst the first sub group seems to correlate with the short term development of the service, the second group distinguishes itself from the others by a high correlation between items which indicate a missing awareness of personal influence on the development process. The items of the third group could be grouped as managerial and economic aspects. Due to its sole purpose as manipulation check the variable awareness of the low fidelity nature of the MVP, could be split in 3 sub-groups from which one showed a significant difference between the groups as explained in section 6.2. The items in regards to their subgroups can be found under Appendix 11.2.
5.4 Method of Analysis
The data collected as described in section 5.1 is the result of a 1-7 likert scale. This type of data can be categorized as ordinal data. Jameson S. (2004), argues that frequencies, χ2 tests, contingency tables, the Mann-Whitney U test, or the Spearman rho assessment are suited for the analysis of ordinal data rather than parametric tests, which require interval data. However, Jameson S. (2004) also states that under certain conditions parametric tests can be used to analyze ordinal data collected via a Likert scale. The first assumptions are a sufficient sample size of at least 5–10 observations per group. Secondly the data needs to be normally distributed (or nearly normal). Furthermore, Norman (2010) describes parametric tests to be sufficiently robust in order to yield largely unbiased answers which are acceptably close to the true value when analyzing Likert scale responses. Rickards G, Magee C, Artino AR., Jr (2012) clarify that when to measure concepts which are less concrete, meaning where a single item is not likely to capture the full concept, researchers group the items into a survey scale and calculate a mean score for the scale items. Therefore, we can conclude that in order to analyze the construct of technology acceptance and the low fi awareness of the MVP we need to test the assumption of normal distribution and insure a sample size larger than 10 for each groups.
6. ANALYSIS
6.1 Test for normal distribution.
In order to test the whether or not the samples follow a normal distribution which is assumed for a wide range of statistical tests, we took a look at the criteria of skewness and the kurtosis in regards to the individual scales of perceived usefulness, perceived ease of use, awareness of the low fidelity nature of the MVP as well as the individual subgroups in regards to the awareness variable used as manipulation check. All mentioned items showed a close to normal distribution when considering the criteria of skewness and kurtosis proposed by George and Mallory (2010) where the values should lie within ± 2. The exact skewness and kurtosis for each variable can be found under appendix 11.3.
6.2 Test of independence
When analysing the variable awareness of the low fidelity nature of the MVP which is used to verify the manipulation of Group A, we identified three sub categories. Each category was tested based on its independency in order to identify a difference between the two groups. The subgroups 1 and 3 did not show a significant result. However, when analysing the second sub group a clear distinction between the groups was identified with an alpha of 0.013. As mentioned earlier the second subgroup including the items 2,3 and 8 which can be related to a missing awareness of personal influence on the development process. Therefore, we can conclude that the manipulation had a significant influence on the groups. A pilot test of the constructed manipulation check variable might have resulted in a clearer distinction and is discussed under Limitations in section 8.
7. RESULTS
In order to analyse the influence of the awareness of the low fidelity nature of an MVP on the acceptance of a prototype an independent sample t-test of the constructs means was constructed after verifying the assumption of normal distribution. Table 11.4 in the appendix shows that the independent variable has no influence on neither the perceived usefulness (0.835) nor the perceived ease of use (0.177). Therefore, we can conclude that there is no significant relation which indicates a relation between the awareness of a prototype and the two variables which determine the technology acceptance of an initial test user. We fail to support the initial hypothesis that the awareness of a low fidelity prototype has an influence on the initial user’s acceptance of a minimum viable product.
8. CONCLUSION AND DISCUSSION
The results give evidence that when making use of initial user testing especially when the lean startup methodology is applied the pre knowledge and awareness of prototyping procedures does not influence the test users’ acceptance of the tested prototype. In regard to Ries statement that early adopters show a higher acceptance and tolerance towards the prototype we can state that these early adopters do not need to be familiar with the entrepreneurial process linked to the product development in order to show a high degree of acceptance. In this regard it is possible to state that when the entrepreneur considers to market a product for early user testing, the focus of converting users to test and interact with the system does not need to lie on an explanation of the current prototype state and its development. The user will accept or reject the prototype based on his or her position in the adopter categories (Ries 2011) Therefore, we can conclude that when considering early user testing with the help of a minimum viable product, the acceptance of the user should be influenced by other factors than the awareness of the test users concerning the state and role of the current product or service. According to this study, by explaining and justifying the prototype, the entrepreneur does not contribute to the validated learning effect as desired within the lean startup methodology. Therefore, explanation and justification concerning missing features and the purpose of the prototype should not be considered when the initial purpose of the user testing is related to the products concept and usability improvement. When experiencing a lack of user to participate in these early tests traditional, methods such as monetary compensation or vouchers for returned survey might appear more efficient.
By filtering processes which do not contribute to the growth of a start-up, or how Eric Ries defines, those who do not contribute to the validated learning effect, it is possible to decrease the high mortality rate of start-ups. For further theoretical research which builds upon the findings presented in this study, an investigation in factors which may have a significant influence on the technology acceptance of early test user is suggested. By constructing a multivariate analysis of different factors such as the initial users’ demographics, ability to learn new concepts or previous experience with similar products, scholar dedicated to scientific entrepreneurship might be able to eliminate find significant correlations. After filtering which process may or may not correlate with the acceptance of a prototype, we are able to avoid those which do not contribute to the validated learning process.
9. LIMITATIONS
Experiencing a low consistency within the awareness constraint we had to use subgroups for analyzing the representativeness of the variable. In order to construct a more reliable manipulation check a pilot test with 3-4 participants before the data collection process should be conducted. This test should concern the items used to measure the initial user’s acceptance of the state of the MVP, in order to provide a clearer distinction between the groups. However, the factor analysis showed that there is a difference between the groups based on the second factor found when dividing the construct into three subcategories.
Furthermore, by including a multivariate analysis in order to draw conclusions to this paper’s research question, we would have been able to control associations between additional variables which might influence the technology acceptance of the initial user. By taking the gender, nationality, occasion or age into consideration, regression models can provide more insight into the relationships between the variables used within this study. However due to the limited timeframe which affected this study, demographics and further variables would appear as the same. This is due to the fact that the time limitations affected the reach of potential test user.
10. REFERENCES
Maurya, A. (2012). Running lean: iterate from plan A to a plan that works. " O'Reilly Media, Inc.".
11. APPENDIX
11.1 Items
Perceived Usefulness
1. Finding other gamers would be difficult to do without xpradar.com.
2. Using xpradar.com can give me greater control over online friends.
3. Using xpradar.com can improves my gaming experience.
4. xpradar.com addresses my gaming-related needs.
5. Using xpradar.com saves me time.
6. xpradar.com enables me to find gamer to game with more quickly.
7. xpradar.com supports critical aspects of online gaming.
8. Using xpradar.com allows me to accomplish find more gamers than it would be possible otherwise.
9. Using xpradar.com reduces the time I spend on searching for others to game with.
10. Using xpradar.com enhances my fun experience while gaming.
11. Using xpradar.com improves the quality of my gaming skills.
12. Using xpradar.com increases my search productivity.
13. Using xpradar.com makes it easier to find gamer.
Perceived Ease of Use
1. I often become confused when I visit xpradar.com.
2. I make errors frequently when using xpradar.com.
3. Interacting with xpradar.com is often frustrating.
4. I have a lot of questions when using xpradar.com.
5. Interacting with xpradar.com requires a lot of my mental effort.
6. xpradar.com is rigid and inflexible to interact with.
7. I find it easy to get the xpradar system to do what I want it to do.
8. xpradar.com is often frustrating.
9. I find it cumbersome to use xpradar.com.
10. My interaction with xpradar.com is easy for me to understand.
11. It is easy for me to remember how to perform tasks using xpradar.com.
12. xpradar.com provides helpful guidance in performing tasks.
13. Overall, I find xpradar.com easy to use.
Awareness of the low-fi nature of the MVP
1. I suggest that the xpradar team should rather concentrate on converting new users than collecting feedback concerning design and concept.
2. I assume that the impact I have on the development of xpradar is limited.
3. It seems to me that the xpradar team experienced high development costs.
4. I expect the concept and design of xpradar.com not to change within the next months.
5. The website can help me to express and clarify my expectations of the service to the developers.
6. It seems to me that xpradar.com has identified its market and user requirements.
7. Xpradar.com appears very detailed to me.
8. I am convinced I can influence the next steps the xpradar team does.
9. I perceive the goal of xpradar, at the current state, to be profit maximization.
11.2 Subgroups EFA (Awareness)
<table>
<thead>
<tr>
<th></th>
<th>F</th>
<th>Sig.</th>
<th>t</th>
<th>df</th>
</tr>
</thead>
<tbody>
<tr>
<td>AwarenessofLFnatureM</td>
<td>.064</td>
<td>.001</td>
<td>1.934</td>
<td>31</td>
</tr>
<tr>
<td>EAN</td>
<td>1.178</td>
<td>.286</td>
<td>.271</td>
<td>31</td>
</tr>
<tr>
<td>AwarenessSub1</td>
<td>6.985</td>
<td>.013</td>
<td>1.616</td>
<td>31</td>
</tr>
<tr>
<td>AwarenessSub2</td>
<td>.009</td>
<td>.926</td>
<td>1.107</td>
<td>31</td>
</tr>
</tbody>
</table>
11.3 Normality testing
<table>
<thead>
<tr>
<th></th>
<th>Statistic</th>
<th>Std. Error</th>
</tr>
</thead>
<tbody>
<tr>
<td>PerceivedUsefulnessMEAN</td>
<td>Mean</td>
<td>4.4156</td>
</tr>
<tr>
<td></td>
<td>Skewness</td>
<td>-.759</td>
</tr>
<tr>
<td></td>
<td>Kurtosis</td>
<td>.686</td>
</tr>
<tr>
<td></td>
<td>Mean</td>
<td>4.8441</td>
</tr>
<tr>
<td>PerceivedEaseofUseMEAN</td>
<td>Skewness</td>
<td>-.975</td>
</tr>
<tr>
<td></td>
<td>Kurtosis</td>
<td>.945</td>
</tr>
<tr>
<td></td>
<td>Mean</td>
<td>4.1717</td>
</tr>
<tr>
<td>AwarenessofLFnatureMEAN</td>
<td>Skewness</td>
<td>-.535</td>
</tr>
<tr>
<td></td>
<td>Kurtosis</td>
<td>.309</td>
</tr>
<tr>
<td></td>
<td>Mean</td>
<td>4.1818</td>
</tr>
<tr>
<td>AwarenessSub1</td>
<td>Skewness</td>
<td>.214</td>
</tr>
<tr>
<td></td>
<td>Kurtosis</td>
<td>-.441</td>
</tr>
<tr>
<td></td>
<td>Mean</td>
<td>4.3232</td>
</tr>
<tr>
<td>AwarenessSub2</td>
<td>Skewness</td>
<td>-.1304</td>
</tr>
<tr>
<td></td>
<td>Kurtosis</td>
<td>2.893</td>
</tr>
<tr>
<td></td>
<td>Mean</td>
<td>4.0530</td>
</tr>
<tr>
<td>AwarenessSub3</td>
<td>Skewness</td>
<td>-.563</td>
</tr>
<tr>
<td></td>
<td>Kurtosis</td>
<td>1.277</td>
</tr>
</tbody>
</table>
11.4 Two Sample T-Test
<table>
<thead>
<tr>
<th></th>
<th>t</th>
<th>df</th>
<th>Sig. (2-tailed)</th>
</tr>
</thead>
<tbody>
<tr>
<td>PerceivedUsefulnessMEAN</td>
<td>.210</td>
<td>31</td>
<td>.835</td>
</tr>
<tr>
<td>PerceivedEaseofUseMEAN</td>
<td>1.381</td>
<td>31</td>
<td>.177</td>
</tr>
</tbody>
</table>
11.5 Low-fi Pro/Cons
Advantages of Low-fidelity Prototype (Rudd 1996)
- Lower development cost.
- Evaluate multiple design concepts.
- Useful communication device.
- Address screen layout issues.
- Useful for identifying market requirements.
- Proof-of-concept.
Disadvantages of Low-fidelity Prototype (Rudd 1996)
- Limited error checking.
- Poor detailed specification to code to.
- Facilitator-driven.
- Limited utility after requirements established.
- Limited usefulness for usability tests.
- Navigational and flow limitations.
11.6 Adopter Categories Normal Curve
11.7 Standardized Introduction text (xpradar.com)
Xpradar is a project which aims to facilitate video gamers to find other gamers who would be willing to play the same games together, whether it is online or via local cooperation. The project is guided within Hardstart the student association for Entrepreneurs in Twente. Currently the team is working on
collecting feedback in order to improve its first version of the xpradar prototype.
The major focus on the collection of feedback is part of the Lean Startup methodology which the team takes into consideration while planning its strategic development. The goal is to use the prototype in order to attract user who are willing to try the concept which is facilitated by this type of prototype called Minimum Viable Product (MVP). The MVP allows the team to test the basic assumptions without developing a very comprehensive program that includes all features and functions as stated in the business plan. Having spent little time on development, the team is now able to present its prototype to you so you can help improving the prototype. All your feedback is highly appreciated and will be taken into account when considering different concepts of the idea.
11.8 Case: xpradar.com
Xpradar.com is a web based application which is supported by a map in order to brows a certain location for video gamers in regards to specific video games. The program is designed to indicate a location on the map at which the individual user represents his profile. By interacting with the map pin (Marker) which represents the indicated location, other users are able to display the information needed to connect with the person that is represented by this particular marker. The information displayed are regarded to the games played, languages spoken and communication channels used (e.g. Skype Steam etc.) on a regular base.
In order to insert this information into the system a menu panel is displayed which under settings displays options to add or change information of the user. Furthermore, the general menu panel provides the user with an overview of the best fitting markers, matching with the personal information provided.
|
{"Source-Url": "https://essay.utwente.nl/70069/1/M%C3%B6llers_BA_BMS.pdf", "len_cl100k_base": 9699, "olmocr-version": "0.1.53", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 31539, "total-output-tokens": 11319, "length": "2e13", "weborganizer": {"__label__adult": 0.0008077621459960938, "__label__art_design": 0.0044708251953125, "__label__crime_law": 0.0008087158203125, "__label__education_jobs": 0.1800537109375, "__label__entertainment": 0.0007939338684082031, "__label__fashion_beauty": 0.0006561279296875, "__label__finance_business": 0.06256103515625, "__label__food_dining": 0.0010938644409179688, "__label__games": 0.0083770751953125, "__label__hardware": 0.0024433135986328125, "__label__health": 0.0019197463989257812, "__label__history": 0.0023193359375, "__label__home_hobbies": 0.0006909370422363281, "__label__industrial": 0.0016193389892578125, "__label__literature": 0.0034236907958984375, "__label__politics": 0.0010175704956054688, "__label__religion": 0.0008831024169921875, "__label__science_tech": 0.285888671875, "__label__social_life": 0.0005807876586914062, "__label__software": 0.03924560546875, "__label__software_dev": 0.39697265625, "__label__sports_fitness": 0.0008273124694824219, "__label__transportation": 0.0018444061279296875, "__label__travel": 0.0006361007690429688}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50649, 0.05066]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50649, 0.46412]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50649, 0.93682]], "google_gemma-3-12b-it_contains_pii": [[0, 2344, false], [2344, 9503, null], [9503, 15663, null], [15663, 22710, null], [22710, 29037, null], [29037, 35212, null], [35212, 41236, null], [41236, 45602, null], [45602, 48826, null], [48826, 50649, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2344, true], [2344, 9503, null], [9503, 15663, null], [15663, 22710, null], [22710, 29037, null], [29037, 35212, null], [35212, 41236, null], [41236, 45602, null], [45602, 48826, null], [48826, 50649, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50649, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50649, null]], "pdf_page_numbers": [[0, 2344, 1], [2344, 9503, 2], [9503, 15663, 3], [15663, 22710, 4], [22710, 29037, 5], [29037, 35212, 6], [35212, 41236, 7], [41236, 45602, 8], [45602, 48826, 9], [48826, 50649, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50649, 0.14423]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
7d8bc23c2b9fe14d7b0a29f95c8dea553c153e16
|
This is an author produced version of Subdomain-based test data generation.
White Rose Research Online URL for this paper:
http://eprints.whiterose.ac.uk/113344/
Article:
https://doi.org/10.1016/j.jss.2014.11.033
Subdomain-Based Test Data Generation
Matthew Patrick\textsuperscript{a,b,*}, Rob Alexander\textsuperscript{a}, Manuel Oriol\textsuperscript{a,c}, John A. Clark\textsuperscript{a}
\textsuperscript{a}Department of Computer Science, University of York, Heslington, York, United Kingdom
\textsuperscript{b}Department of Plant Sciences, Downing Street, University of Cambridge, United Kingdom
\textsuperscript{c}ABB Corporate Research, Baden-Dättwil, Switzerland
Abstract
Considerable effort is required to test software thoroughly. Even with automated test data generation tools, it is still necessary to evaluate the output of each test case and identify unexpected results. Manual effort can be reduced by restricting the range of inputs testers need to consider to regions that are more likely to reveal faults, thus reducing the number of test cases overall, and therefore reducing the effort needed to create oracles. This article describes and evaluates search-based techniques, using evolution strategies and subset selection, for identifying regions of the input domain (known as subdomains) such that test cases sampled at random from within these regions can be used efficiently to find faults. The fault finding capability of each subdomain is evaluated using mutation analysis, a technique that is based on faults programmers are likely to make. The resulting subdomains kill more mutants than random testing (up to six times as many in one case) with the same number or fewer test cases. Optimised subdomains can be used as a starting point for program analysis and regression testing. They can easily be comprehended by a human test engineer, so may be used to provide information about the software under test and design further highly efficient test suites.
Keywords: testing, search, input distribution, subdomains, evolution strategy
1. Introduction
Despite a recognition of the importance of software testing by the industry and a significant investment in its practice, many faults are often still not found. For example, the Java Compatibility Kit \cite{1} is an extensive test suite developed for the Java Development Kit (JDK), yet there are still thousands of additional JDK bug reports in Sun’s bug database \cite{2}. The main problem is that software is complex; programs have too many paths to show that they are all correct \cite{3}. As a result, software testing is expensive and it is often performed incompletely.
Automatic test data generation is seen as a solution to some of the challenges involved with software testing \cite{4}. It saves time and money by producing a greater number of test cases more quickly and with less manual involvement. In theory, this should allow a higher standard of testing to be achieved with fewer resources, as it frees testers to focus on the overall strategy rather than individual test case design and implementation.
Yet the quality of the testing process is also dependent upon the model (or oracle) used to determine the expected outcome of each test \cite{5}. Considerable effort is required to construct effective test oracles, even when a domain expert is available \cite{6}. For example, Weyuker \cite{7} suggests that a financial specialist may be able to distinguish whether a company’s assets are closer to $1,000,000 or $1,100,000, but would find it difficult to specify exactly what this value should be.
Existing techniques scatter test cases across the input domain. Many of the values are obscure and it can be difficult to understand their significance [8]. The human tester is not told which values are of particular importance, nor whether other values might also detect the same faults. Testers therefore become separated from the process of generating test cases; their role is reduced to running the testing tool and evaluating its results. Myers [9] claims that testing is performed poorly because testers find it boring and repetitive.
Subdomains are more informative than test cases because their optimal size and placement suggest input regions that are particularly important for testing. Compared to a set of inputs chosen randomly from the whole input domain, less manual effort is required to evaluate test cases whose values are closer together and easier to understand [8]. Subdomains reduce the cost of constructing an oracle because they limit the range of inputs testers must consider and decrease the number of test cases they have to evaluate.
The choice of subdomains has a significant effect on the efficiency of random testing. For example, the TriTyp (also known as Triangle) program has three integer inputs (a, b and c) and its branches contain conditions such as \(a=b=c\). Michael et al. [10] selected over 8000 test cases from the entire input domain, but exercised less than half of the program’s branches. Duran [11] selected 25 test cases from the subdomains ([1,5], [1,5], [1,5]) and exercised all the branches. Random testing can therefore be made more efficient by carefully tuning the subdomains.
Since subdomains require a large number of test cases for their optimisation, other techniques may be computationally more efficient. Yet, we expect subdomain testing will be less labour-intensive because there are ultimately fewer test cases to evaluate. Compared with other testing techniques, subdomains have three main advantages:
1. **They improve the effectiveness of random testing and provide a means to find faults more efficiently**
Subdomains target regions of input mutation analysis predicts likely to reveal faults.
2. **They can be used as a starting point for regression testing more readily than a set of individual test cases**
Subdomains are more robust than test cases to small changes in a program’s values.
3. **They provide information about the execution behaviour of a program that is useful for constructing further tests**
Subdomains suggest important parameters and key threshold for branch conditions.
This article introduces a new technique for optimising subdomains that can be sampled from at random to produce highly efficient test suites. The new technique combines elements of both white-box and black-box testing. Subdomains are optimised through direct manipulation of the source code (mutation analysis), rather than identified by inspection of its specification. Yet optimisation is performed by evolving bounds for each subdomain in the input domain and once the subdomains have been evolved, test cases can be sampled without further analysis of the source code.
It can be difficult to determine which subdomains to use and why. For example, Andrews et al. [12] report that the subdomain [0,31] gave the best results in testing a dictionary, but do not explain how they discovered this ‘magic number’. Rather than using trial and error to find the best subdomains to use with random testing, it is more productive to take a systematic approach. We optimise subdomains using an evolution strategy so that they are efficient at killing mutants.
Evolution strategies have been shown to be efficient at fine-tuning numerical values [13]. They optimise numbers directly, rather than representing them as bit strings and focus on adaptation over recombination [14]. This means that any disruption from recombination is largely avoided. Mutation analysis subsumes various other testing techniques, including MC/DC and statement coverage [15]. It has also been shown to detect more faults than all-uses and prime path coverage on a number of Java programs [16][17]. Finally, experiments with the Siemens test suite and a civil nuclear program suggest mutants are representative of the faults programmers make [18][19].
2. Subdomain Optimisation
We optimise subdomains initially using mutation score (proportion of non-equivalent mutants killed) as our fitness function. A mutant is killed by a test case if it produces a different output to the original program for the same input values. The higher the mutation score the subdomains achieve, the fitter they are considered to be.
A candidate solution consists of one subdomain for each input parameter to the software under test. At every generation, test input values are sampled numerically for each parameter. A candidate solution consists therefore of a set of subdomains with intervals in the following three forms:
**Numerical subdomains**
are represented with lower and upper bounds (rounded to whole numbers to keep the subdomains simple). Values are sampled inclusively within these bounds as real numbers, such that subdomain $[3,6]$ includes values 3 and 6, but also every value in-between.
**Boolean chance values**
are described with an integer value between 0 and 100. Rather than defining a boundary within which test inputs are sampled, this value represents the percentage chance that a particular test input value is ‘true’.
**Character array subdomains**
are fixed in length (by default to five characters). Special characters (wildcard, closure etc.) are identified from the program code and given their own chance of inclusion, whilst characters from the basic Latin alphabet are selected uniformly at random.
Evolution strategies differ from some genetic algorithms in that they optimise numerical values rather than bit strings and focus on mutation over recombination [14]. Evolution strategies optimise numerical values through Gaussian adaptation. Gaussian adaptation is a suitable mechanism for generating new candidate solutions because it favours values close to the old ones, but still allows exploration of values further away.
Our initial experiments were conducted using a traditional (1+1) form of evolution strategy. The evolution strategy maintains one candidate solution (set of subdomains) at a time. Each candidate solution is represented using a numerical set of values $(x_1,\ldots,x_n)$, as determined by the coding of subdomain types described previously.
At every generation, a single new candidate solution $(x'_1,\ldots,x'_n)$ is perturbed from the current one through Gaussian adaptation. It is generated such that $x'_1 = x_1 + \epsilon_1, \ldots, x'_n = x_n + \epsilon_n$, where $\epsilon_1,\ldots,\epsilon_n \sim \mathcal{N}(0,\sigma^2)$. The new candidate replaces the current solution if it evaluates as being superior (i.e. test cases sampled from it achieve a higher mutation score), otherwise it is discarded.
Effort may be wasted in pursuit of locally optimal regions unless the optimisation process balances the development of strong candidates with the exploration of new regions [20]. Rechenberg’s one-fifth rule states the convergence rate is optimal when one out of five new candidates perform better than the previous solution [21]. Following advice from Schwefel [22], the standard deviation of the Gaussian distribution ($\sigma$) is adjusted by applying Equation 1 once every ten generations.
$$
\sigma' = \begin{cases}
\sigma \times 0.85, & \text{if } r < 2 \\
\sigma / 0.85, & \text{if } r > 2 \\
\sigma, & \text{if } r = 2
\end{cases}
$$
(where $r$ is the number of adaptations in every 10 generations that increase the fitness evaluation)
Algorithm 1 describes the process used to optimise lower ($l$) and upper ($u$) boundary values for input parameters ($\alpha,\ldots,\Omega$). The evolution strategy is set up so that it has the ability to explore a wide range of potential candidate solutions quickly, then narrow its focus to exploit those subdomain values found to be the most efficient.
Subdomain values are initially assigned uniformly at random, between 0 and 100 for numerical and Boolean input parameters and within the size of the alphabet for character array parameters. Gaussian adaptation has an initial variance of 50. These initial values were found to be a good starting point for the programs under test. The evolution strategy can, as its search progresses, move outside of these initial boundaries.
Algorithm 1 Synthesising an optimal solution \([\alpha_l, \alpha_u], [\beta_l, \beta_u], \ldots, [\Omega_l, \Omega_u]\)
Input: \(s=\)number of test cases with which to evaluate each candidate solution (we later experiment with 10, 100 and 1000); \(n=\)number of input parameters to the program under test.
1: Select initial random values \((x_1 \ldots x_n)\) for \(\alpha_l, \alpha_u, \beta_l, \beta_u, \ldots, \Omega_l\) and \(\Omega_u\).
2: Generate \(s\) test cases from \([x_1, x_2], [x_3, x_4], \ldots, [x_{n-1}, x_n]\).
3: Count the number of mutants \(m\) killed by the test cases
4: repeat
5: \(r = 0\)
6: for \(i = 1\) to 10 do
7: Sample new values from a normal distribution:
\[x'_1 = x_1 + \epsilon_1, x'_2 = x_2 + \epsilon_2, x'_3 = x_3 + \epsilon_3, x'_4 = x_4 + \epsilon_4, \]
\[\ldots, x'_{n-1} = x_{n-1} + \epsilon_{n-1}, x'_n = x_n + \epsilon_n\]
where \(\epsilon_1 \ldots \epsilon_n \in \mathcal{N}(0, \sigma^2)\)
8: Generate \(s\) test cases randomly within the bounds \([x'_1, x'_2], [x'_3, x'_4], \ldots, [x'_{n-1}, x'_n]\).
9: Count the number of mutants \(m'\) killed by the test cases
10: if \(m' > m\) then
11: \(x_1 = x'_1, x_2 = x'_2, x_4 = x'_4, x_{n-1} = x'_{n-1}, x_n = x'_n, r = r + 1\).
end if
13: end for
14: if \(r < 2\) then \(\sigma^2 = \sigma^2 * 0.85\) (ensures optimal rate for convergence \([22]\))
15: else if \(r > 2\) then \(\sigma^2 = \sigma^2/0.85\)
16: until generations>300 and mutation score no longer increases
3. Optimising Multiple Sets of Subdomains
As well as single sets of subdomains, we also optimise multiple sets, so as to kill specific mutants more precisely. Consider a program with two mutants \((M1\) and \(M2)\) and one input parameter \(x\); \(M1\) can only be killed if \(x = 1\) and \(M2\) can only be killed if \(x = 1000\). The smallest subdomain for \(x\) capable of killing both \(M1\) and \(M2\) is the interval \([1, 1000]\). Widening the subdomain to this interval reduces the efficiency of the sampled test suite so the probability of killing each mutant is 1/1000. It is therefore more efficient to evolve separate subdomains, one for each mutant.
Multiple sets of subdomains are optimised one at a time, in a similar way to single sets, except with a more sophisticated fitness function (see Equation 2) and a new form of evolution strategy (Covariance Matrix Adaptation). Each candidate set is evaluated by sampling test cases from within its bounds. The candidate is saved if it kills mutants a certain number of times out of a fixed number of trials and the search continues to optimise further sets for the remaining mutants.
Covariance Matrix Adaptation Evolution Strategy (CMA-ES) was chosen because it is a population-based technique, so does not get stuck in a local optimum as often as 1+1-ES. CMA-ES adapts the search distribution at the same time as the candidate solutions. It can solve difficult optimisation problems (including non-linear fitness landscapes) without the need for manual parameter tuning. In a recent black-box comparison study with 25 benchmark functions, CMA-ES outperformed other optimisation algorithms in terms of the number of function evaluations before the global optimum value is reached \([23]\).
Subdomains are trained initially against the complete set of mutants; then later they are trained against mutants for which no effective subdomain has yet been found. In this way, some subdomains are produced to target a large number of easy to kill mutants, whilst others are produced to target a small number of difficult to kill mutants. The resulting subdomains complement each other by targeting different groups of mutants. Mutants can therefore be killed efficiently with as few sets of subdomains as possible.
CMA-ES represents the search neighbourhood using a multivariate Gaussian distribution [24]. Compared with the univariate approach, multiple dimensions of variance allow the search to adapt more precisely to the underlying fitness landscape. A covariance matrix is used to represent the shape of the distribution and a scaling factor to represent its size. CMA-ES adjusts the size and shape of the distribution according to pairwise dependencies identified in the covariance matrix [24].
Figure 1 explains how CMA-ES is used to optimise multiple sets of subdomains. In our experiments, candidate solutions are evaluated by sampling 100 test suites of 5 test cases, randomly from within the bounds of each subdomain. A mutant is considered covered if it is killed at least once in 95 out of 100 test suites sampled from the subdomains. Although we found these settings to be effective, alternatives may also be used.
The new fitness function (see Equation 2) favours subdomains that target a distinct group of mutants. It maximises variance in the number of times each mutant is killed and minimises variance in the number of times the same mutant is killed. Each numerator represents the differences within the same mutant and each denominator represents the differences between mutants. By minimising this function, subdomains are selected that consistently kill the same group of mutants.
\[
\sum_{s \in S} \sum_{m \in M} \frac{(K_{s,m} - \bar{K}_m)^2}{(K_m - \bar{K})^2}
\]
\[
\bar{K}_m = \frac{\left(\sum_{s \in S} K_{s,m}\right)}{100}
\]
\[
\bar{K} = \frac{\left(\sum_{m \in M} K_{s,m}\right)}{\#M}
\]
(\(S\) is the set of test suites, \(M\) the set of mutants, \(K_{s,m}\) is the number of times \(s\) kills \(m\), \(K_m\) is the average number of times \(m\) is killed and \(\bar{K}\) is the average number of times any mutant is killed)
Once subdomains are found to cover a particular group of mutants, the search continues to identify and target a new group from among the remaining mutants. If no new mutants have been covered after 50 generations, the program is transformed through a process known as ‘program stretching’ to make individual mutants easier to kill one at a time. The search is terminated if, after the stretching process is completed for each mutant, no new mutants have been covered.
Program stretching was originally suggested as a technique for improving branch coverage [25]. It transforms a program to make difficult search goals easier to achieve, then gradually transforms it back to the original code, retraining the test data at each stage. Program stretching adapts the fitness landscape dynamically so as to guide the search towards achieving a specific goal.
Figure 1: Optimising Multiple Sets of Subdomains
Program stretching is used in this article as a means to kill more mutants. For this to happen, the mutant must be reached, infect a difference in the data state and propagate this difference to the output. The program transformations used in this research were designed to address these goals. Figure 2 summarises the process used to find effective subdomains for difficult to kill mutants by stretching and un-stretching the program code.
The following code transformations are used:
**Path stretching** forces branch conditions leading up to a mutant to be true or false, depending on whether the branch was taken the last time the mutant was killed.
**Mutation stretching** alters the mutation by an offset of 100, for example \( x > y \rightarrow x > y + 100 \) with the aim of increasing its impact on the program.
**Branch condition stretching** adds an offset of 100 to a difficult branch condition in order to make it easier to meet, for example \( x = y \) becomes \( (x < y + 100) \&\&(y < x + 100) \).
Program stretching is performed so that the mutant that has been killed the most number of times is targeted first, then the next most frequently killed and so on. Once stretching is completed, the main fitness function is reapplied to take advantage of the stretching process on other mutants that are killed by similar input values.
4. Subdomain Set Selection
We seek to identify small, but efficient, sets of subdomains from those that have been optimised. Sequential Floating Forward Selection (SFFS) was chosen because it is computationally feasible, but still allows backtracking whenever it improves the selection. Unlike branch-and-bound techniques, SFFS is not guaranteed to find the global optimum, but it is typically much faster at making a selection [26]. SFFS is not restricted to a fixed number of backtracking steps, as with other sub-optimal (plus-l-takeaway-r) techniques. It can make as many sweeps through the feature set as are needed to identify an efficient selection.
Equation 3 describes the fitness criterion used to evaluate subdomain set selections. 100 test cases are sampled randomly from within the bounds of each set to establish its ability to kill each mutant. The current selection is evaluated according to the sum (for each mutant) of the maximum number of times a mutant is killed by any of the included sets. In this way, the criterion function seeks small selections of subdomain sets that kill all the mutants as frequently as possible.
\[
\sum_{m \in M} \max_{s \in S} (killed(s, m)) \tag{3}
\]
\( M \) is the set of mutants, \( S \) is the set of subdomains, \( killed(s, m) \) is the number of times out of 100 that subdomain \( s \) kills mutant \( m \).
Initially, none of the subdomains are selected. Then, one at a time, subdomains are chosen that most improve the criterion evaluation (mutation adequacy). After a subdomain is added, other subdomains are removed as long as the resulting subsets improve the criterion evaluation at that level. Once a selection has been confirmed and backtracking has been completed, the selected subdomains will never be changed. This makes it straightforward to identify the point at which

adding another set of subdomains will not increase the mutation score any further. The technique is therefore suitable for removing redundant sets of subdomains and finding the smallest selection from which test cases can be sampled without having a detrimental effect on fault finding ability.
5. Research Questions
The overall hypothesis of this paper is that software testing can be made more efficient by sampling test cases from efficient sets of subdomains. We consider whether such test cases are more effective at killing mutants and if the subdomains from which they are sampled reveal information that will help the tester to construct an oracle. Finally, we consider whether multiple sets of subdomains and subset selection can be used to improve software testing efficiency even further.
RQ1: Are test suites sampled from an optimised set of subdomains more efficient at killing mutants than unoptimised random testing?
A test suite is considered more efficient if it kills more mutants with the same number of test cases. Mutation analysis is used to determine whether optimised sets of subdomains are more efficient than unoptimised random testing for test suites of 10, 100 and 1000 test cases. If 10 test cases can be sampled such that they kill as many mutants as 100 or 1000 test cases, this can be considered as a ten or hundred-fold improvement in efficiency.
RQ2: To what extent does the relative effectiveness of each set of subdomains (at killing mutants) reveal information about the program under test?
Upper/lower boundaries and chance values clearly have an affect on the effectiveness of sampled test suites. The challenge is to understand how the relative characteristics of subdomains impact their effectiveness, so as to determine the causal relationships between specific subdomain values and the effectiveness of the resulting test suites. Once this is achieved, it should be possible to produce new more efficient subdomains in the future.
RQ3: Are test suites sampled from multiple sets of subdomains more efficient at killing mutants than single sets?
Multiple sets of subdomains can be targeted to kill specific groups of mutants more precisely than a single set of subdomains. Multiple sets are therefore expected to be significantly more efficient at killing mutants than single sets. To find out whether this is the case, mutation analysis is applied to test suites sampled from the subdomains produced by each technique. Multiple sets of subdomains can be considered to be more efficient if they kill more mutants than single sets with the same number of test cases.
RQ4: Does it take longer to optimise multiple sets of subdomains than single sets?
Even if multiple sets of subdomains are more efficient than single sets, it is also important that it does not take much longer to optimise them. Multiple sets are evolved one after the other, so that optimising a large number of sets can be computationally expensive. Yet, it is only necessary to cover one group of mutants at a time, so the stopping criterion for each set is less demanding. This question attempts to discover the trade-off between computation time and efficiency. The efficiency of the evolved subdomains is more important than the time it takes to evolve them, since computation is typically cheaper than human effort, but testers still do not want to wait a long time for the subdomains to be produced.
RQ5: Is it possible to reduce the number of sets of subdomains without significantly impacting their effectiveness?
Sets of subdomains can be removed to further improve fault finding efficiency and reduce human effort, but some mutants that could be killed before may no longer be killed. Sequential Floating Forward Selection (SFFS) is applied to discover how much of the original effectiveness can be retained for various sizes of selection. This will reveal whether it is possible to remove subdomains optimised by the multiple set approach without significantly impacting their effectiveness.
6. Test Subject Programs
We conduct experiments on 10 Java programs (see Table 1) often used in testing research, since they are well known and understood. We chose programs that represent a variety of computation, so that our results are valid for a wide range of applications [31]. The programs are small (35 to 500 lines of code), which means we can repeat our experiments a large number of times.
Power, TrashAndTakeOut and Cal perform numerical calculations. They were published in a textbook on software testing [27]. FourBalls calculates the values of four integers (the weights of balls) relative to each other. It was first used to evaluate evolutionary test data generation [32].
TCAS is an air traffic collision avoidance system. It was first used by Siemens to investigate data flow and control flow coverage criteria [33]. TriTyp (also known as the triangle program) classifies triangles as equilateral, isosceles or scalene. It has been used extensively in research since being introduced by Ramamoorthy et al. [34].
Schedule and Replace process character arrays. Schedule uses an array of instructions with specific command codes, whereas Replace applies a search and replacement string to the source file.
SVD (Singular Value Decomposition) and Schur (Schur Transformation) have a more complex (matrix) input data structure. We evolve numerical subdomains for each diagonal of a four-by-four matrix for SVD and each value of a three-by-three matrix for Schur.
7. Experimental Design
Subdomains are optimised for their ability to kill mutants generated by MuJava [35]. MuJava is based upon research into selective mutation [36][15], which suggests modifying arithmetic, relational, logical and conditional expressions to be the most effective way to mutate program code.
We optimise single sets of subdomains using a 1+1-ES (see Section 2). Subdomain values are initialised randomly between 0 and 100. The adaptation variance is set to 50, then updated using Rechenberg’s one-fifth rule every 10 generations. Although we found this to be effective, other options may also work well. A more sophisticated algorithm could be used, but for illustrative reasons we made our technique as simple as possible.
Multiple sets of subdomains are optimised using a CMA-ES with 95% mutant coverage as its selection criterion (see Section 3). The means and covariances of the multivariate Gaussian distribution are updated automatically by the algorithm. We only sample 5 test cases from each set of subdomains, so as to keep their total number small.
Optimised subdomains are compared to the expected mutation scores for unoptimised random testing (see Equation 4). A test suite of 100 000 random test cases was used because it is important that N is much larger than s for accurate results. Numerical input values were generated between 0 and 100, Boolean values were given a 50% chance of being true and character arrays were generated from the basic Latin alphabet.
Table 1: Test Programs Used in our Experiments
<table>
<thead>
<tr>
<th>Program</th>
<th>Mutants</th>
<th>LOC</th>
<th>Function</th>
<th>Source</th>
</tr>
</thead>
<tbody>
<tr>
<td>Cal</td>
<td>280</td>
<td>134</td>
<td>Counts days between dates</td>
<td>[27]</td>
</tr>
<tr>
<td>FourBalls</td>
<td>189</td>
<td>40</td>
<td>Calculates the ratio of inputs</td>
<td>[28]</td>
</tr>
<tr>
<td>Power</td>
<td>58</td>
<td>35</td>
<td>Calculates the value of ( x^y )</td>
<td>[27]</td>
</tr>
<tr>
<td>Replace</td>
<td>1632</td>
<td>500</td>
<td>Performs substring replacement</td>
<td>[29]</td>
</tr>
<tr>
<td>Schedule</td>
<td>373</td>
<td>200</td>
<td>Determines execution order</td>
<td>[29]</td>
</tr>
<tr>
<td>Schur</td>
<td>2125</td>
<td>497</td>
<td>Matrix transformation</td>
<td>[30]</td>
</tr>
<tr>
<td>SVD</td>
<td>2769</td>
<td>298</td>
<td>Matrix decomposition</td>
<td>[30]</td>
</tr>
<tr>
<td>TCAS</td>
<td>267</td>
<td>120</td>
<td>Processes air traffic control</td>
<td>[29]</td>
</tr>
<tr>
<td>TrashAndTakeOut</td>
<td>111</td>
<td>60</td>
<td>Mathematical calculation</td>
<td>[27]</td>
</tr>
<tr>
<td>TriTyp</td>
<td>310</td>
<td>61</td>
<td>Classifies triangle shapes</td>
<td>[28]</td>
</tr>
</tbody>
</table>
\[ e(s) = \sum_{m \in \text{mutants}} 1 - (1 - K/N)^s \]
(s: expected number of test cases, N: actual number of test cases, K: number of test cases that killed m)
8. Results and Analyses
8.1. Results for RQ1: Are test suites sampled from an optimised set of subdomains more efficient than unoptimised random testing?
RQ1 is answered using a (1+1) evolution strategy to optimise subdomains for test suites of 10, 100 and 1000 test cases. The aim is to determine whether optimised subdomains are more efficient than unoptimised random sampling. Table 2 lists the mutation scores achieved for each size of test suite and Table 3 compares these results for optimised subdomains, the initial random subdomains and unoptimised random testing.
Optimised subdomains achieve a higher mutation score than the initial subdomains for every program and all sizes of test suite. They also exceed the mutation scores for unoptimised random testing with three exceptions (shown in bold). In these cases, all the mutants are expected to be killed by random testing, but the evolution strategy sometimes becomes stuck in a local optimum. Table 4 shows (at a 95% confidence interval) these differences are not significant. By contrast all the other differences are statistically significant.
There is a relationship between the size of a program and the mutation score achieved. Most of the mutants can be killed from the smallest program (Power) with 10 test cases and little optimisation (see Figure 3c), whereas the largest program (Replace) has a low mutation score after 600 generations and 1000 test cases (Figure 3h).
### Table 2: Mutation Scores Achieved by Optimised Subdomain Initial Subdomains and Expected Random Testing
<table>
<thead>
<tr>
<th>Program</th>
<th>Initial Subdomains</th>
<th>Random Subdomains</th>
<th>Optimised Subdomains</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>s=10</td>
<td>s=100</td>
<td>s=1000</td>
</tr>
<tr>
<td>Cal</td>
<td>0.400</td>
<td>0.417</td>
<td>0.421</td>
</tr>
<tr>
<td>FourBalls</td>
<td>0.291</td>
<td>0.299</td>
<td>0.304</td>
</tr>
<tr>
<td>Power</td>
<td>0.947</td>
<td>0.945</td>
<td>0.940</td>
</tr>
<tr>
<td>Replace</td>
<td>0.255</td>
<td>0.332</td>
<td>0.305</td>
</tr>
<tr>
<td>Schedule</td>
<td>0.173</td>
<td>0.823</td>
<td>0.747</td>
</tr>
<tr>
<td>Schur</td>
<td>0.494</td>
<td>0.724</td>
<td>0.749</td>
</tr>
<tr>
<td>SVD</td>
<td>0.115</td>
<td>0.217</td>
<td>0.219</td>
</tr>
<tr>
<td>TCAS</td>
<td>0.083</td>
<td>0.099</td>
<td>0.099</td>
</tr>
<tr>
<td>TrashAndTakeOut</td>
<td>0.669</td>
<td>0.682</td>
<td>0.702</td>
</tr>
<tr>
<td>TriTyp</td>
<td>0.515</td>
<td>0.514</td>
<td>0.498</td>
</tr>
</tbody>
</table>
### Table 3: Difference Between Optimised Subdomains and Random Benchmarks
<table>
<thead>
<tr>
<th>Program</th>
<th>1) Compared to Initial</th>
<th>2) Compared to Random</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>s=10</td>
<td>s=100</td>
</tr>
<tr>
<td>Cal</td>
<td>+125%</td>
<td>+127%</td>
</tr>
<tr>
<td>FourBalls</td>
<td>+191%</td>
<td>+231%</td>
</tr>
<tr>
<td>Power</td>
<td>+5.04%</td>
<td>+5.72%</td>
</tr>
<tr>
<td>Replace</td>
<td>+47.5%</td>
<td>+32.4%</td>
</tr>
<tr>
<td>Schedule</td>
<td>+117%</td>
<td>+2.25%</td>
</tr>
<tr>
<td>Schur</td>
<td>+59.4%</td>
<td>+36.5%</td>
</tr>
<tr>
<td>SVD</td>
<td>+132%</td>
<td>+85.4%</td>
</tr>
<tr>
<td>TCAS</td>
<td>+379%</td>
<td>+377%</td>
</tr>
<tr>
<td>TrashAndTakeOut</td>
<td>+44.7%</td>
<td>+42.2%</td>
</tr>
<tr>
<td>TriTyp</td>
<td>+126%</td>
<td>+82.9%</td>
</tr>
</tbody>
</table>
**Bold font** indicates the optimised subdomains achieved a lower mutation score than random testing.
A program’s size does not always determine how many mutants can be killed. Cal has twice the number of mutants as FourBalls, but 89% were killed by 10 test cases, compared to 83% with FourBalls (see Figures 3a and 3b). TriTyp has one more line than TrashAndTakeOut, but only 64% of its mutants are killed (see Figures 3h and 3g). Using 10 test cases, the mutation score is correlated to the number of mutants and lines of code with -0.690 and -0.667 Spearman’s rank coefficients. The z-scores for these statistics are -23.3 and -22.1, which means we can reject the null hypothesis that there is no correlation.
None of the initial trials with TCAS produced a mutation score above 0.05, the prediction for random testing. Inspection of the code reveals TCAS uses large constants in its branch conditions. For example, unless \textit{Cur\_Vertical\_Sep} is greater than 600, most lines will not be executed. As this value lies far outside the range of the initial subdomains, the probability of this condition being met is low. Widening the initial subdomains improved the mutation score, but only slightly.
A significantly greater improvement in mutation score was made by scaling the program constants so that they lie within the initial subdomains. The program was transformed by dividing eight of its constants by 10, thus bringing them within the 0-100 range used for the initial bounds of each subdomain. When the subdomains were optimised for the transformed program, they achieved an average mutation score of 0.316 with 10 test cases, 0.470 with 100 test cases and 0.471 with 1000 test cases (see Figure 3d, NB: the s=100 line is covered by s=1000 line).
Subdomains discovered on the transformed program can be scaled up for use on the original program by multiplying the relevant values by 10. The subdomains identified by scaling and descaling TCAS achieved an average mutation score of 0.401 for 1000 test cases, with one of the trials achieving 0.625. This is comparable to the 0.643 mutation score achieved by Papadakis et al. [29] with dynamic symbolic execution test generation.
The approach could easily be applied to other programs by manually identifying the relationship between the input parameters and the internal program constants to determine which parameters should be scaled. This could however be time consuming for a human tester who needs to test more complex programs. Our approach for optimising multiple sets of subdomains addresses this problem with automated program stretching.
**Summary for RQ1:** Optimised subdomains achieve a higher mutation score than random testing whenever the mutation score is not already 100%. The size of a program is correlated to how difficult its mutants are to kill. The mutation score for TCAS is increased from 0.05 to 0.401 by scaling (and descaling) its internal constants.
<table>
<thead>
<tr>
<th>Program</th>
<th>1) Compared to Initial</th>
<th>2) Compared to Random</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>s=10</td>
<td>s=100</td>
</tr>
<tr>
<td>Cal</td>
<td>323</td>
<td>45.7</td>
</tr>
<tr>
<td>FourBalls</td>
<td>92.9</td>
<td>13.1</td>
</tr>
<tr>
<td>Power</td>
<td>5.13</td>
<td>0.725</td>
</tr>
<tr>
<td>Replace</td>
<td>23.4</td>
<td>3.31</td>
</tr>
<tr>
<td>Schedule</td>
<td>541</td>
<td>76.5</td>
</tr>
<tr>
<td>Schur</td>
<td>72.0</td>
<td>10.2</td>
</tr>
<tr>
<td>SVD</td>
<td>27.1</td>
<td>3.83</td>
</tr>
<tr>
<td>TCAS</td>
<td>130</td>
<td>18.4</td>
</tr>
<tr>
<td>Trash</td>
<td>49.4</td>
<td>6.99</td>
</tr>
<tr>
<td>TriTyp</td>
<td>34.4</td>
<td>4.86</td>
</tr>
</tbody>
</table>
**Bold font** indicates it is not possible to reject the null hypothesis at the 95% confidence interval.
Table 4: Z-Scores and Cohen’s d Effect Sizes for the Improvements Achieved by Optimised Subdomains
Figure 3: Mutation Scores for Random Test Suites and Evolved Subdomains (Averaged over 100 Trials)
8.2. Results for RQ2: To what extent does the relative effectiveness of each set of subdomains (at killing mutants) reveal information about the program under test?
RQ2 is answered by recording information on the mutation scores achieved by test suites sampled from various sets of subdomains. This information is used by the evolution strategy to discover more efficient subdomains, but it can also be used to reveal useful information about the characteristics of the program under test.
`Power` inputs two integers \((x, y)\), then returns the value of \(x^y\) by applying \(y - 1\) multiplications of \(x\). If the value of \(y\) is less than or equal to zero, `Power` does not enter its multiplication loop, instead returning the value of \(x\). As the majority of mutable statements occur in or around this loop, most of the mutants will not be exercised unless positive values for \(y\) are generated.
Setting the lower boundary of \(y\) to a positive value prevents negative numbers being generated and produces a mutation score around 95% (see Figure 4). Yet, to exercise all the mutants, it is necessary to include at least one negative and one zero value. 100% mutation score is only achieved if the lower boundary of \(y\) is negative.
TCAS has a large number of input parameters, each of which have a different effect on the program. For example, to achieve a high mutation score, the upper boundary of ‘\(\text{Cur Vertical Sep}\)’ must be greater than 60. This corresponds to a (global constant) threshold condition of 600 in the untransformed program code. It is also important to have a high chance for ‘\(\text{High Confidence}\)’ to be true, as much of the code is not executed if it is false (see Figure 5).
It is tempting to think `TriTyp` requires small subdomains close to zero to increase the likelihood of isosceles, equilateral and invalid triangles. In reality, there is little pressure towards the use of smaller subdomains (see Figure 6). It is only necessary for the upper boundary to be large enough to support each type of triangle. This contradicts the findings of Michael et al. [10] and Duran [11].
Subdomain optimisation can be used to predict branch structure. The results of `FourBalls` show four distinct levels of mutation score (see Figure 7). They correspond to four branches in the program code, conditioned upon the value of ‘\(\text{cual}\)’ (1, 2, 3 or other). Figure 7 suggests the ‘\(\text{cual}\)’ subdomain must be small to achieve a high mutation score (values greater than three produce the same result).
Subdomain optimisation is capable of revealing information about the programs under test, but it has at least one significant limitation. If values in the input domain necessary for killing mutants are spaced far apart, the highest mutation score will be achieved when the subdomain includes all these values. Yet, widening the subdomain has a negative effect because the likelihood of sampling these values is reduced. Subdomain optimisation is torn between widening the subdomains to make it possible to kill more mutants, or focussing on an efficient area of the input domain. This issue is discussed further (with regards to optimising multiple sets of subdomains) in the next section.
An illustration of this limitation can be found in the results for Schedule. There are useful areas within the input domain for ‘prio_1’ at around 500 or -500 (see Figure 8). Yet, due to the likelihood of sampling these values from such a large subdomain, many of the evaluations produce low mutation scores. More mutants can be killed with a smaller test suite by evolving multiple sets of subdomains, one for each group of mutants.
Figure 9 provides 3D representations of the percentage of trials that achieve a particular mutation score as the evolution strategy progresses. For each generation on the x-axis, the y-axis plots the mutation scores (binned into 0.1 intervals) achieved by each trial of the evolution strategy and the z-axis plots the number of trials (out of 100) that achieve this mutation score. These graphs provide insight into the process involved in optimising subdomains for each program.
It is immediately apparent from the graphs that there is a distinction between programs for which all the mutants are killed straight away (e.g. Power) and programs for which many of the mutants are difficult to kill (e.g. TCAS). Since high mutation scores are achieved quickly for Power and many of the TCAS mutants are not killed, there are large flat areas in their graphs where there is little or no selection pressure. By contrast, programs reveal the most useful information for testing if their mutants are difficult but still possible to kill, as their subdomains are highly specialised by the end of the optimisation process.
For some programs (e.g. TriTyp) optimisation progresses smoothly from start to finish, whereas for others (e.g. FourBalls) there are peaks or ‘ripples’ in mutation score where optimisation has become stuck in a local optimum. This distinction can also be seen in the scatter plots to a lesser extent. Ripples correspond to branch conditions that are difficult to meet. One way to address this problem is to restart a trial once it has become stuck. Another (less disruptive) way is to modify the fitness landscape so the trial is no longer stuck. Multiple set optimisation transforms the branch conditions to make them easier to meet.
Summary for RQ2: The relationship between subdomain values and the mutation scores they achieve can be characterised through the use of graphs. In particular, 3D plots of the optimisation process can be used to infer the number of branches in a program. Scatter plots of subdomain lower and upper boundaries reveal thresholds that must be met to satisfy particular branch conditions. Scatter plots of subdomain sizes indicate when a narrow range of values is needed to exercise branch conditions efficiently.
8.3. Results for RQ3: Are test suites sampled from multiple sets of subdomains more efficient at killing mutants than single sets?
RQ3 is answered by comparing the effectiveness of multiple optimised sets of subdomains (with program stretching) against single optimised sets of subdomains (without program stretching). The results are presented graphically in Figure 10 and numerically in Table 5. Subdomains use the initial interval [0,100] (50% chance of being true for Booleans). In the interest of fairness, both techniques were evaluated with the same number of test cases (5 for each set of subdomains) and the results are averaged over 100 trials. We do not include Power and TrashAndTakeOut in these results, as their mutants were previously shown to be trivial to kill using a single set of subdomains.
Multiple sets of subdomains achieved 33% higher mutation score on average than single sets and 230% higher than random testing (see Table 5). The difference in mutation score between multiple sets and single sets is small compared to the difference between either technique and random testing. Yet, for all but one program (Schur),
multiple sets achieved a higher mutation score than single sets. For a 95% confidence interval, all of these differences are considered significant. In the case of Schur, single sets and random testing already achieved a high mutation score, so there is little improvement that could be made.
Multiple sets of subdomains were particularly effective at meeting difficult branch conditions. Take for example the TCAS program, which for single sets required manual parameter scaling. The multiple set optimisation technique renders this unnecessary by automatically stretching the program code to make mutants easier to kill.
Multiple sets of subdomains achieved a 71% increase in mutation score on the TCAS program compared to single sets. Multiple set optimisation is particularly effective for difficult branch conditions, because it can assign a set of subdomains for the purposes of meeting each condition.
**Summary for RQ3:** Test suites sampled from multiple sets of subdomains achieved 33% higher mutation scores than single sets on average. Multiple set optimisation stretches programs automatically, without the need for manual parameter scaling. For the TCAS program, this increased the mutation score by an average of 71%.
**8.4. Results for RQ4: Does it take longer to optimise multiple sets than single sets?**
RQ4 is answered by comparing the mutation scores achieved by single and multiple set subdomains throughout their optimisation process. Figure 10 plots the mutation scores as an averaged continuous curve (across 100 trials) against the time it took to evolve them. Least squares logarithmic curve fitting is applied to compare the averaged results at each minute of computation time (between 0 and 2000 minutes). We correct the curve with a cut-off at the average point after which no further mutants were covered.
For half of the programs, it took longer to evolve multiple sets than single sets, whereas for the other half it took less time to evolve multiple sets. The difference in time is typically large, for example it took more than seven times longer to evolve single sets for TCAS than multiple sets. All of the differences can be considered significant at the 95% confidence interval. Yet, on average it took only 11.6% longer to evolve multiple sets of subdomains than single sets (see Table 5).
The variability in time taken to identify subdomains (and reach a point at which there is no more improvement in mutation score) is a result of differences in the rate at which mutants are killed and the time required to execute the program. Typically, most mutants are killed quickly, but it takes a long time to kill the remaining mutants. A long value for time may indicate the program takes a long time to run, the subdomains are difficult to evolve (and as a result a low mutation score is achieved) or a large number of subdomains are evolved (and a high mutation score is achieved).
Multiple sets of subdomains quickly achieve a higher mutation score than single sets on half of the programs (TriTyp, TCAS and SVD). Yet, it still takes longer for SVD to reach its maximum
<table>
<thead>
<tr>
<th>Program</th>
<th>Mutation Score</th>
<th>Time* (mins)</th>
<th>Tests†</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Single‡</td>
<td>Multi‡</td>
<td>Z-score</td>
</tr>
<tr>
<td>Replace</td>
<td>0.520</td>
<td>0.566</td>
<td>13.6</td>
</tr>
<tr>
<td>Schedule</td>
<td>0.850</td>
<td>0.930</td>
<td>19.6</td>
</tr>
<tr>
<td>Schur</td>
<td>0.986</td>
<td>0.920</td>
<td>-11.2</td>
</tr>
<tr>
<td>SVD</td>
<td>0.397</td>
<td>0.632</td>
<td>45.5</td>
</tr>
<tr>
<td>TCAS</td>
<td>0.457</td>
<td>0.780</td>
<td>57.6</td>
</tr>
<tr>
<td>TriTyp</td>
<td>0.951</td>
<td>0.998</td>
<td>8.22</td>
</tr>
</tbody>
</table>
* Time taken to reach point at which optimisation stops i.e. no new sets of subdomains are identified.
† In the multiple set approach, 5 test cases are sampled from each set of subdomains.
‡ The results are averaged over 100 trials.
mutation score with multiple sets compared to single sets (the final value is much higher).
With Schedule and Replace, multiple sets of subdomains perform similarly to single sets at first, but then eventually overtake it. The mutation score for Schedule is lower with multiple sets for the first 13 hours and the first 9 hours for Replace. Multiple sets never achieve as high an average mutation score for Schur, but it takes on average 73 minutes less time.
**Summary for RQ4:** Overall, multiple sets of subdomains do not take much longer to evolve than single sets. On some programs, multiple sets take less time and for others they take more time. For the programs on which multiple sets of subdomains takes longer, the higher mutation scores outweigh the added computational expense.
**8.5. Results for RQ5: Is it possible to reduce the number of sets of subdomains without significantly impacting their effectiveness?**
We also evaluated the effect selecting smaller sets of subdomains (from the optimised sets) has on the mutation score for each program. The theory is that, since multiple sets of subdomains may kill the same mutants, removing some of the sets can improve the fault finding efficiency of the resulting test suites without affecting their effectiveness. Figure 11 and Table 6 present the results of selecting every possible number of sets of subdomains, from a single set all the way up to include every set identified by the optimisation process.
Reducing the number of sets of subdomains improves fault finding efficiency as long as it only has a small effect on the mutation score. The Spearman’s correlation coefficient between selection size and mutation score is significant for all programs at the 95% confidence interval (see Table 6). Yet, it is possible to remove some sets of subdomains with a minimal reduction in mutation score. Removing a quarter of the optimised sets of subdomains only reduced the mutation score by 0.0252 on average. Selecting a quarter of the sets of subdomains of TCAS only reduces the mutation score by 3.6% of that achieved using all the sets.
For both SVD and Schedule, removing sets of subdomains almost immediately decreases the mutation score. These programs only had 8 and 24 sets optimised for them (see Table 5). This limits the opportunity for redundant sets of subdomains and makes it more likely for reducing the number of subdomain sets to have an effect on the mutation score.
Even though there were on average only 9 sets of subdomains (i.e. 45 test cases) evolved for Schur, at least half of these sets can be removed without significantly affecting the mutation score. All the mutants generated for Schur are easy to kill (even by random testing). As a result, the subdomains produced are typically not mutant-specific and can be removed with little impact on mutation score.
It is also of interest that the mutation scores for Schedule decrease and then increase again as sets of subdomains are removed. This is confusing, since removing a set of subdomains cannot increase the criterion evaluation. The reason for this is that the results are averaged over 100 trials and in each trial a different number of subdomains was initially evolved. Similarly, other graphs are not completely smooth because each optimisation run identified a different number of subdomains.
Along with the average mutation score, Figure 11 includes minimum and maximum mutation scores (dotted lines). The minimum mutation score is low for Schur when selecting the first few sets of subdomains, but this changes quickly after the fifth set is added. It is caused by an optimisation run in which no one set of subdomains has a high mutation score by itself. In general, the minimum, maximum and average values are consistently close to each other, suggesting the results of RQ6 can be relied upon.
**Summary for RQ5:** Fewer sets of subdomains can be selected for all but two programs (SVD and Schedule) with minimal decrease in mutation score. The potential for subdomain selection depends on the number of subdomains produced and their specificity for killing certain mutants. This in turn is dependent upon the number of mutants that are generated and how difficult they are to kill.
Figure 10: Percentage of Mutants Covered by Evolved Subdomains during Optimisation (Averaged over 100 Trials)
## Table 6: Mutation Scores for Different Selection Sizes (Averaged over 100 Trials)
<table>
<thead>
<tr>
<th>Program</th>
<th>25%</th>
<th>50%</th>
<th>75%</th>
<th>100%</th>
<th>Spearman’s ρ</th>
<th>Z-score</th>
</tr>
</thead>
<tbody>
<tr>
<td>Replace</td>
<td>0.523</td>
<td>0.542</td>
<td>0.547</td>
<td>0.566</td>
<td>0.979</td>
<td>9.37</td>
</tr>
<tr>
<td>Schedule</td>
<td>0.686</td>
<td>0.862</td>
<td>0.828</td>
<td>0.930</td>
<td>0.876</td>
<td>8.38</td>
</tr>
<tr>
<td>Schur</td>
<td>0.883</td>
<td>0.920</td>
<td>0.921</td>
<td>0.920</td>
<td>0.774</td>
<td>7.40</td>
</tr>
<tr>
<td>SVD</td>
<td>0.460</td>
<td>0.531</td>
<td>0.579</td>
<td>0.603</td>
<td>0.977</td>
<td>9.35</td>
</tr>
<tr>
<td>TCAS</td>
<td>0.752</td>
<td>0.778</td>
<td>0.779</td>
<td>0.780</td>
<td>0.811</td>
<td>7.76</td>
</tr>
<tr>
<td>TriTyp</td>
<td>0.946</td>
<td>0.988</td>
<td>0.994</td>
<td>0.998</td>
<td>0.871</td>
<td>8.33</td>
</tr>
</tbody>
</table>
Figure 11: Percentage of Mutants Covered by Evolved Subdomains during Subset Selection (Averaged over 100 Trials) (Dotted lines represent the minimum and maximum mutation scores; solid lines represent the mean.)
9. Threats to Validity
Although optimised subdomains are efficient at killing mutants, subdomain optimisation is computationally expensive. Further experiments are required to determine whether the total number of evaluations is less than with random testing. The goal of this research is not just to kill mutants, but to identify subdomains that can be understood by the tester. Yet, work is still needed to make our techniques more efficient for use in industry.
The experiments in this paper were performed on 10 relatively small programs, ranging from 40 up to 500 lines of code. Further research is required to determine whether the techniques we describe are effective for larger programs. It might not be as clear why subdomains evolved for more complex programs are effective at killing mutants, so it may be difficult to achieve results similar to those presented in Section 8.2. It is necessary to consider how subdomains can be optimised for non-procedural (object-oriented) programs.
If test cases are only sampled from within the optimised subdomains, it is possible to miss mutants that for which subdomains have not been evolved because they are difficult to kill. We have addressed this by evolving multiple sets of subdomains for different groups of mutants. Yet, it may be helpful to include some test cases sampled from outside the subdomains. One solution is to optimise input distributions that cover the entire input domain rather than subdomains which just cover certain key areas. Yet it is likely this would require more computational resources and there is a question as to whether these distributions would be as straightforward for testers to understand.
Program stretching makes difficult to kill mutants easier to kill by widening branch conditions for paths along which that mutant was previously killed. The problem with this technique is that it requires the mutant to have been killed at least once before it can be used. Difficult to kill mutants are (by their nature) less likely to be killed during optimisation. It may be helpful to stretch paths along which a mutant has been reached (or partially reached) and use static analysis to predict paths for which a mutant is likely to be killed.
10. Related Work
There are three main types of technique that improve fault finding and reduce human effort:
**Improved random testing** reduces the number of test cases needed to find faults by sampling them from a non-standard distribution.
**Structural test data generation** uses the underlying program structure as an aid to efficiently target test cases at specific goals.
**Test case selection** removes some of the test cases once they have been produced, according to some evaluation of their usefulness.
The efficiency of random testing can be improved by distributing test cases evenly, so that they cover the input domain more quickly. For example, Adaptive Random Testing (ART) has been shown to halve the number of test cases needed to find the first failure for some programs [37]. As ART does not take the specific behaviour of a program into account, there is a limit to the improvements it can make [38]. The added expense can sometimes outweigh the benefits [39].
Hamlet [40] recommends partitioning the input domain into contiguous regions for which the program behaves the same. If the partitions are homogeneous, we only need to sample one test case from each one. This is typically approximated using structural or functional coverage criteria and sampling a few values from each partition. Hamlet [40] claims emphasis should be placed on failures that are likely to occur more often. This can be achieved by sampling more test cases from certain partitions according to a usage profile.
Poulding and Clark [41] aim to give equal emphasis to each part of a program by modelling the dependencies between parameters with a Bayesian network. They adjust the width of a series of bins, so as to maximise the least covered program branch. By contrast, Andrews et al. [42] optimise a single subdomain for each scalar type using a genetic algorithm to maximise statement coverage. We also optimise subdomains (rather than partitions) to improve code coverage, but for each input parameter instead of each data type.
Structural test data generation techniques typically involve dynamic symbolic execution and/or automated search. Dynamic symbolic execution solves branch conditions leading to a goal as a series of constraints [29][43]. Search based software testing optimises branch conditions as a series of fitness criteria [44]. In this paper, we have chosen to take a search-based approach because this allows us to target mutants without having to specify in advance which particular path to follow.
A wide variety of search-based optimisation techniques have been used to target structural components for test data generation. These include (amongst others): genetic algorithms [42], genetic programming [45], simulated annealing [46], tabu search [47], scatter search [48], bacteriological algorithms [49] and artificial immune systems [50]. We use evolution strategies (1+1-ES and CMA-ES) because they are conceptually straightforward and have been shown to be highly effective at fine tuning numerical values.
One way to target structural goals is with the approximation level criterion [51], which indicates the distance from the current path to a path that contains the goal. The first statement in the program has zero approximation level. Every time a critical branch is encountered that if taken, would prevent the goal from being reached, the approximation level is incremented. This means statements with the highest approximation level are closest to the goal. In addition to targeting the execution of goals, mutation analysis requires each mutation to have an effect on the output.
In some cases it is possible to represent infectivity as an additional branch condition [29]. Yet, to propagate the effect of the mutant to the output, heuristics are applied. Some researchers attempt to predict which paths are more likely to reveal a difference [29][43]. Another option is to search for input values that maximise mutation impact [44]. Our approach does not consider this issue directly (additional criteria could be added later). Our aim is to find subdomains that consistently achieve a high mutation score. Therefore, we search for efficient subdomain values by causing the execution to follow a path along which a mutant has already been killed at least once.
Selection techniques are used to improve test efficiency by removing all but the most useful test cases [52]. Test cases can be selected that cover infrequently met test criteria [53], meet the most number of unmet criteria [54] or consistently contribute to the overall evaluation [55]. Test selection criteria are typically deterministic, since test cases produce the same result each time they are executed. In contrast, our approach to subdomain set selection uses non-deterministic criteria. This is because test cases are sampled probabilistically from within the bounds of each subdomain.
Test selection methods are often based on the greedy algorithm [52]. They add test cases one at a time, selecting at each step the test case that most improves the criteria evaluation. The problem is that criteria met by earlier test cases are also often met by a combination of test cases selected later in the process, thus making some of the earlier test cases redundant. Our selection technique applies backtracking as often as it helps the evaluation. We also select test cases on the basis of multiple evaluations to avoid over-fitting.
In contrast with the related work by other researchers, we optimise continuous subdomains rather than individual test cases, as evaluated by mutation rather than structural coverage. Our subdomains can be sampled again and again to produce small but efficient test suites that achieve a high mutation score.
11. Conclusions
The main aim of this research was to make software testing more efficient by introducing new techniques for identifying and evaluating efficient sets of input subdomains for test data generation. This was achieved through a combination of random testing, mutation analysis, evolutionary optimisation and subset selection. Restricting the range of inputs helps to decrease the manual effort involved in software testing because it reduces the number of situations for which testers need to consider the behaviour of the program under test. We showed that subdomains can be used to reduce the number of test cases that are evaluated, whilst still maintaining a high mutation score.
Our single set optimisation technique increased the mutation score of each test suite compared to the expected result for random testing by an average of 80.1% for test suites of 1000 test cases. Even greater improvements were made when using 10 or 100 test cases. The average increase in mutation score for test suites of 10 test cases was 98.5%. This shows that subdomain selection is able to make testing more effective, whilst still reducing the number of test cases that are used.
On the other hand, single sets of subdomains required the input parameters of TCAS to be manually scaled before optimisation can be effective. This is not trivial, since an understanding of the program code is necessary to determine which parameters to scale. Our technique for optimising multiple sets of subdomains stretches the program code automatically, without the need to inspect its constants. In addition, each set of subdomains is targeted at a different group of mutants, allowing mutants to be killed more efficiently.
Sampling test cases from multiple sets of optimised subdomains achieved on average 33% higher mutation score than single sets and 230% higher than unoptimised random testing. Multiple sets of subdomains were on average only slightly more computationally expensive to evolve than single sets. They took less time for some programs and more time for others. Multiple sets of subdomains were particularly effective at evolving subdomains for TCAS. On average they achieved 71% higher mutation score than single sets and took 1/7th of the time to evolve.
The subdomains identified by our optimisation techniques can serve as a starting point for regression testing. They highlight specific regions in the input domain that are effective at indicating when the behaviour of the program has changed. This is particularly helpful when those changes are unintended, but when the difference is intentional, the evolution strategy should be able to adapt the current set of subdomains more quickly than if it had started from an earlier state. The specialisations achieved by multiple sets of subdomains allow the tester to track the effect that changes have on the behaviour of the program with regard to its requirements for testing.
The subdomains identified by our technique reveal information about the program under test. For example, to achieve a high mutation score with TCAS, test input values must be used for ‘Cur_Vertical_Sep’ that are greater than 600. This information can be used to produce new more efficient test suites in the future. In this way, subdomains can be seen as an effective tool to support testing. Subdomain optimisation is computationally expensive compared to random testing at first. Yet once efficient subdomains have been identified, the cost of sampling new test cases is insignificant and the ability of the new test cases to find faults is substantially increased.
Subdomain selection can be performed, once optimisation is complete, to significantly improve the efficiency of the resulting test suites. Subdomain selection reduced the number of subdomains for four out of six programs with little effect on mutation score. Subdomain selection is successful as long as there is some overlap in the mutants each subdomain kills. This was not the case for SVD because its mutants were too easy to kill or Schedule because too few subdomains were evolved for it. Subdomain selection is computationally inexpensive compared to subdomain optimisation and acts as a useful tool, providing significant improvement for certain programs.
12. Future Work
Three main continuations are envisaged:
1. Applying the experiments in this paper to larger more complex software
2. Deriving efficient subdomains from the results of previous test results
3. Optimising test input distributions to cover the entire input domain
The largest program used in our experiments (Replace) only has 500 lines of code. There is no reason in principle why our techniques could not be applied to larger programs. The biggest challenge we face in demonstrating this is the time it takes to run each experiment. It took an average of 23.5 hours to optimise multiple sets of subdomains for Replace. We need to reduce this time if our techniques are to be used in industry.
Subdomain optimisation is computationally expensive and much effort is spent generating test cases that are immediately discarded in favour of the resulting subdomains. However, there is no reason why subdomains could not be optimised at the same time as the software is being tested.
Rather than generating test cases explicitly for the purposes of subdomain optimisation, subdomains may be derived from the results of other test data generation tools. An advantage of this is that it is no longer necessary for our subdomain optimisation tool to generate effective test data. A disadvantage is that the test data available from other tools may not provide the most useful information for characterising the input domain.
Another limitation of subdomain optimisation is that it is necessary to sample outside the evolved subdomains to test software thoroughly. Our approach provides little information about when to do this or which values are most likely to be useful. One solution is to optimise input distributions that cover the entire input domain rather than subdomains which just cover certain key areas. Techniques to achieve this may be borrowed from the field of structural statistical testing [41].
This extension of our technique would allow each test case evaluation to have a more direct impact on the shape of the input distribution than is possible by using a CMA-ES to evolve sets of subdomains. Statistical testing is more expressive than subdomain testing and can take into account more of the information gained by test case evaluation. One downside is that more computational resources may be required to optimise a distribution for the entire input domain. Another important question is whether a (potentially non-smooth) input distribution is as straightforward for test engineers to conceptualise and apply.
References
[23] N. Hansen, A. Auger, R. Ros, S. Finck, P. Posik,
|
{"Source-Url": "http://eprints.whiterose.ac.uk/113344/1/Subdomain_Testing_accepted_manuscript.pdf", "len_cl100k_base": 15691, "olmocr-version": "0.1.53", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 71598, "total-output-tokens": 21337, "length": "2e13", "weborganizer": {"__label__adult": 0.0003256797790527344, "__label__art_design": 0.00032901763916015625, "__label__crime_law": 0.00023984909057617188, "__label__education_jobs": 0.00115203857421875, "__label__entertainment": 6.103515625e-05, "__label__fashion_beauty": 0.00016057491302490234, "__label__finance_business": 0.00022709369659423828, "__label__food_dining": 0.00024819374084472656, "__label__games": 0.0006999969482421875, "__label__hardware": 0.0007371902465820312, "__label__health": 0.00031256675720214844, "__label__history": 0.000244140625, "__label__home_hobbies": 9.22083854675293e-05, "__label__industrial": 0.000274658203125, "__label__literature": 0.0002949237823486328, "__label__politics": 0.0001780986785888672, "__label__religion": 0.00035500526428222656, "__label__science_tech": 0.01309967041015625, "__label__social_life": 8.52346420288086e-05, "__label__software": 0.00614166259765625, "__label__software_dev": 0.9736328125, "__label__sports_fitness": 0.0002999305725097656, "__label__transportation": 0.00042557716369628906, "__label__travel": 0.00017845630645751953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 77934, 0.07159]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 77934, 0.50233]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 77934, 0.89162]], "google_gemma-3-12b-it_contains_pii": [[0, 423, false], [423, 3814, null], [3814, 8116, null], [8116, 12356, null], [12356, 16094, null], [16094, 18850, null], [18850, 22108, null], [22108, 26128, null], [26128, 30122, null], [30122, 34408, null], [34408, 38700, null], [38700, 38799, null], [38799, 41362, null], [41362, 44750, null], [44750, 45896, null], [45896, 49890, null], [49890, 54141, null], [54141, 54251, null], [54251, 55017, null], [55017, 59291, null], [59291, 63709, null], [63709, 68000, null], [68000, 72696, null], [72696, 77934, null]], "google_gemma-3-12b-it_is_public_document": [[0, 423, true], [423, 3814, null], [3814, 8116, null], [8116, 12356, null], [12356, 16094, null], [16094, 18850, null], [18850, 22108, null], [22108, 26128, null], [26128, 30122, null], [30122, 34408, null], [34408, 38700, null], [38700, 38799, null], [38799, 41362, null], [41362, 44750, null], [44750, 45896, null], [45896, 49890, null], [49890, 54141, null], [54141, 54251, null], [54251, 55017, null], [55017, 59291, null], [59291, 63709, null], [63709, 68000, null], [68000, 72696, null], [72696, 77934, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 77934, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 77934, null]], "pdf_page_numbers": [[0, 423, 1], [423, 3814, 2], [3814, 8116, 3], [8116, 12356, 4], [12356, 16094, 5], [16094, 18850, 6], [18850, 22108, 7], [22108, 26128, 8], [26128, 30122, 9], [30122, 34408, 10], [34408, 38700, 11], [38700, 38799, 12], [38799, 41362, 13], [41362, 44750, 14], [44750, 45896, 15], [45896, 49890, 16], [49890, 54141, 17], [54141, 54251, 18], [54251, 55017, 19], [55017, 59291, 20], [59291, 63709, 21], [63709, 68000, 22], [68000, 72696, 23], [72696, 77934, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 77934, 0.18942]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
e4579c6c8a1a0dae3169543fa7e7cd386c925a7d
|
Alignment and distribution is NOT (always) NP-hard.
Vincent Boudet, Fabrice Rastello, Yves Robert
To cite this version:
HAL Id: hal-02101994
https://hal-lara.archives-ouvertes.fr/hal-02101994
Submitted on 17 Apr 2019
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Alignment and distribution is NOT (always) NP-hard
Vincent BOUDET
Fabrice RASTELLO
Yves ROBERT
Juillet 1998
Research Report N° 98-30
Abstract
In this paper, an efficient algorithm to simultaneously implement array alignment and data/computation distribution is introduced and evaluated. We re-visit previous work of Li and Chen [13, 14], and we show that their alignment step should not be conducted without preserving the potential parallelism. In other words, the optimal alignment may well sequentialize computations, whatever the distribution afterwards. We provide an efficient algorithm that handles alignment and data/computation distribution simultaneously. The good news is that several important instances of the whole alignment/distribution problem have polynomial complexity, while alignment itself is NP-complete [13].
Keywords: compilation techniques, parallel loops, alignment, distribution, “the owner computes” rule.
Résumé
Dans ce rapport, un algorithme efficace est présenté et évalué pour résoudre simultanément l’alignement des tableaux et la distribution des données et des calculs. Nous revisons les travaux précédents de Li et Chen [13, 14], et nous montrons que leur recherche d’un alignement ne doit pas être conduite sans préserver le parallélisme potentiel. En d’autres termes, l’alignement optimal peut séquentialiser les calculs quelle que soit la distribution choisie ensuite. Nous présentons un algorithme efficace qui tient compte simultanément de l’alignement et de la distribution des données et des calculs. La bonne nouvelle est que plusieurs instances du problème d’alignement/distribution ont une complexité polynomiale alors que l’alignement lui-même est NP-complet [13].
Mots-clés: techniques de compilation, boucles parallèles, alignement, distribution, règle du “the owner computes”.
Alignment and distribution is NOT (always) NP-hard
Vincent Boudet, Fabrice Rastello and Yves Robert
LIP, URA CNRS 1398
Ecole Normale Supérieure de Lyon, 69364 Lyon Cedex 07, France
e-mail: [Vincent.Boudet, Fabrice.Rastello, Yves.Robert]@ens-lyon.fr
Abstract
In this paper, an efficient algorithm to simultaneously implement array alignment and data/computation distribution is introduced and evaluated. We re-visit previous work of Li and Chen [13, 14], and we show that their alignment step should not be conducted without preserving the potential parallelism. In other words, the optimal alignment may well sequentialize computations, whatever the distribution afterwards. We provide an efficient algorithm that handles alignment and data/computation distribution simultaneously. The good news is that several important instances of the whole alignment/distribution problem have polynomial complexity, while alignment itself is NP-complete [13].
Key words: compilation techniques, parallel loops, alignment, distribution, “the owner computes” rule.
Corresponding author: Yves Robert
LIP, Ecole Normale Supérieure de Lyon, 69364 Lyon Cedex 07, France
Phone: + 33 4 72 72 80 37, Fax: + 33 4 72 72 80 80
E-mail: Yves.Robert@ens-lyon.fr
*This work was supported by the CNRS-ENS Lyon-INRIA project ReMaP and by the Eureka Project EuroTOPS.
1 Introduction
Compile-time techniques for mapping arrays and computations onto distributed memory machines have focused a large research effort recently, as illustrated by the survey paper of Ayguadé, Garcia and Kremer [5]. Several methods and tools have been presented since the reference paper of Li and Chen [13, 14], who have studied the problem of aligning arrays so as to minimize communications. Because Li and Chen have shown the alignment problem to be NP-complete (in the number of data arrays and statements within the loop nest), heuristics or costly (exponential) algorithms, such as Integer Linear Programming, have been introduced. We briefly survey the related literature in Section 2.
In this paper we re-visit previous work of Li and Chen [13, 14], and we show that their alignment step should not be conducted without preserving the potential parallelism. In other words, the optimal alignment may well sequentialize computations, whatever the distribution afterwards. We provide an efficient algorithm that handles alignment and data/computation distribution simultaneously. The good news is that several important instances of the whole alignment-distribution problem have polynomial complexity, while alignment itself is NP-complete [13].
We take as input a loop nest, possibly non perfect, where parallelism has been made explicit, e.g., after applying the Allen and Kennedy parallelization algorithm [2]. We construct a new graph, the alignment-distribution graph, which replaces Li and Chen’s component affinity graph. Using this graph, we are able to determine which parallel loop(s) and which array dimension(s) should be distributed to the processors so as to preserve parallelism while minimizing communications. Our alignment-distribution graph is weighted, and the weights represent estimates of the communication costs: it is a very flexible approach, and we are able to take advantage of recent results on modeling such communication costs accurately [7, 4, 3, 11]. Because the choice of the distributed loops provides kind of a “reference” pattern, the alignment step is conducted according to this choice, and the complexity to finding the optimal solution reduces to a fast (polynomial) path algorithm on the alignment-distribution graph. This is a very nice result for the practical applicability of our approach (again, previous techniques aimed at solving a NP-complete problem).
The paper is organized as follows: we start with a motivating example in Section 2. We use the example to summarize the approach of Li and Chen [13, 14] and to point out its limitations. We briefly review the existing literature in Section 3. We describe our new algorithm, and we state complexity results, in Section 4. We give some final remarks in Section 5.
2 Motivation
We use a simple example to explain why aligning arrays and distributing parallel loops should be dealt with simultaneously.
Example 1
\[
\begin{align*}
\text{for } i = 2 \text{ to } n \text{ do} \\
\quad \text{for } / / j = i + 1 \text{ to } n \text{ do} \\
\qquad S_1: a(i, j) = b(i, j) + a(i - 1, j) \\
\qquad S_2: b(j, i) = a(j, j) + 1
\end{align*}
\]
To check that the second loop on \( j \) is indeed parallel, we can use a dependence analysis tool like Tiny [18]. Using such a tool, we check that there is only one flow dependence of level 1 from \( S_1 \) to itself, which is due to \( a \). The reduced dependence graph for Example 1 is depicted in Figure 1.
\[
\text{Figure 1: The reduced dependence graph (using dependence levels) for Example 1.}
\]
First we review Li and Chen's approach [13, 14] through Example 1. Then we explain why their technique may kill the potential parallelism.
### 2.1 Li and Chen's component affinity graph
We represent in Figure 2 the component affinity graph (CAG) that Li and Chen [14, 13] would derive for Example 1. We informally explain how the CAG is built using the example. The CAG contains 2 columns of 2 nodes, because there are 2 arrays \( a \) and \( b \) (hence 2 columns) of dimension 2 each (hence two nodes in each column). Node \( a_1 \) represents the first dimension of array \( a \), and so on. There is an edge between two nodes, i.e., between two dimensions of different arrays, if, roughly speaking, the subscripts of these dimensions are the same up to a translation by a constant, and if these arrays appear on both sides of the same assignment. The CAG is undirected. Self references are not taken into account. In our example, there is an edge between nodes \( a_1 \) and \( b_1 \) because of statement \( S_1 \): the same subscript \( i \) appears in the first dimension of \( a \) and \( b \). In general, when the same subscript, up to a translation by a constant, appears in dimension \( i_x \) of array \( x \) and in dimension \( i_y \) of array \( y \), these two dimensions are said to have an affinity relationship, and we draw an edge between the corresponding nodes. Similarly, due to \( S_1 \) again, there is an edge between \( b_2 \) and \( a_2 \). Because self references are not taken into account, the occurrence of \( a(i - 1, j) \) in the right hand side has no impact on the graph. The intuitive idea is that edges imply an alignment preference between the corresponding arrays. The term alignment may well be understood here as an HPF ALIGN directive [10] onto a virtual template. Aligning arrays according to the edges will reduce, or even suppress (as in statement \( S_1 \)), the possible communications induced by the distribution of the arrays onto parallel processors.
Statement \( S_2 \) introduces some complication, because the same index \( j \) appears in the first dimension of \( a \) on the left hand side, and in both dimensions of \( b \) on the right hand side. The two edges \((a_1, b_1)\) and \((a_1, b_2)\) are said to be competing.
The CAG is weighted: edges are valued according to the strength of preference. A competing edge has weight \( \varepsilon \), a value much smaller than 1. The weight of an edge between nodes indexed by a spatial variable (a subscript of a parallel loop, like \( j \) in Example 1) is 1. Finally, the weight of an edge between nodes indexed by a temporal variable (a subscript of a sequential loop, like \( i \) in Example 1) is \( \infty \). We are led to the graph of Figure 2. If there are several edges between two nodes, we only keep one, whose weight is the sum of all edge weights between the two nodes.
Li and Chen [14, 13] state the alignment problem as follows: partition the nodes of all columns into disjoint subsets that represent aligned dimensions. The rule of the game is that no two nodes
of the same column are in the same subset. The objective is to minimize the sum of the edge weights between subsets. Unfortunately, the problem is NP-complete in the size of the CAG (Li and Chen use a reduction from MAX-CUT [6]). To compute a satisfactory alignment, Li and Chen use a greedy heuristic based upon bipartite matching [14]. For Example 1, their heuristic leads to the optimal (minimal-weight) solution, namely aligning $a_1$ with $b_1$ and $a_2$ with $b_2$. In other words arrays $a$ and $b$ are directly superimposed onto the same template.
### 2.2 Distributing parallel loops
The previous alignment, however, causes all the potential parallelism to be lost when it comes to distributing array elements onto processors! To see why, consider the following two possible data distributions:
**Distributing the first dimension** This means that rows of arrays $a$ and $b$ are distributed to processors: elements $a(i, j)$ and $b(i, j)$, for $1 \leq j \leq n$, are stored in (virtual) processor $P_i$. This causes statement $S_1$ to be executed sequentially: given a value of the first loop index $i$, all iterations of the second loop index $j$ are computed by the same processor $P_i$.
**Distributing the second dimension** Quite similarly, distributing columns of $a$ and $b$ to processors will lead statement $S_2$ to be executed sequentially.
To summarize, the best alignment, as computed by Li and Chen, turns out to kill the parallelism. We claim that the alignment step should be conducted while having parallelism in mind: distributing parallel loops to processors is the true priority. A good alignment can reduce or suppress communications, but what if it leads to gather all parallel computations onto the same processor, as in our example?
We informally explain our approach using Example 1. See Section 4 for a complete description of our algorithm. Assume we target a one-dimensional processor grid. The highest priority is to distribute parallel computations, i.e., instances of the parallel loop $j$, on processors. In the example there is not much freedom: we distribute columns of $a$ and rows of $b$ to processors: processor $P_j$ receives $a(i, j)$ and $b(j, i)$ for all $1 \leq i \leq n$. Owing to this distribution, for each instance of the external loop $i$, we distribute the parallel computations of loop $j$ to processors. There remains some communications: for each instance $i$ of the external loop, because of statement $S_1$, the $i$-th
row of \( b \) must be scattered from processor \( P_i \) to all processors. But parallelism has been preserved. Our approach does lead to this solution, based upon an alignment-distribution graph that privileges parallel loops. The alignment-distribution graph for Example 1 is represented in Figure 3. It is built as follows: there are 4 array dimension nodes, one per array and per dimension, as in Li and Chen’s CAG, plus an additional loop node for the parallel \( j \) loop. There is an edge between the loop node and an array dimension node if distributing both of them onto the processors induces communications. Edge weight correspond to (estimated) communication costs. In Figure 3, \( Ga \) stands for Gather, and \( Sc \) for Scatter.
Figure 3: The alignment-distribution graph for Example 1.
The detailed construction of the graph as well as our solution to the problem are described in Section 4. We conclude our study of Example 1 with a few important remarks:
**Remark 1:** “the owner-computes” rule. There is no major reason to obey “the owner-computes” rule. The true objective is to distribute the parallel computations \( S_1(i, j) \) and \( S_2(i, j) \) to processor \( P_j \), for \( 1 \leq i \leq n \). To this purpose, we might distribute columns of \( a \) and \( b \) to processors, which corresponds to Li and Chen’s alignment. But we would insist that \( S_2(i, j) \) is executed by processor \( P_j \), at the price of a communication after the computation, to store the written value \( b(j, i) \) into the memory of processor \( P_i \). For each value of \( i \), statement \( S_2 \) would then induce a gather operation (\( P_j \) owns \( a(j, j) \), writes into \( b(j, i) \) and sends it to \( P_i \)).
**Remark 2:** computations versus communications. Example 1 is a toy example and should be considered as such. In this example, our solution may not be significantly better than a solution that sequentializes the parallel loop, because of the cost of the communications. Still, we can easily modify the example! Also, we can take benefit of the many papers in the literature to derive the best physical distribution, i.e. deciding whether rows of \( a \) and columns of \( b \) will be distributed in a pure cyclic, pure block or block-cyclic fashion over \( p \) physical processors, where \( p \) is likely to be much smaller than \( n \), the array size. In fact, our approach is quite flexible and can benefit from any precise modeling of the computation and communication costs: our alignment-distribution graph is vertex-weighted and edge-weighted, and the more precise the weights, the more accurate the solution. See the literature survey in Section 3.
**Remark 3:** loop parallelization algorithms and redistribution. An experienced programmer may have decided to apply loop distribution [19, p. 323] on Example 1 before considering alignment and distribution. Such a transformation is perfectly legal and leads to the following loop nest:
\[
N*Ga(N/P)+N*Sc(N/P) \\
N*Sc(N/P) \\
N*Br(N) \\
\]
\[ \begin{align*}
a1 & \quad b1 \\
\quad j & \\
a2 & \quad b2 \\
\end{align*} \]
\[ \begin{align*}
N*Ga(N/P)+N*Sc(N/P) \\
N*Sc(N/P) \\
N*Br(N) \\
\end{align*} \]
---
\[ \text{Figure 3: The alignment-distribution graph for Example 1.} \]
---
\[ \begin{align*}
N*Ga(N/P)+N*Sc(N/P) \\
N*Sc(N/P) \\
N*Br(N) \\
\end{align*} \]
\[ \begin{align*}
a1 & \quad b1 \\
\quad j & \\
a2 & \quad b2 \\
\end{align*} \]
---
\[ \text{Figure 3: The alignment-distribution graph for Example 1.} \]
---
\[ \begin{align*}
N*Ga(N/P)+N*Sc(N/P) \\
N*Sc(N/P) \\
N*Br(N) \\
\end{align*} \]
\[ \begin{align*}
a1 & \quad b1 \\
\quad j & \\
a2 & \quad b2 \\
\end{align*} \]
Distributing loops
for $i = 2$ to $n$ do
for // $j = i + 1$ to $n$ do
$S_1$: $a(i, j) = b(i, j) + a(i - 1, j)$
end for //
end for
for // $i = 2$ to $n$ do
for // $j = i + 1$ to $n$ do
$S_2$: $b(j, i) = a(j, j) + 1$
end for //
end for
We could then perform the alignment step separately on the two nests, and eventually redistribute some data array (say $b$) in between. If the modified loop nest (having distributed the loop) is given as input to our alignment-distribution graph, and if the redistribution of one array (say $b$) is optimal, our algorithm will find it. But given the original loop nest of Example 1, we do not deal with ANY loop transformation.
Consider the following modification of Example 1:
Example 2
for $i = 2$ to $n$ do
for // $j = i + 1$ to $n$ do
for $k = 2$ to $n$ do
$S_1$: $a(i, j, k) = b(i, j, k) + b(i + 1, i, k - 1) + a(i - 1, j, k)$
$S_2$: $b(j, i, k) = a(j, j, k) + a(i, i + 1, k)$
end for
end for //
end for
The reduced dependence graph is shown in Figure 4: loop distribution is no longer valid. We represent Li and Chen’s CAG in Figure 5: solid arrows correspond to statement $S_1$, and dashed arrows to $S_2$. Again, the optimal solution for the CAG is to superimpose arrays $a$ and $b$, i.e., align each dimension of $a$ with the same dimension of $b$. Again, this would lead to a sequential execution, whatever the distribution chosen. However, as before, our alignment-distribution graph, represented in Figure 6, gives priority to the parallel loop $j$ and distribute the first dimension of $a$ and the second dimension of $b$ to processors.
To summarize, our approach starts from a “parallelized” loop nest, i.e., a loop nest for which dependence analysis and loop parallelization have already been carried out. The most popular tools for these two steps are dependence levels [1, 2] and the Allen-Kennedy algorithm [2]. Given a parallelized loop nest, we determine which parallel loops should be distributed to processors, and the best alignment and distribution of arrays to minimize communications. This is done through the alignment-distribution graph.
Our main contribution is for a single loop nest, possibly non perfectly nested. When there are several consecutive loop nests, or an iterative loop surrounding several loop nests, we use the approach of Lee [11], which we briefly summarize in Section 4.3 when dealing with multiple nests.
Figure 4: The reduced dependence graphs (using dependence levels) for Example 2.
Figure 5: The component affinity graph for Example 2.
Figure 6: The alignment-distribution graph for Example 2.
3 Related work
There are numerous papers on the alignment and distribution problem. We refer the reader to the survey [5] and the references therein. In this section, we summarize a few selected papers. In addition to Li and Chen’s alignment method [13, 14] (already described in Section 2.1), we describe three papers by Tandri and Abdelrahman [17], Kelly and Pugh [9], and Ayguadé et al. [4, 3], whose goal is similar to ours. Next we present results by Gupta and Banerjee [7] and Li and Chen [12] on identifying structured communications and estimating their weight.
Our algorithm also uses the dynamic programming algorithm of Lee [11] when dealing with several loop nests. Indeed, redistributing some arrays between two consecutive nests may well prove more efficient. We describe Lee’s technique in Section 4.3.
3.1 Tandri and Abdelrahman
Given a loop nest, Tandri and Abdelrahman [17] construct an undirected graph where each node represents either a parallel loop, or an array dimension. There is an edge between a loop node and an array node if the dimension considered is indexed by the loop variable.
Attributes are assigned to the nodes: *, Cyclic or CyclicRcyclic for loop nodes, to favor load balancing, and *, Block or BlockCyclic for array node, to favor local access. For example, if $X$ is referred to as $X(a+i+b*j)$ where $j$ (outer) is parallel and $i$ (inner) is sequential, then the attribute will be BlockCyclic.
There is a conflict when an edge connects two nodes whose attributes are different. To solve such a conflict, we replace the attributes by an intermediary. Thus, Cyclic and Block resolve to BlockCyclic.
Once all conflicts are solved, we have to assign dimensions of the processor geometry to the nodes. The algorithm is a greedy one. We consider first the outer loop. We assign to them and to the array nodes connected to them a dimension of processors. We pursue then with the other nodes. A distribution scheme is then found.
Tandri and Abdelrahman’s method is somewhat crude, in that communication costs are not taken into account precisely. Also, their selection of the best array dimension to be distributed is not clear. Still, they give priority to distributing parallel loops, and next they align the array dimensions onto those loops: we believe this is the right way to go, and we use a similar (but refined) scheme in our algorithm.
3.2 Ayguadé et al.
Ayguadé et al. [4, 3] consider programs constituted of several consecutive perfect loop nests $L_1 L_2 \cdots L_n$. All arrays are assumed to have the same dimension $d$. They describe their method for 1D- and 2D-grids, but we only deal with 1D-grids in this short survey. We start with the construction of a graph called the Communication-Parallelism Graph. Nodes are organized in columns. Each column represents an array in a nest and it contains $d$ nodes.
There are two types of edges. Data movement edges show possible alignment alternatives between the dimension of two arrays in a nest $L_i$. The assigned weight reflects the data movement cost to be paid if these two dimensions are aligned and distributed. We add other data movement edges to show possible realignment in a sequence of nests. If the array $A$ in $L_i$ is used in $L_j$, then $d \times d$ edges connect each node of array $A$ in $L_i$ to each node of $A$ in $L_j$. If the edge connects the same dimension, its weight is null, otherwise its weight is the cost of a realignment.
Parallelism hyper-edges show possible parallelization strategies for the loops in $L_i$. An hyper-edge connects the nodes corresponding to the array dimensions that have to be distributed to parallelize the loop according to the owner computes rule. Its weight is the time that is saved when the loop is parallelized.
We have to find a path in the CPG that includes exactly one node of each column so that the sum of weights of the edges minus the sum of weights of the hyper-edges that connect nodes in the chosen path is minimized. This problem is formulated as a linear 0-1 programming problem. The variables are $Y_{PQ}(i, j)$ which corresponds to the edge between the $i^{th}$ dimension of $P$ and the $j^{th}$ dimension of $Q$ and $Z_k$ which corresponds to the $k^{th}$ hyper-edge.
The constraints are the following:
- $\sum_j Y_{PQ}(i, j) = \sum_j Y_{QR}(i, j) \forall i, P, Q, R$
- $\sum_i \sum_j Y_{PQ}(i, j) = 1 \forall P, Q$
- If $Z_k$ connects the nodes $X_{pi1}(i_1), \ldots, X_{pik}(i_k)$ which are connected by the edges $Y_{piQ}, \ldots, Y_{pikQ}$, we need $\sum_j Y_{piQ}(i, j) \geq Z_k \forall l \in [1..k]$
The approach of Ayguadé et al. [4, 3] is interesting because of their precise estimation of edge weights. Also they can handle redistribution between consecutive nests. However, the requirement that all nests are perfect and that all arrays have same dimension is very restrictive. In addition, the integer linear programming solution may prove too expensive in practice.
### 3.3 Kelly and Pugh
The title of Kelly and Pugh’s paper [9] is *Minimizing communication while preserving parallelism*. This title exactly corresponds to our goal! However Kelly and Pugh consider a framework quite different from ours: they study all the possible transformations (loop permutations) of the program to determine which one induces the maximum of parallelism and the best mapping of the computations.
To determine valid loop permutations, Kelly and Pugh use a dependence analysis more sophisticated than the dependence levels. The direct dependences are computed by the Omega software and the indirect dependences are computed by transitive closure.
For each legal permutation, they determine the parallelism level which is allowed and they estimate the number of required synchronizations (they use a sophisticated model which allows to take pipelining into account). Finally, for each statement pair, they compute the number of data written in the first statement and read in the second one, using value-based flow dependence analysis.
To summarize, in the case where a precise dependence analysis is possible (e.g., when all dependences are affine), Kelly and Pugh’s method is quite powerful. However, it cannot be applied to general loop nests where only limited information (such as dependence levels) is available.
### 3.4 Communication patterns
Li and Chen [12] present interesting results on communication routines. They consider already parallelized programs with sequential and parallel loops. They assume that each array element
can be assigned only once, that left-hand side subscripts are index variables, and that arrays are aligned to have a common index domain within each loop nest. We have a distribution scheme over a template and we want to recognize communication routines.
Each assignment \( a(\sigma_1, \ldots, \sigma_n) = \ldots b(\delta_1, \ldots, \delta_n) \ldots \) may generate communications. If the tuples differ in only one corresponding pair of elements, the communication is either a Spread or a Reduce or a Copy or a Shift or a Multi-spread. The routine can be found with a pattern matching on these elements.
If the tuples are strongly different, we try by pattern matching on the tuples to recognize one of these routines: One-All-Broadcast, All-One-Reduce, Single-Send-Receive, Uniform-Shift or Affine-Transform. When a pattern cannot be matched with a routine, we decompose it into sub-patterns. Indeed, a pattern over an n-dimensional index domain can be thought of as a composition of n simple patterns. For example, \( \text{send} \, a(c(i, j), j - 3) \, \text{to} \, (i, j) \) can be decomposed into two simple communications: \( \text{send} \, a(c(i, j), j - 3) \, \text{to} \, (i, i - 3) \), which is a Multi-spread, and then \( \text{send (the data) from} \, (i, j - 3) \, \text{to} \, (i, j) \), which is a Shift.
Gupta and Banerjee [7] improve Li and Chen’s alignment method to estimate communication costs. Their method is based on pattern-matching, applied upon the different assignments which could generate communications in the program. Their communication primitives are Transfer, OneToManyMulticast, ManyToManyMulticast, Scatter, Gather, Shift and Reduction.
They allow operations on the structure of the program to decrease the communications costs by founding a better placement of communication. For instance they use loop distribution over two components to enable any communication placed between those components to be aggregated with respect to that loop. They try to permute loops when there is a parallel loop outside a loop in which communication takes place. To control the size of communication buffers required, they propose to strip-mine the loops.
Sometimes, the compiler may generate more communication than necessary, for example when there are conditionals. Information about the frequency of execution of statements can help the compiler decide between carrying out potentially extra communication and using a large number of messages. Since the primitives corresponding to different terms implement the data movement in distinct grid dimensions, they can legally be composed in any order. So another optimization is to permute the communications in favor of reducing the message sizes handled by processors.
### 4 Solving the alignment-distribution problem
As already stated, we start from a parallelized program, i.e. a program for which dependence analysis and loop parallelization have already been carried out; we are using the same hypotheses as Li and Chen [14]. Our goal is to preserve the potential parallelism while conducting the alignment step. We first describe our algorithm for a unidimensional processor grid. Next we move to a bidimensional grid. In both cases, we target a single (possibly non perfectly nested) loop nest. For several consecutive loop nests, we simply use the approach of Lee [11], who uses a dynamic-programming algorithm to determine whether some data redistribution is needed between two successive loop nests.
#### 4.1 Unidimensional grids
##### 4.1.1 Construction of the alignment-communication graph
We have two kinds of nodes in the graph, array dimension nodes and loop nodes:
- For each array, each dimension of this array is represented by a node (like for Li & Chen graph). The weight of such a node is zero.
- Each loop is also represented by a node. We give a weight to this node which represents the (approximated) execution time of the loop. For parallel loops, we divide the sequential execution time by the number of processors, as in Ayguadé et al [4, 3].
Edges link array dimension nodes to loop nodes. There is an edge between two such vertices if there is a reference to the corresponding array dimension in the corresponding loop; the edge weight represents the (estimated) communication costs induced by the distribution of both the array dimension and the loop instances to the processors.
Finally, we add dashed arrows to illustrate the loop nesting. This is only for convenience. We refer to loop nodes and dashed arrows as the loop subgraph of the alignment-communication graph.
Consider the Cholesky factorization algorithm showed in Example 3. We use this example to describe our algorithm because it is a classical in compilation literature. Data dependence analysis can be conducted exactly on this example because all references are affine, but this is by no means a requirement for our algorithm.
**Example 3**
\[
\text{for } k = 1 \text{ to } n \text{ do} \\
\quad S_1 : a(k, k) = \sqrt{a(k, k)} \\
\quad \text{for } / / j = k + 1 \text{ to } n \text{ do} \\
\quad\quad S_2 : a(k, j) = \frac{a(k, j)}{a(k, k)} \\
\quad\text{end for} / / \\
\quad \text{for } / / i = k + 1 \text{ to } n - 1 \\
\quad\quad \text{for } / / j = i \text{ to } n - 1 \\
\quad\quad\quad S_3 : a(i, j) = a(i, j) - a(k, i) * a(k, j) \\
\quad\text{end for} / / \\
\quad\text{end for} / / \\
\text{end for}
\]
Note that Li and Chen's CAG for Cholesky has no edge, because there is a single array in the nest, and they do not take self references into account. We represent the alignment-distribution graph in Figure 7. Boxed nodes are the loop nodes; we use a circle for a parallel loop and a square for a sequential loop. The other nodes are the array dimension nodes. We use the following routines for the edge weights:
\[
\begin{align*}
\text{Br}(N) &= \text{Broadcast}(N) & \text{a processor sends the same } N \text{ data items.} \\
\text{Sc}(N) &= \text{Scatter}(N) & \text{a processor sends } N \text{ different data items.} \\
\text{Ga}(N) &= \text{Gather}(N) & \text{a processor receives } N \text{ different data items.} \\
\text{Aap}(N) &= \text{All_to_all-personalized}(N) & \text{each processor sends } N \text{ different data items.} \\
\text{Aa}(N) &= \text{All_to_all}(N) & \text{each processor sends the same } N \text{ data items.}
\end{align*}
\]
For example, the edge between \(a_2\) and the left parallel node \(j\) comes from statement \(S_2\). It means that if we distribute this \(j\) loop and the second dimension of \(a\), each processor \(j\) which computes \(a(k, j)\) has to receive from the same processor \(k\) the value of \(a(k, k)\); hence the label \(Br(1)\).
4.1.2 The algorithm
The goal is to find exactly one parallel loop node to distribute, along each path of the loop subgraph. We also need to distribute a dimension of each array. The optimization criteria is to minimize residual communications costs.
The optimal solution is to consider all different possibilities to distribute the parallel loops. Once a given distribution is chosen, we compare for each array the communication costs generated by this distribution, and we select the dimension which minimizes the communications. We sum the costs over all arrays and we obtain the total cost of the selected loop distribution. We keep the loop distribution scheme of minimal cost.
Coming back to Example 3, there are two different paths. We have to choose $j$ in the left path, and either $i$ or $j$ in the right path. In the case of the distribution scheme $(j, i)$, we have for $a1$ the weight $N \times Br(1) + 2N \times Sc(N/P) + N \times Ga(N/P) + N \times Br(N)$ and $N \times Br(1) + 2N \times Aap(N/P) + N \times Sc(N/P) + N \times Br(N/P)$ for $a2$. The weight of $a1$ is lower, hence we distribute $a1$. For the other distribution scheme $(j, j)$, the weight is $N \times Br(1) + N \times Sc(N/P) + N \times Ga(N/P) + 2N \times Aap(N/P) + N \times Aa(N/P)$ for $a1$ and $N \times Br(1) + N \times a(N/P)$ for $a2$. In this case, we choose $a2$. Then we have to compare the two solutions. The cost of the first solution is $N \times Br(1) + 2N \times Sc(N/P) + N \times Ga(N/P) + N \times Br(N)$, and the cost of the second solution is $N \times Br(1) + N \times a(N/P)$. Since a personalized all-to-all is expensive, we would most certainly select the first solution.
4.1.3 Complexity
Consider first the case of a perfect loop nest. Let $s$ be the number of parallel loops, $T$ be the number of arrays and $d_i$ the dimension of the $i$-th array $T_i$. The complexity of our algorithm is $O(s \times \sum_{i=1}^{T} d_i)$ because for each parallel loop and for each array, we search for the best dimension to distribute. Letting $d = \max_i (d_i)$ be the largest array dimension, the complexity of our algorithm is $O(d \times T \times s)$.
It is important to understand why this result does not contradict the NP-completeness result of Li and Chen, who show that the alignment problem is NP-complete in the size of the CAG, i.e., the number of arrays $T$ multiplied by the largest array dimension $d$. The intuitive explanation is the following: Li and Chen have no template reference for the alignment problem, so they have to explore the possibility of aligning each dimension of each array with every dimension of every other array, hence the combinatorial swell. On the contrary in our approach, because we aim at preserving
the potential parallelism, each loop distribution scheme constitutes a reference pattern for which we search the best distribution for each array. Because we have few possible loop distribution schemes, the overall complexity is kept small.
**Theorem 1** The alignment-distribution problem can be solved in time $O(d \times T \times s)$ for a perfect loop nest with $s$ parallel loops and $T$ arrays with largest dimension $d$.
In the case of a non-perfect nest, on a given path labeled $i$ in the loop nodes of the alignment-distribution graph, there are $s_i$ parallel loops. For instance in Example /refprog.choles/, we have two paths in the loop subgraph, $s_1 = 1$ and $s_2 = 2$. The complexity of the algorithm is $O(d \times T \times \prod_{i=1}^{p} s_i)$ because $\prod_{i=1}^{p} s_i$ represents the number of distribution scheme. In the worst case, the complexity is $O(d \times T \times e^s)$.
The exponential term is not important. Indeed, the number of parallel loops in a nest is not higher than 3 in practice.
### 4.1.4 Remarks
**Remark 1** In the above version of the algorithm, we always distribute exactly one parallel loop along each path of the loop subgraph. In certain cases, it may well be more efficient to execute a parallel loop in sequential mode on a single processor. We can implement this modification, which amounts to select *at most one* (instead of *exactly one*) parallel loop along each path of the loop subgraph: we make a copy of each parallel node. One copy indicates a sequential execution and the other a parallel execution. So, there are twice as many loop nodes, hence more loop distribution schemes to evaluate.
Similarly, we always distribute one dimension of each array. Sometimes, it will be better to allocate a whole array to an unique processor. To that purpose, we can add a node for each array which indicates that we do not want to distribute this array.
**Remark 2** The problem (and of course the alignment-communication graph) is “symmetric” between loop nodes and array dimension nodes. Sometimes, it will be better to iterate on all possible distribution schemes for the arrays, and to deduce the best distribution scheme for the loops. For Example 3, there is a single array of dimension 2 and several loop nodes, so we should indeed consider the different choices for distributing $a$, and for each of them to determine the best distribution scheme for the loops.
**Remark 3** For the (mostly theoretical) situation where our algorithm would be too costly, we can introduce the following greedy heuristic: along each path of the loop subgraph, give priority to distributing the most external parallel loop. This will lead to the largest granularity of the tasks that are distributed to processors.
### 4.2 Bidimensional grids
If the dimension of the processor grid of processors is larger than one, we propose the following two strategies.
4.2.1 Recursive algorithm
We build the alignment-distribution graph just as in Section 4.1, and we use the previous unidimensional algorithm. At this stage we have chosen to distribute one parallel loop and one dimension of each array. We distribute them along the first dimension of the grid.
We construct a new graph by deleting already chosen nodes. We update edge weights by taking the distribution scheme for the first grid dimension into account. Then we use a second time the unidimensional algorithm to determine which loops and which array dimensions will be distributed along the second grid dimension.
We iterate the process as many times as there are dimensions in the processor grid.
Example 4
Assume that we target a 2D-processor grid for the following nest:
```plaintext
for // i = 1 to n do
for // j = 1 to n do
for // k = 1 to n do
a(i, j, k) = b(j, i, k) * b(i, j, k)
end for //
end for //
end for //
```
Using this recursive algorithm, we first distribute the $k$ loop and the last dimension of $a$ and $b$. Indeed, such a choice preserves the parallelism and is communication-free. After deleting the corresponding nodes and updating the weights, we obtain the graph of Figure 8. Next the recursive algorithm decides to distribute $i$ and the first dimension of $a$ and $b$ along the second grid dimension.

4.2.2 Optimal algorithm
The main principle of the optimal algorithm is the same as in the unidimensional case. Instead of considering one node by path of the loop subgraph, we consider $g$ nodes by path, where $g$ is the dimension of the target processor grid. When $d$ loop nodes are chosen along each path, we determine for each dimension of each array the cost of the communications induced by the distribution of this dimension and these loops. We keep the loop distribution scheme which minimizes the communications.
Coming back to the example 4, we construct the graph depicted in the figure 9. In this graph, we have to compare the three following cases: distribute \((i, j)\), distribute \((i, k)\) or distribute \((j, k)\).
\textbf{Distribute} \((i, j)\): We distribute \(a_1, a_2\) and \(b_1, b_2\).
\textbf{Distribute} \((i, k)\): We distribute \(a_1, a_3\) and \(b_1, b_3\).
\textbf{Distribute} \((j, k)\): We distribute \(a_2, a_3\) and \(b_2, b_3\).
In all three cases communications come from accessing \(b(j, i, k)\). The first case is very expensive. We have to choose between the second and the third. Since the communications are the same for both, we distribute \((i, k)\), the solution with largest task granularity.
\subsection{4.2.3 Comparison}
Let \(g\) be the number of dimensions of the processor grid. For the recursive algorithm, the complexity for a perfect loop nest is \(O(g \times d \times T \times s)\). For a non perfect nest, we get \(O(g \times d \times T \times e^{\frac{s}{d}})\). This is because we use the unidimensional algorithm \(g\) times. Of course \(g\) can be viewed as a small constant in practice (\(g = 2\) or 3 for current machines).
For the optimal algorithm, the complexity for a perfect nest is \(O(\#\text{schemes} \times T \times d)\). The number of loop distribution schemes is \(\binom{g}{s}\). Hence the complexity is \(O(d \times T \times s^g)\). For a non perfect nest, the complexity is \(O(d \times T \times \prod_{i=1}^{g} s_i)\). So in the worst case, it's \(O(d \times T \times e^{g \times s})\).
Of course the optimal algorithm has higher complexity. However, it relies on a more accurate estimation of the communication costs, because when we search for a loop distribution scheme we look for \(g\) dimensions of arrays to distribute together with the selected loops.
\subsection{4.3 Several nests}
In the case of several loop nests, we use the method proposed Lee \[11\]. Given a program constituted by a sequence of \(n\) nests, we want to determine the best distribution scheme (for parallel loops and arrays) for the whole program. In a word, Lee \[11\] uses Li and Chen’s CAG as a basic block for a single loop nest, together with a dynamic programming algorithm to determine whether to
redistribute some array in between two consecutive blocks. We simply suggest to use our alignment-distribution graph as a new basic block, and to keep the dynamic approach unchanged. This will preserve parallelism over the whole program in addition to determining the best distribution and re-distribution of arrays.
When we consider two consecutive nests, we have two main choices:
- either we keep the same alignment-distribution for the two nests, and we look for the scheme that minimizes the sum of the communications for both nests,
- or we determine the best alignment-distribution for each nest, and we use a redistribution in between.
Consider a sequence of \( n \) loop nests \( L_1L_2\cdots L_n \). For each subsequence \( L_iL_{i+1}\cdots L_{i+j-1} \), where \( 1 \leq i \leq n, 1 \leq j \leq n - i + 1 \). Let \( T_{i,j} \) be the minimal time to compute \( L_iL_{i+1}\cdots L_{i+j-1} \) with the restriction that it uses the distribution scheme \( P_{i,j} \) for the sequence \( L_iL_{i+1}\cdots L_{i+j-1} \). Thus the final distribution scheme after computing \( T_{i,j} \) is \( P_{i,j} \). At the beginning, \( T_{1,j} \) is equal to \( M_{i,j} \). Let \( \text{cost}(P_{i-k,k}, P_{i,j}) \) be the communication cost of changing data layouts from \( P_{i-k,k} \) to \( P_{i,j} \). Lee [11] uses the following dynamic programming algorithm:
\[
\text{for } i = 2 \text{ to } s \text{ do }
\quad \text{for } j = 1 \text{ to } s - i + 1 \text{ do }
\quad\quad T_{i,j} = \min_{1 \leq k \leq i} (T_{i-k,k} + M_{i,j} + \text{cost}(P_{i-k,k}, P_{i,j}))
\quad \text{end for}
\text{end for}
\]
Minimum = \( \min_{1 \leq k \leq s} (T_{s-k+1,k}) \)
If the sequence of nests is enclosed by an iterative loop, the last line of the algorithm is modified as follows:
\[
\text{Minimum} = \min_{1 \leq k \leq s} (T_{s-k+1,k} + \text{MAX ITER} \times \text{dependence}(T_{s-k+1,k})),
\]
where \( \text{dependence}(T_{s-k+1}) \) returns the cost of changing data layouts from the distribution scheme of the last nest to the first one.
Consider the following simple example:
**Example 5**
\[
\text{for } i = 1 \text{ to } n \text{ do }
\quad \text{for } j = 1 \text{ to } n \text{ do }
\quad\quad a_{ij} = a_{i-1,j} + a_{ij}
\quad \text{end for}
\text{end for }
\]
\[
\text{for } i = 1 \text{ to } n \text{ do }
\quad \text{for } j = 1 \text{ to } n \text{ do }
\quad\quad a_{ij} = a_{i-1,j} \times a_{ij}
\quad \text{end for}
\text{end for }
\]
Lee’s algorithm consists in considering the program either as a unique nest or as two nests for which we may need to determine a redistribution scheme.
A unique nest: Our alignment-distribution algorithm decides to distribute the two parallel loops and the first dimension of $a$. The second nest induces many communications.
Two different nests: For the first nest, we distribute the $i$ loop and the first dimension of $a$. For the second nest we distribute the $j$ loop and the second dimension of $a$. There is no communication inside the two nests, but we need communications to redistribute $a$ between them.
We have to compare both solutions. In the first case, processor $P_j$ receives $a(i, j)$ from $P_i$ and $a(i-1, j)$ from $P_{i-1}$, and then sends the result to $P_i$. Each processor has to communicate with all the others several times. However, if we use a block distribution, these communications are often transformed into local memory accesses. So the final solution is to distribute $i$, $j$ et $a$1 (the unique nest strategy).
5 Conclusion
We have introduced the alignment-distribution graph to replace Li and Chen's component affinity graph. The major two advantages of our approach are the following:
- Parallelism is preserved: we derive the best loop distribution together with the best array alignment
- Complexity is polynomial for perfect loop nests. Complexity is always polynomial in the number of arrays addressed inside the nest.
In addition, we retain all the flexibility of Li and Chen's approach: new results from the literature and from experiments can be easily incorporated, for instance to refine the estimation of the communication and computation weights. Indeed, our weight model for communications is much more refined than the original CAG of Li and Chen; as for computation costs, we can also benefit from the literature, e.g. [8, 15, 16]. Finally, our graph can be used as a building block for techniques that manipulate larger programs.
The current largest limitation is that our alignment-distribution graph is built for a fixed, already parallelized loop nest. It would be nice to incorporate loop transformations in the framework: how to determine the best way of writing the loop nest, in order to derive the best way to distribute arrays and computations to processors?
References
|
{"Source-Url": "https://hal-lara.archives-ouvertes.fr/hal-02101994/file/RR1998-30.pdf", "len_cl100k_base": 11747, "olmocr-version": "0.1.51", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 62326, "total-output-tokens": 14065, "length": "2e13", "weborganizer": {"__label__adult": 0.000331878662109375, "__label__art_design": 0.00040221214294433594, "__label__crime_law": 0.0003197193145751953, "__label__education_jobs": 0.001102447509765625, "__label__entertainment": 8.630752563476562e-05, "__label__fashion_beauty": 0.00017130374908447266, "__label__finance_business": 0.0003666877746582031, "__label__food_dining": 0.0003826618194580078, "__label__games": 0.0007486343383789062, "__label__hardware": 0.00205230712890625, "__label__health": 0.0006346702575683594, "__label__history": 0.0004038810729980469, "__label__home_hobbies": 0.00015079975128173828, "__label__industrial": 0.0006260871887207031, "__label__literature": 0.00032019615173339844, "__label__politics": 0.0003211498260498047, "__label__religion": 0.0006160736083984375, "__label__science_tech": 0.10137939453125, "__label__social_life": 8.547306060791016e-05, "__label__software": 0.0090179443359375, "__label__software_dev": 0.87939453125, "__label__sports_fitness": 0.0003352165222167969, "__label__transportation": 0.0006985664367675781, "__label__travel": 0.0002684593200683594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50810, 0.02711]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50810, 0.41127]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50810, 0.84654]], "google_gemma-3-12b-it_contains_pii": [[0, 970, false], [970, 1106, null], [1106, 2803, null], [2803, 4147, null], [4147, 7305, null], [7305, 10803, null], [10803, 13287, null], [13287, 16988, null], [16988, 19423, null], [19423, 19618, null], [19618, 23081, null], [23081, 26147, null], [26147, 29810, null], [29810, 32835, null], [32835, 35581, null], [35581, 38490, null], [38490, 40448, null], [40448, 42696, null], [42696, 45305, null], [45305, 48238, null], [48238, 50810, null]], "google_gemma-3-12b-it_is_public_document": [[0, 970, true], [970, 1106, null], [1106, 2803, null], [2803, 4147, null], [4147, 7305, null], [7305, 10803, null], [10803, 13287, null], [13287, 16988, null], [16988, 19423, null], [19423, 19618, null], [19618, 23081, null], [23081, 26147, null], [26147, 29810, null], [29810, 32835, null], [32835, 35581, null], [35581, 38490, null], [38490, 40448, null], [40448, 42696, null], [42696, 45305, null], [45305, 48238, null], [48238, 50810, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50810, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50810, null]], "pdf_page_numbers": [[0, 970, 1], [970, 1106, 2], [1106, 2803, 3], [2803, 4147, 4], [4147, 7305, 5], [7305, 10803, 6], [10803, 13287, 7], [13287, 16988, 8], [16988, 19423, 9], [19423, 19618, 10], [19618, 23081, 11], [23081, 26147, 12], [26147, 29810, 13], [29810, 32835, 14], [32835, 35581, 15], [35581, 38490, 16], [38490, 40448, 17], [40448, 42696, 18], [42696, 45305, 19], [45305, 48238, 20], [48238, 50810, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50810, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-04
|
2024-12-04
|
6dfc53b7eb9eef77c9cd2f97d45cc726f5151396
|
[REMOVED]
|
{"Source-Url": "http://www.lirmm.fr/~huchard/Documents/Papiers/models08.pdf", "len_cl100k_base": 8295, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 41202, "total-output-tokens": 9710, "length": "2e13", "weborganizer": {"__label__adult": 0.0003056526184082031, "__label__art_design": 0.0003724098205566406, "__label__crime_law": 0.0003237724304199219, "__label__education_jobs": 0.0007109642028808594, "__label__entertainment": 5.6743621826171875e-05, "__label__fashion_beauty": 0.00015604496002197266, "__label__finance_business": 0.0002548694610595703, "__label__food_dining": 0.0002510547637939453, "__label__games": 0.00037741661071777344, "__label__hardware": 0.0005326271057128906, "__label__health": 0.00040030479431152344, "__label__history": 0.0002593994140625, "__label__home_hobbies": 8.827447891235352e-05, "__label__industrial": 0.0003845691680908203, "__label__literature": 0.0003046989440917969, "__label__politics": 0.00024890899658203125, "__label__religion": 0.0004279613494873047, "__label__science_tech": 0.0290374755859375, "__label__social_life": 9.751319885253906e-05, "__label__software": 0.01041412353515625, "__label__software_dev": 0.9541015625, "__label__sports_fitness": 0.00022780895233154297, "__label__transportation": 0.0004117488861083984, "__label__travel": 0.0001938343048095703}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36842, 0.04492]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36842, 0.59905]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36842, 0.86141]], "google_gemma-3-12b-it_contains_pii": [[0, 2661, false], [2661, 5768, null], [5768, 7021, null], [7021, 9087, null], [9087, 11606, null], [11606, 13450, null], [13450, 15905, null], [15905, 17919, null], [17919, 21701, null], [21701, 23745, null], [23745, 26128, null], [26128, 28247, null], [28247, 30423, null], [30423, 33897, null], [33897, 36842, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2661, true], [2661, 5768, null], [5768, 7021, null], [7021, 9087, null], [9087, 11606, null], [11606, 13450, null], [13450, 15905, null], [15905, 17919, null], [17919, 21701, null], [21701, 23745, null], [23745, 26128, null], [26128, 28247, null], [28247, 30423, null], [30423, 33897, null], [33897, 36842, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36842, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36842, null]], "pdf_page_numbers": [[0, 2661, 1], [2661, 5768, 2], [5768, 7021, 3], [7021, 9087, 4], [9087, 11606, 5], [11606, 13450, 6], [13450, 15905, 7], [15905, 17919, 8], [17919, 21701, 9], [21701, 23745, 10], [23745, 26128, 11], [26128, 28247, 12], [28247, 30423, 13], [30423, 33897, 14], [33897, 36842, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36842, 0.14286]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
9a2e94c1987371cc57832e4faecae3791f2a4ec4
|
**Title:** A Task Networking and Visual Programming Language for Jack
**Author:** Dr. Norman I. Badler
**Performing Organization:**
University of Pennsylvania
Computer and Information Science Department
Center for Human Modeling & Simulation
Phila., PA 19104-6389
**Sponsoring/Monitoring Agency:**
U.S. Army Research Office
P.O. Box 12211
Research Triangle Park, NC 27709-2211
**ABSTRACT**
This report includes how VisualJack was designed as a graphical user interface (GUI) to Lisp PaT-Nets (Parallel Transition Networks). The VisualJack conception was that a user could use the GUI to construct PaT-Nets interactively, see the relationships among the various parts of a PaT-Net program, and thus speed the task of PaT-Net definition. Essentially finite automata, Parallel Transition Networks execute in parallel in the Jack environment.x (See the Appendix for a guide to LISP PaT-Nets.) Together with the Jack LISP API, they form an intuitive interface to controlling simulation and behavior of processes and agents in Jack.
A Task Networking and Visual Programming Language for Jack
FINAL REPORT
DAAH04-94-G-0151
August 1996
Norman I. Badler
badler@central.cis.upenn.edu
MEMORANDUM OF TRANSMITTAL
U.S. Army Research Office
ATTN: AMSRL-RO-RI (Hall)
P.O. Box 12211
Research Triangle Park, NC 27709-2211
☐ Reprint (Orig + 2 copies) ☐ Technical Report (Orig + 2 copies)
☐ Manuscript (1 copy) ☐ Final Progress Report (Orig + 2 copies)
☐ Related Materials, Abstracts, Theses (1 copy)
CONTRACT/GRANT NUMBER: DAAH04-94-G-0151
REPORT TITLE: A Task Networking and Visual Programming Language for Jack
is forwarded for your information.
SUBMITTED FOR PUBLICATION TO (applicable only if report is manuscript):
Sincerely,
Norman I. Badler
Department of Computer & Information Science
University of Pennsylvania
Philadelphia, PA 19104-6389
A Task Networking and Visual Programming Language for Jack
Norman I. Badler, Principal Investigator
Prepared by: Brett Douville
Introduction
VisualJack was designed as a graphical user interface (GUI) to Lisp PaT-Nets (Parallel Transition Networks). The VisualJack conception was that a user could use the GUI to construct PaT-Nets interactively, see the relationships among the various parts of a PaT-Net program, and thus speed the task of PaT-Net definition.
Essentially finite automata, Parallel Transition Networks execute in parallel in the Jack environment. (See the Appendix for a guide to LISP PaT-Nets.) Together with the Jack LISP API, they form an intuitive interface to controlling simulation and behavior of processes and agents in Jack.
The node is the basic building block of the PaT-Net. There are several types of nodes, but each has a similar structure and behavior. Each node has an associated action, and transitions between nodes determine the path through the graph. Transitions can be randomly assigned, weighted with probability, or given as a set of ordered conditions from which the first valid condition will be selected. Conditions and actions can manipulate a set of local variables. A set of monitors adds control within the PaT-Net. VisualJack allows the user to create nodes and add transitions interactively. Lisp codes to be executed in either nodes or transitions may be typed directly into the graphical objects via the GUI.
The VisualJack GUI
VisualJack has a simple window manager, with the look and feel of Microsoft Windows95's "multiple document interface." To demonstrate, select "File->New->PaT-Net" from the menu bar with the left mouse button. You will note a window in the main VisualJack window which can be manipulated much like a Windows95 window. Also notice that when you move around to different selections in the "File" menu, the friendly help bar ("QuickHelp") at the bottom of the main window changes its text to give you a helpful hint about the function of that menu selection. (This will crop up at all times while you're using VisualJack -- it's a very helpful reminder of what various features do!)
Select the title bar of the window you just created (its name is "Untitled PaT-Net 1" by default -- we'll get to how to rename this later). You can drag and drop the window anywhere on the canvas just as in most window managers. As in Windows95, this window can also be maximized, minimized, and closed.
When you minimize a window using the left mouse button on either the Window Control Menu (under the button in the titlebar with the little "VJ" in it) or the button on the right hand side of the title bar with the underbar ("_") in it, it gets turned into a button which appears in the bottom of the VisualJack main window. Try minimizing the window both ways and restoring it by clicking on the button that appears in the lower left-hand corner of the VisualJack window.
You can also maximize and restore a window, using either the menubar or the button with the little picture of a window at the right hand side of the title bar. The button and menubar automatically reconfigure based on the current state of the window -- when you maximize, the maximize button becomes a restore button and vice versa, and the menu bars change also.
Finally, you can also close the window. Closing the window can be done from either the "X" button at the right hand side of the title bar, or by using the "Close" selection of the Window Control Menu or the main File menu.
Interacting with a PaT-Net Window
VisualJack features a context sensitive menu that is always available under the right mouse button (RMB). When you use the RMB inside of a VisualJack window, it gives a list of operations, which are appropriate to the window.
For example, if you click the RMB in the "Untitled PaT-Net 1" canvas (which is purple), a pop-up menu appears which indicates that you can currently "Create new node" in that window.
When you select "Create new node", you will find that the QuickHelp in the bottom of the main window of VisualJack changes to read "Click the left mouse button to place a new node; hit the middle mouse button to cancel." First, try aborting the new node creation by clicking the middle mouse button (MMB) anywhere inside of the purple area.
Next, create an actual node, by repeating the above step but using the LMB instead of the MMB inside the purple region.
Now that you've created a node, you have more options on the pop-up menu. Try using the RMB again, and you'll see that you now have the following selections:
Create new node
Edit node
Create arc
Delete node
Select "Delete node" from the pop-up menu. Note that the cursor will change to a skull and crossbones, which you should place over the node you've just created and choose the LMB (again, selecting the MMB will cancel this action).
Once you've selected the node to be deleted, you'll see a dialog box which asks whether or not you really want to delete the node, telling you that all edges leading in and out of the node will also be deleted. Select "cancel" and then repeat the whole process and select "OK".
You'll see that the node gets removed from the display. Furthermore, the pop-up menu will have changed again, so that now, the only action you're able to take is "Create new node" again.
Manipulating Nodes and Actions
Create another new node by using the pop-up menu and placing the node wherever you'd like. First, let's look at the action of that node by selecting the button that says "Action1". There's a lot of information about an action that you can fill in -- although most of this information isn't necessary for the actual running of a PaT-Net, it will be helpful for future versions of VisualJack to do things like debugging, etc.
Note that the title of the dialog window is the same as the title in the entry under "Title". If you change this name, you'll also change the name of the dialog.
You can also change the name of the action, annotate it (to help explain what it's supposed to do, for example) and change the lisp name of the action. Default names are given for all of these, except the annotation. By clicking the "Edit" button, you can edit the lisp code of the function, using a separate editor that pops up when the button is clicked. Selecting the "Cancel" button revokes the changes so that the original settings are restored, and selecting "OK" makes the changes.
You can also edit a node by selecting the "Edit node" entry on the pop-up menu. When you do so, you will see several bits of information about the node, much like the action editor. Furthermore, you can set the action of the node to be an existing action in the PaT-Net (such as "no-op", which exists in every PaT-Net by default) by clicking the left mouse button on the entry window containing the action name. This pops up a list box from which one of several existing actions can be selected. Simply select one of these to change the action (or keep the action) of the node. You can also create a new action for the node by selecting the "New" button. This will allow you to set the name of the new action.
Finally, you can choose to change the type of a node, for example, from a "Normal" node (from which arcs are taken based on the values of conditions) to a "Probabilistic" node (from which arcs are taken based on the probabilities of taking various arcs).
Of course, any changes you make can be cancelled with the "Cancel" button, and they are made when you select the "OK" button.
Creating Arcs
Once you've created a node, you have the option of creating arcs (you need only create a single node, since arcs can have the same beginning and ending). To create an arc, simply select "Create arc". QuickHelp will now tell you to select the start node of the arc using the left mouse button and having done so, will then prompt for the end node for the arc. To create an arc beginning and ending at the same node, simply select the same node twice.
Try creating nodes and arcs for a while -- in particular, note that arcs are laid out so that they don't overlap with one another when more than one arc goes between the start and end nodes.
Arcs are laid down with a simple two-line diagram because of speed tradeoffs. Tcl scripts are unfortunately very slow in drawing many objects (they do not take advantage of specialized hardware such as is found on the SGI) so a more rounded curve is simply impractical when many arcs occupy a scene. In future versions of VisualJack, other options could be:
1. Implementing in a language with lower level control of the hardware such as C (or C++)
2. Changing level of detail on the arcs when interactive drawing rates are required.
In any case, having created several arcs, you can now manipulate the conditions and arc information using the "Modify arc" command on the pop-up menu.
APPENDIX: LISP PaT-Net Guide
Appendix: PaT-Net User’s Guide
PaT-Net User’s Guide
Brett J. Douville
August 4, 1995
1 Introduction
Essentially finite automata, Parallel Transition Networks (PaT-Nets) execute in parallel in the Jack environment. Together with the Jack LISP api, they form an intuitive interface to controlling simulation and behavior of processes and agents in Jack.
The node is the basic building block of the PaT-Net. There are several types of nodes (see Section 7), but each has a similar structure and behavior. Each node has an associated action, and transitions between nodes determine the path through the graph. Transitions can be randomly assigned, weighted with probability, or given as a set of ordered conditions from which the first valid condition will be selected. Conditions and actions can manipulate a set of local variables. A set of monitors adds control within the PaT-Net.
This framework provides a powerful yet intuitive machinery for simulation control. This document describes in detail all important features of the PaT-Net formalism; the addenda provide several contextual details.
2 PaT-Net Declaration
Before any actions, conditions, nodes, or anything else about a PaT-Net can be declared, the PaT-Net itself has to be declared. This is just a simple line which alerts the LISP interpreter to the existence of a PaT-Net having a particular name and a particular set of local variables (as described in Section 3 below).
2.1 Declaring the PaT-Net
The LISP syntax for declaring a PaT-Net is:
(deffsm <pname> `(,<lvar1>, <lvar2> ... <lvarn>))
where
• <pname> is the name of the PaT-Net.
• `<lvar;>` is the name of the `i`th variable local to the PaT-Net. These will be the only variables local to the PaT-Net.
Appendix B describes a declaration macro, `defnet`, in detail. `Defnet` is useful only for small PaT-Nets consisting of between ten and twenty nodes. Essentially, the macro bundles action, condition, node, and monitor assignments into a simpler form that doesn’t require the PaT-Net name to be included in every assignment. For more details, see Appendix B.
2.2 Example
The list of local variables can be as simple or as lengthy as desired. Here’s a simple example:
```lisp
(deffsm grab_tool_net `(human hand tool))
```
A more complicated example would include a longer list of variables, such as:
```lisp
(deffsm thumb_net `(humanptr handstr jptr0 jptr1 jptr2 seg0
seg1 seg2 fin0 fin1 fin2 fin3 goal_x goal_z object seg_list
start end time motionflag opp))
```
2.3 A Tip for Declaring PaT-Nets
When writing PaT-Nets, it’s helpful to describe precisely the purpose of each local variable. That way, when a user attempts to use your PaT-Net, there is a clear specification (if not an overly formal one) of what exactly your PaT-Net manipulates.
For example, the simple declaration above could be modified as follows:
```lisp
(deffsm thumb_net
`(humanptr ;;; Pointer to human whose thumb is moved
handstr ;;; Which hand ("right" or "left")
jptr0 ;;; Joint pointers
jptr1
jptr2
seg0 ;;; Strings for the names of the segments
seg1 ;;; in the thumb
seg2
fin0 ;;; Lists of strings, three strings each
fin1 ;;; containing the names of the segments in
fin2 ;;; the fingers -- sans human-name
fin3
goal_x ;;; Goal angles for the thumb0 joint
goal_z ;;; Will default to hand geometry limits
```
object ;; Grasped object
seg_list ;; Possibly colliding segments
;; (less object name)
start ;; Start time
end ;; End time
time ;; Explicit representation of time
motionflag ;; Use motion system for time?
opp ;; Defaults to "palmar".
;; May be one of "palmar", "adducted", "pad".
;; Refers to opposition space info.
))
This specification clarifies the above example, and this style tends to be generally beneficial in more complicated examples.
3 Local Variables
Each PaT-Net may have several local variables, variables which are local to each instantiation (see Section 10, below). These local variables must be declared when the PaT-Net is declared (see Section 2 above).
Accessing Local Variables
Local variables of a PaT-Net may be accessed and manipulated solely through the val function. The syntax for the val function is as follows:
(val <label> <?newval>)
where <label> is the name of the local variable being accessed, and <?newval> is an optional parameter which, if present, becomes the new value of the local variable. The function val returns the value of the local variable after the function call; if the function changes the value of the variable, it returns the new value.
4 PaT-Net Initialization
Each PaT-Net executes an initialization phase when instantiated by a message (see Section 10 below). When the PaT-Net is first instantiated, the arbitrary LISP code in the body of the initialization is evaluated; this code is not evaluated at any other time and only one initialization phase may be defined for a particular PaT-Net. (Actually, more than one initialization phase may be defined, but only the last one bound would be executed when the PaT-Net is instantiated.)
4.1 Defining the Initialization Phase
The LISP syntax for the initialization routine of a PaT-Net is as follows:
\[
\text{(definit <pname> <iargs> <ibody>)}
\]
where
- \text{pname} is the name of the PaT-Net for which the initialization is defined.
- \text{iargs} is a list of arguments to the PaT-Net. This is a LISP argument string, and may contain, for example, optional and keyword arguments.
- \text{body} is the body of the PaT-Net initialization.
Initialization occurs immediately after the PaT-Net is instantiated (see Section 10 below).
4.2 An Example
In the following example, a PaT-Net with local variables (\text{humanptr} \ \text{handstr} \ \text{toolptr}) is instantiated with a string describing a human in the \text{Jack} environment, a string describing a tool in the \text{Jack} environment, and a string telling with which hand to reach for the tool.
\[
\text{(definit reach\_net \ (humanstr toolstr &key (handstr \"\text{'right'}\"))} \\
\quad ;; \text{Assign the local variable humanptr to the pointer to the human figure.} \\
\quad \text{(val humanptr (figure\_find humanstr))}
\]
\[
\quad ;; \text{Assign the handstr to the argument handstr, which must be either} \\
\quad ;; \text{\text{\text{\text{\text{\text{'right'}}\text{ or 'left'}}}}.} \\
\quad \text{(val handstr handstr)}
\]
\[
\quad ;; \text{Assign the local variable toolptr to the pointer to the tool} \\
\quad ;; \text{described by the string toolstr.} \\
\quad \text{(val toolptr (figure\_find toolstr))}
\]
\[
\quad ;; \text{Print a message to the calling window.} \\
\quad \text{(format t \"\text{\text{'Initialization complete ~%'}\"})}
\]
5 PaT-Net Conditions
A \text{condition} is an arbitrary LISP expression that evaluates to \text{nil} or non-\text{nil}. Typically, conditions are tested to determine what transition to take from a node to a subsequent node (see Section 12 below).
Rather than being directly connected to any particular transition, conditions are bound to a PaT-Net, and can be called as a message. They can be combined arbitrarily in this way to make new conditions; similarly, if they have side effects, they can be used as parts of actions (see Section 9).
5.1 Defining Conditions
The LISP syntax for defining a condition is:
(defcond <pname> :<cname> <cbody>)
where
- `<pname>` is the name of the PaT-Net in which the condition is defined.
- `<cname>` is the name of the condition.
- `<cbody>` is the condition body. The body of the condition is evaluated when the condition is called.
A condition evaluates to the return value of the last evaluated expression in the condition body.
Predefined Conditions
The :default condition is predefined in every PaT-Net. Evaluating :default always returns non-nil.
5.2 Examples
As LISP expressions, conditions can be arbitrarily complex and take full advantage of the expressive power of LISP. Some of the following examples use local variables, which are described in Section 3. All of the PaT-Nets have the same name: “simnet”.
- This example checks the condition of some global variables.
(defcond simnet :c_threshold
;; Checks whether either global variable <x1> or global variable <x2> has exceeded the global variable <tolerance>.
(or (> x1 tolerance)
(> x2 tolerance)))
- An example of a condition which tests to see whether a certain time has elapsed in Jack’s motion system. (The function (motion-time) is a Jack LISP api call which returns a floating point value of the current simulation time.)
(defcond simnet :c_test_time
;; Returns false if the motion system hasn’t yet reached time <time>.
(< (motion-time) (val time))))
- This condition is again a tolerance measure, but it instead checks a robot's current fatigue against its expected fatigue tolerance and its current heat against its threshold heat. (The functions fatigue, fatigue_threshold, sys_temp and heat_tolerance would have to be written – they are given as examples; their names suggest their results.)
(defcond simnet :c_breakdown
;; Tests whether robot breakdown is imminent by looking at fatigue
;; (measured by energy levels) and current system temperature.
(or
(> (fatigue (val robot)) (fatigue_threshold (val robot))))
(> (sys_temp (val robot)) (heat_tolerance (val robot)))))
5.3 Tips for Writing Conditions
- Name your conditions mnemonically, so that you have some idea of what it means at a glance. This will also make it easier for another programmer to understand your code (especially node transitions) and it might make it easier to generate diagrams of your PaT-Nets.
- You might also want to preface your conditions with the letter 'c' if you plan to use them for any side effects they might cause. This will make it clear that the method is a condition, but that it might be used out of context. Also, it makes transitions a little more clear (sort of like putting a 'p' before pointers when writing C code).
- If you find yourself repeating a lot of code in your conditions, i.e. anding several conditions together as another condition, try to take advantage of PaT-Net communication (Section 9, below). The following shows two sets of conditions, one with repeated code, and one with conditions called by PaT-Net communication:
(defcond simnet :c_fatigue
;; Tests to see whether the robot has drained its batteries.
(> (fatigue (val robot)) (fatigue_threshold (val robot))))
(defcond simnet :c_overheat
;; Tests to see whether the robot is in danger of overheating.
(> (sys_temp (val robot)) (heat_tolerance (val robot))))
(defcond simnet :c_breakdown
;; Tests whether robot breakdown is imminent by looking at fatigue
;; (measured by energy levels) and current system temperature.
(or
(> (fatigue (val robot)) (fatigue_threshold (val robot))))
(> (sys_temp (val robot)) (heat_tolerance (val robot))))
Compare the rewriting of code in :c_breakdown with the following, which is much clearer:
(defcond simnet :c_breakdown
;; Tests for imminent robot breakdown by looking at fatigue
;; (measured by energy levels) and current system temperature.
(or
(send self :c_fatigue)
(send self :c_overheat)))
This also has the virtue of reminding you what other conditions you are testing in the PaT-Net.
6 PaT-Net Actions
An action is an arbitrary LISP expression. Though typically an action modifies something in the Jack environment, it can compute an arbitrary function, for example. However, since we are concerned primarily with the use of PaT-Nets for simulation purposes, we will focus on actions which have meaning in the Jack simulation environment.
As with conditions (Section 5), actions are not associated directly with any particular node; rather, actions are defined for a PaT-Net and are called by nodes when entered. They can also be called independently from individual nodes, using PaT-Net communication; an example appears in Section 6.2.
6.1 Defining Actions
The LISP syntax for defining a condition is:
(defaction <pname> :<aname> <abody>)
where
- `<pname>` is the name of the PaT-Net in which the action is defined.
- `<aname>` is the name of the action.
- `<abody>` is the action body. The body of the action is evaluated when the action is executed.
Similarly to a condition, an action evaluates to the return value of the last evaluated expression in the action body.
Predefined Actions
There is a single predefined action in every PaT-Net, the :no-op action. :no-op means "no operation" – this is a null action which simply returns non-nil.
6.2 Examples
Because they are LISP expressions, conditions can be arbitrarily complex and can take full advantage of the expressive power of LISP. However, we will usually think of actions as having some impact on a simulation, whether directly (such as adjusting a joint angle) or indirectly (such as instantiating another PaT-Net which will have some effect on the simulation). Here are a few simple actions (some of which use functions that are undefined). We'll continue using our robot controller example.
- Here's an action that turns the robot to the left a certain arc. (Several of these functions are bound in the Jack LISP api. Assume that *frame-rate* is a global constant describing the Jack simulation rate.)
(defaction simnet :turn_left
;; Turns a robot to the left a certain number of degrees dependent on the
;; frame rate and the turning velocity (angular velocity in degrees/sec)
;; of the wheels.
(rawjcl (format nil "move_figure(%s,%a);"
(val robot)
(matrix-tojcl
(matrix-mult
(figure-transform (figure-find (val robot)))
(matrix-rot (* *frame-rate* (val turn-velocity))))))
- In this example, an avoidance is bound to a wall in the environment. This indirectly affects the simulation because the behavioral simulation system (BSS), which provides some low-level control of human locomotion through attraction and avoidance, will change the path of the human to avoid the wall.
(defaction simnet :bind_wall_avoid
;; Binds an avoidance to a wall, whose pointer is currently in the local
;; variable 'wall'. The function (bind-avoidance) takes two arguments, a
;; human and a figure, and the human avoids the figure (through BSS).
(bind-avoidance (figure-find (val human))
(val wall)))
- In this example, the action spawns another PaT-Net. Again, this doesn't directly affect the simulation, but instead creates another PaT-Net which may itself directly (or indirectly) affect the simulation.
(defaction simnet :start_simnet2
;; Starts a different PaT-Net with the argument of the current robot.
(send simnet2 :new (val robot)))
6.3 Tips for Writing Actions
- Name your actions mnemonically, so that you have some idea of what it means at a glance. This will also make it easier for other programmers to understand your code at a higher level just by looking at the nodes and transitions; it might make it easier to diagram your PaT-Nets as well.
- Prefacing actions with the letter 'a' is helpful if you intend to use them as parts of conditions.
- Actions can be called similarly to conditions through messages; for more detail, see Section 9.
7 PaT-Net Nodes
Nodes form the heart of PaT-Nets, as they are the structure on which actions and conditions are hung. In the following, the follow node refers to the node to which a transition is made. There are several types of PaT-Net nodes, each of which will be described in detail below:
**Simple Node** The type of node one normally associates with finite state machines, this has a number of transitions whose conditions are tested before moving to another node.
**Probabilistic Nodes** This node has a number of transitions associated with it, but instead of having particular conditions associated with each node, probabilities summing to a value less than or equal to 1.0 are associated with transitions. When selecting a transition, the node will select the follow node probabilistically.
**Weighted Nodes** Weighted nodes are like probabilistic nodes, except that the probability values are scaled to sum to 1.0.
**Random Nodes** Random nodes are simply probabilistic nodes where every node has equal probability; these sum to 1.0. The follow node is selected randomly from among a list of nodes.
7.1 Defining Simple Nodes
The LISP syntax for defining a simple node is:
```
(defnode <pname> <nname> :<aname>
(:<c1> <n1>) ;; Transition on c1 to n1
(:<c2> <n2>)...) ;; Transition on c2 to n2 etc.
```
where
- `<pname>` is the name of the PaT-Net in which the condition is defined.
- `<nname>` is the name of the node which you are defining. (You must name nodes so that transitions between nodes can be bound.)
• `<aname>` is the name of the action to execute upon entering the node (see Section 12 below).
• `<c_n>` is the name of the condition associated with a particular transition. These conditions will be evaluated in order until one of them returns non-`nil`, at which point there will be a transition to the follow node.
• `<n_n>` is the name of the follow node if the condition evaluates to non-`nil`.
### 7.2 Defining Probabilistic Nodes
The LISP syntax for defining a probabilistic node is:
```
(def-probnode <pname> <nname> :<aname>
((<p_1> <n_1>) ;; Probability of transition to n_1
(<p_2> <n_2>) ...) ;; Probability of transition to n_2 etc.
where
• `<pname>` is the name of the PaT-Net in which the node appears.
• `<nname>` is the name of the node.
• `<aname>` is the name of the action to execute upon entering the node.
• `<p_n>` is the probability associated with a particular transition. The follow node will be determined probabilistically, and with probability `<p_n>` will transition a particular node.
• `<n_n>`, which is the name of the follow node with probability `<p_n>`.
A probabilistic node is only meaningful if the probabilities sum to less than or equal to 1.0. If the sum of the probabilities P ≤ 1.0, then no transition will be taken (see Section 12).
### 7.3 Defining Weighted Nodes
A weighted node is a special case of a probabilistic node, where probabilities are assigned according to the weights on the nodes and scaled to sum to 1.0. The LISP syntax for defining a weighted node is:
```
(def-weightnode <pname> <nname> :<aname>
((<w_1> <n_1>) ;; Transition to n_1 with weight w_1
(<w_2> <n_2>) ...) ;; Transition to n_2 with weight w_2 etc.
where
• `<pname>` is the name of the PaT-Net in which the node is defined.
• `<nname>` is the name of the node.
• `<aname>` is the name of the action to execute upon entering the node.
• `<w_n>` is the weighted probability to assign to a particular transition.
• `<n_n>` is the name of the node to take with weighted probability `<w_n>`.
A transition from a weighted node will always be taken (it is impossible to remain in the state, though an explicit translation to the state is possible).
### 7.4 Defining Random Nodes
A random node is a special case of a weighted probabilistic node in which all states have equal weight. The LISP syntax for defining a random node is:
```lisp
(def-randnode <pname> <nname> :<aname>
n_1 n_2 ... n_n) ;; Possible transitions
```
where
• `<pname>` is the name of the PaT-Net in which the node is defined.
• `<nname>` is the name of the node.
• `<aname>` is the name of the action associated with the node.
• `<n_n>` are the names of potential follow nodes among which a random selection is made. The probability of selecting any particular follow node is $\frac{1}{k}$, where $k$ is the number of nodes.
### Predefined Nodes
There is one predefined node in every PaT-Net, the `exit` node. Making a transition to the exit node removes the PaT-Net from the list of active PaT-Nets. (The list of active PaT-Nets is described in Section 12.)
### 7.5 Examples
Here are examples of each type of node:
• This node in a robot controller determines whether to back up, continue straight, or turn on the basis of some primitive sensation. The robot continues in its current direction if there is no obstacle directly in front of it, backs up if it’s boxed in, and goes to a turning node otherwise.
(defnode simnet locomote :move_forward
(:forward_clear locomote)
(:boxed_in back_up)
(:default turn))
- This node in the same robot controller decides among turns probabilistically. It will go left with probability .2, right with probability .2, and straight with probability .4. With probability .2 the robot will stay in this node (which is different from returning to this node, see Section 12) and do nothing. In the subsequent simulation step, a second probabilistic evaluation will occur.
(def-probnode simnet possibly_turn :move_forward
(0.2 turn_left)
(0.2 turn_right)
(0.4 possibly_turn))
- Here is a weighted probability version of the previous node. Note that the PaT-Net can't remain in this node in this version. The values associated with the transitions will scale to 0.25, 0.25, and 0.5 respectively.
(def-weightnode simnet possibly_turn2 :move_forward
(0.2 turn_left)
(0.2 turn_right)
(0.4 possibly_turn))
- Finally, here's a version of the same node using a random node. Again, there is no possibility of remaining in the same node without making a transition.
(def-randnode simnet possibly_turn3 :move_forward
turn_left turn_right possibly_turn)
7.6 The Initial Node
The first node defined in a PaT-Net is the initial node. This will be the node which is entered immediately after the initialization phase of the PaT-Net (see Section 4).
With the exception of the initial node, the order in which nodes are defined is unimportant.
7.7 Tips for Writing Nodes
- As with conditions and actions, it is often helpful to name your nodes mnemonically. Names like node1 and state12, while obvious choices, are not very illustrative of information about the state.
- Take care when listing your transitions in a simple node. Remember that they will be tested in order rather than non-deterministically.
8 Monitors
A monitor is a device which exists outside of the node structure of a PaT-Net. As its name suggests, it checks whether a specific condition is non-nil of the PaT-Net at every simulation step, and if it is, executes an action. Only one monitor executes per clock tick; the first whose condition is true.
Monitors are useful for looking at special cases, updating local variables (such as an explicit time variable or a counter), and other actions which might be useful to execute every frame. They can be helpful in debugging, too, by executing an action which prints the values of all local variables (or tracking one variable in particular) after every frame.
8.1 Defining Monitors
The LISP syntax for defining a monitor is:
(defmonitor <pname> <mname> :<cname> :<aname>)
where
- <pname> is the name of the PaT-Net in which the monitor resides.
- <mname> is the name of the monitor.
- <cname> is the name of a condition associated with the PaT-Net. This condition will be evaluated every simulation frame; if non-nil, the action below will be executed.
- <aname> is the name of an action associated with the PaT-Net. This action will only be executed in frames when the condition denoted by <cname> is true.
8.2 Example
This monitor increments a variable representing simulation time on every simulation step. Because of the nature of monitors, the action associated with the monitor is provided; the condition is predefined.
(defaction simnet :increment_time
(val time (+ (val time) *frame-rate*)))
(defmonitor simnet inc_time :default :increment_time)
8.3 Tips for Writing Monitors
- Use monitors sparingly; if you find yourself requiring a lot of monitors, you may want to reconsider the design of your PaT-Net, either through refining your actions or by taking advantage of PaT-Net parallelism and having several PaT-Nets execute at once to simulate your process.
• Monitors can also benefit from using mnemonic names. Consider the readability of the example above against the following:
(defmonitor simnet mon :default :mon_action)
• Remember that at most one monitor will be executed per simulation step (see Section 12 below); keep this in mind when designing monitors.
9 PaT-Net Communication
PaT-Nets communicate by messages. A message to a PaT-Net class can instantiate a new class (see Section 10, below), signal a wait (see Section 11, below), and execute actions and conditions by name (for an example, see Section 5.3 above).
9.1 Sending Messages
Several different messages can be sent to PaT-Nets; however, these all follow a common LISP syntax, given below.
(send <name> :<message> <args>)
where
• <name> is the name of the object being sent a message (either a PaT-Net or a PaT-Net class in the case of instantiation, see Section 10 below).
• <message> is the message being sent. Messages are always preceded by a colon.
• <args> are any arguments required by the message. Arguments are most commonly seen when instantiating a new PaT-Net (any arguments to the initialization of the PaT-Net must be sent), or when setting waits, which are discussed in detail in Section 11 below.
9.2 Message Evaluation
Message evaluation returns different values depending on the message. The following is a list messages and their return values:
• Evaluating a :new message to a PaT-Net class results in a new PaT-Net instance. This result can be used subsequently for the sending of other messages, for example:
(setf simnet1 (send simnet :new 'jack' 'hammer' 'left'))
(send simnet1 :c_threshold)
• A special message receiver (self) always refers to the object from which the message is sent. For example, in Section 5.2 above, we defined a condition in which two messages were passed to create a disjunction of two existing conditions. This example is repeated below using messages:
(defun simnet :c_breakdown
; Tests whether robot breakdown is imminent by looking at fatigue
; (measured by energy levels) and current system temperature.
(or
(send self :c_fatigue)
(send self :c_overheat)))
• Evaluating a :<condition> message to a PaT-Net results in the evaluation of the condition within that PaT-Net. For example, in the above, the (send simnet :c_threshold) command would return the same result as evaluating :c_threshold within the PaT-Net containing the condition.
• Section 11 provides a full discussion of waits.
10 PaT-Net Instances
A specification of a PaT-Net differs from an instantiation (which I will call an instance) of a PaT-Net; the specification of a PaT-Net provides a template which derives individual instances. This important distinction separates the PaT-Net class from the actual PaT-Net which is instantiated via a message.
Sending a :new message (along with any arguments required to initialize the PaT-Net) instantiates a PaT-Net of the type being sent the message. The evaluation of such a message returns the PaT-Net instance thereby created. For example, evaluating
(send simnet :new "jack", "hammer")
will instantiate the PaT-Net whose initialization phase is described in Section 4 above.
11 Waits
An action, condition, or initialization can post a set of waits; the PaT-Net will block until the wait is no longer active. The following sections, and the description of execution (Section 12) should also be helpful. There are several types of waits, each described in detail below:
Wait for Another PaT-Net This allows a PaT-Net to wait until another PaT-Net exits before continuing.
Wait for a Specific Time This allows a PaT-Net to wait for a specific time in Jack's motion system before proceeding.
Wait for a Specific Condition This allows a PaT-Net to wait until a specific condition becomes true before continuing.
Wait for a Motion to Complete The PaT-Net will wait for a motion in *Jack's* motion system to finish before continuing.
Wait for a Semaphore This allows a PaT-Net to wait based on a operating system-style semaphore with a particular priority. A full description of our implementation of semaphores is given in Appendix C.
Each of these waits will be described in detail below.
### 11.1 Waiting for Another PaT-Net
Currently, the PaT-Net formalism only supports waits for another PaT-Net to exit (that is, pass through its *exit* node). This functionality will be extended so that the wait can be used to block the PaT-Net until another PaT-Net goes through an arbitrary node. The LISP syntax for this extension will be:
```
(send <patnet> :wait-fsm <patnet-instance> ?<:state statename>)
```
where
- `<patnet>` is the PaT-Net which is going to wait. This argument is most commonly filled with *self*, however, a wait can be signalled for any PaT-Net in this manner. I refer to this as the *waiting* PaT-Net.
- `<patnet-instance>` is the PaT-Net for which to wait, which I refer to as the *wait-for* PaT-Net.
- `?<:state statename>` refers to the optional keyword argument giving a state through which the *wait-for* PaT-Net must pass before the *waiting* PaT-Net can continue. For an example, see Section 11.6 below.
### 11.2 Waiting for a Specific Time
Often when a PaT-Net is running in lock step with the *Jack* motion system, waiting for a specific time in the motion system can be helpful. (For example, if you’re simulating a teapot on a stove, then you might want steam to come out of it after three minutes on high heat.) The LISP syntax for defining a wait of this type is:
```
(send <patnet> :wait-time <time>)
```
where
- `<patnet>` is the name of the *waiting* PaT-Net.
- `<time>` is the time in the motion system until which to wait.
11.3 Waiting for a Specific Condition
PaT-Nets can be made to wait for an arbitrary condition to be true within the PaT-Net; such conditions can therefore refer to local variables using the val macro (see Section 3 above). The conditions must be expressed in terms of functions which take no arguments, usually a zero-argument lambda function. The LISP syntax for describing such a wait is:
\[(\text{send} \ <\text{patnet}\> :\text{wait-condition} \ <\text{condition-fun}\>)\]
where
- \(<\text{patnet}\>\) is a PaT-Net instance or self.
- \(<\text{condition-fun}\>\) is a LISP function closure which takes no arguments.
11.4 Waiting for a Motion to Complete
A PaT-Net can wait for a particular motion in Jack's motion system to complete before continuing. To do so, the PaT-Net must be provided with a pointer to the motion in the animation system, which can be found using the Jack LISP api call \((\text{motion-find} \ <\text{str}\>)\), where \(<\text{str}\>\) is the name of the motion in Jack (a string). The LISP syntax for such a wait is:
\[(\text{send} \ <\text{patnet}\> :\text{wait-motion} \ <\text{motion-pointer}\>)\]
where
- \(<\text{patnet}\>\) is a PaT-Net instance or self.
- \(<\text{motion-pointer}\>\) is a pointer to a motion in the Jack motion system.
For more information about Jack's motion system, see the Jack User's Guide and the Jack LISP api.
11.5 Waiting for a Semaphore
The LISP version of semaphores is analogous to the operating system concept of a semaphore, and are described in more detail in Appendix C. Waiting on a semaphore means being put on the semaphore's wait queue in order of priority. The LISP code for waiting on a semaphore is as follows:
\[(\text{send} \ <\text{patnet}\> :\text{wait-semaphore} \ <\text{semaphore}\> \ ?<:\text{priority} \text{ priority}>\)]
where
- \(<\text{patnet}\>\) is a PaT-Net instance or self.
- \(<\text{semaphore}\>\) is an instance of a semaphore.
- \(?<:\text{priority} \text{ priority}>\) is an optional assignment of the priority the PaT-Net has on the semaphore's wait queue. This defaults to 1.0.
11.6 Examples
Included below are examples for several types of waits.
- In the following example, the action spawn_simnet2 of simnet instantiates a new PaT-Net of type simnet2. Any instance of simnet executing this action will wait until the new instantiation of simnet2 exits before continuing.
(defaction simnet :spawn_simnet2
;; Spawn another PaT-Net and wait for it to exit.
(send self :wait-fsm (send simnet2 :new (val human) (val tool)))))
- The following example illustrates the use of a wait for a specific time in the motion system:
(defaction simnet :wait_until_time
;; The variable time has been determined by other means, and
;; now the PaT-Net must wait until that time to continue.
(send self :wait-time (val time)))
- In the following example, assume the function attached-fig returns non-nil if its first argument is attached to its second argument. The PaT-Net waits until this condition returns non-nil.
(defaction simnet :wait_for_attach
;; simnet waits until the tool has been attached to the human.
(send self :wait-condition
#'(lambda () (attached-fig (val tool) (val human)))))
- The following provides an example of waiting for a specific motion (in Jack's motion system) to complete:
(defaction simnet :wait_on_arm
;; Simnet waits until the arm motion completes.
(send self :wait-motion (motion-find (val motion_name))))
- The extended example in Appendix A gives a non-trivial example of a semaphore wait.
12 Execution View of a PaT-Net
PaT-Nets execute in the context of the Jack 3D graphics modeling and simulation package developed at the University of Pennsylvania. Briefly, transitions between nodes and action execution take place at the rate (commonly referred to as the frame-rate) at which the simulation updates. In real-time simulation, the frame-rate is $\frac{1}{50}$ seconds, though in practice this rate is much slower, perhaps between .5 and 5 seconds depending on the complexity of the simulation. For now, we will treat the frame-rate as a fixed unit of time independent of any particular simulation and refer to its units as clock ticks.
When instantiated, a PaT-Net is placed on the active list, a list of active PaT-Nets in the current simulation environment. This list is maintained for the duration of a Jack session; it may be cleared using the (reset-fsm) command described in Appendix D.
This section will describe in detail the execution of PaT-Nets both individually and in parallel; for additional detail about the PaT-Net structure, see Appendix D.
12.1 Executing a Single PaT-Net
When instantiated, a PaT-Net executes its initialization phase, instantiating local variables and executing the arbitrary LISP code associated with the initialization phase. Furthermore, it is added to the active list, and will enter its start node on the following simulation tick.
On each subsequent tick, the following steps take place:
- Each of the PaT-Net’s monitors are checked. Currently, only the first monitor whose associated condition returns true has its action executed, however in Jack 6.0 the PaT-Net formalism will be extended to include multiple monitor execution.
- If the action associated with the current node has not been executed, then it is executed.
- The PaT-Net’s waits are polled. If all wait conditions return non-nil, then execution continues; otherwise, the PaT-Net passes execution and its waits will be checked again on the following frame. Waits which return non-nil are removed from the list of waits.
- The PaT-Net queries the node for a transition. In the case of a probabilistic node, this requires the generation of a random value which is checked against the weights of each of its arcs. In the case of a simple node, each of the arcs’ conditions are checked in order until one returns true, and the associated transition is taken.
- If no transition is taken, then no transition is made from the node. (The PaT-Net will not execute another action until it makes a transition.)
- If any waits are posted, they are added to an active wait list, which will be checked on every following tick.
Figure 1: A Simple PaT-Net. Script letters indicate the type of node: S for simple, P for probabilistic, R for random, and W for weighted. Node names appear in bold and actions to be executed appear directly below node names. Conditions and weights are attached to transitions (arrows) and are designated by italics.
12.2 Example Execution of a Simple PaT-Net
Consider the PaT-Net displayed in Figure 1. This PaT-Net represents a very simple robot controller for navigating a maze. A sample environment for the robot is given in Figure 2; one could imagine testing the weights of given probabilities to see what differing results occurred in the traversal of the maze. In any case, the following example will show the motion of the robot through the maze according to the PaT-Net of Figure 1.
Figure 2: The PaT-Net and environment after the initialization phase. The dash-bordered node is the current node in the left diagram; the figure at the right shows the environment.
After the initialization phase of this PaT-Net enters its start node (Figure 2) and begins moving forward. In the absence of obstacles, this PaT-Net will locomote the robot forward
forever; in this simulation, a maze, this structure is appropriate.
Figure 3: When it nears a wall, the robot will stop and entertain a number of options. The PaT-Net will be in the state depicted in the left figure; the current state is indicated by the dashed-border. A sample environment is shown on the right.
The robot locomotes until it encounters its first wall, when it must make a transition to the options node (Figure 3); the environment at this point is also displayed. This node is probabilistic: for purposes of discussion, we'll suppose that the follow node is the turn node.
After making a transition to the turn node (see Figure 4), where no action is taken, a transition is selected randomly from the possible transitions out of the node.
Figure 4: The PaT-Net after a transition to the turn node. The dash-bordered node is the current node.
Suppose the transition to the left90 node is taken. After making this transition, the PaT-Net is in the state as shown in Figure 5. After executing the associated action of the node, the environment should look something like that shown in Figure 5.
Figure 5: The PaT-Net and environment after a random transition to the *left90* node. The dash-bordered node is the current node; the figure on the right displays the environment after the execution of the action associated with the node.
### 12.3 Parallel Execution
As mentioned above, PaT-Nets are added to an *active list* as they are instantiated. This list of active PaT-Nets is maintained throughout a simulation; only a single active list may exist in a single *Jack* session.
PaT-Nets exhibit parallelism in a very restricted sense: each PaT-Net executes one action and transitions to another node in every simulation step (assuming that the PaT-Net isn't waiting). Thus, if three PaT-Nets are instantiated at time 0, then at the first tick, each PaT-Net will execute the action in its initial node. The actions of each of these PaT-Nets will occur *serially*, in the order in which they were added to the active list (i.e. the order in which they were instantiated).

**Figure 6:** Three simple PaT-Nets.
Figure 6 shows three simple PaT-Nets to be instantiated in a simulation. PaT-Nets 1
and 2 will be instantiated on clock tick 0, and PaT-Net 3 will be instantiated on clock tick 2.
At time 0, PaT-Nets 1 and 2 are instantiated in that order. PaT-Net 1 executes its initialization phase and is added to the active list; then PaT-Net 2 executes its initialization phase and is added to the end of the active list.

Figure 7: Three simple PaT-Nets immediately after the start of a simulation. Dashed borders reflect the current node of the PaT-Net.
At time 1, PaT-Nets 1 and 2 will both enter their initial states, as depicted in Figure 7. However, they will do this in the order in which they appear in the active list. PaT-Net 1 will execute action :a₁₁ first; once a transition has been selected (for example, to node n₁₂), the PaT-Net will pass execution to PaT-Net 2. PaT-Net 2 will execute the action :a₂₁ and make a transition (for example, to node n₂₄) and pass execution. Since there are no more active PaT-Nets on the active list, the simulation will continue.
At time 2, PaT-Nets 1 and 2 both continue execution by executing the actions associated with their current nodes. PaT-Net 1 will first execute action :a₁₂ and select a transition (to node n₁₃); then PaT-Net 2 will execute action :a₂₄ and select a transition (to node n₂₃). Remember that PaT-Net 3 is to be instantiated on this step; we will assume that this happens last (perhaps because it was instantiated in the action :a₂₄ or by user input). PaT-Net 3 executes its initialization phase and execution continues.
At time 3, all three PaT-Nets continue execution. PaT-Net 1 executes action :a₁₃, then selects a transition. Then PaT-Net 2 repeats this process, executing action :a₂₃ and selecting a transition. Finally, PaT-Net 3 executes action :a₃₁ and selects a transition. Execution continues throughout the simulation.
Figure 8: The three simple PaT-Nets at clock tick 2. Dashed borders reflect the current node of the PaT-Net.
A An Example PaT-Net
B The DEFNET Macro
C Semaphores
D Other Random Nonsense
Figure 9: The three simple PaT-Nets at clock tick 3. Dashed borders reflect the current node of the PaT-Net; note that PaT-Net 3 has just become active.
|
{"Source-Url": "http://www.dtic.mil/dtic/tr/fulltext/u2/a395660.pdf", "len_cl100k_base": 12588, "olmocr-version": "0.1.53", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 36584, "total-output-tokens": 14219, "length": "2e13", "weborganizer": {"__label__adult": 0.0002644062042236328, "__label__art_design": 0.0003654956817626953, "__label__crime_law": 0.00016689300537109375, "__label__education_jobs": 0.0008273124694824219, "__label__entertainment": 8.368492126464844e-05, "__label__fashion_beauty": 0.0001118183135986328, "__label__finance_business": 0.00020015239715576172, "__label__food_dining": 0.0002567768096923828, "__label__games": 0.0009279251098632812, "__label__hardware": 0.0015659332275390625, "__label__health": 0.0002512931823730469, "__label__history": 0.000225067138671875, "__label__home_hobbies": 9.489059448242188e-05, "__label__industrial": 0.0005125999450683594, "__label__literature": 0.00015842914581298828, "__label__politics": 0.00015747547149658203, "__label__religion": 0.00029540061950683594, "__label__science_tech": 0.034027099609375, "__label__social_life": 7.045269012451172e-05, "__label__software": 0.0137939453125, "__label__software_dev": 0.94482421875, "__label__sports_fitness": 0.00025534629821777344, "__label__transportation": 0.0004470348358154297, "__label__travel": 0.00014519691467285156}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52417, 0.02116]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52417, 0.72206]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52417, 0.88402]], "google_gemma-3-12b-it_contains_pii": [[0, 1032, false], [1032, 1181, null], [1181, 1851, null], [1851, 5161, null], [5161, 8311, null], [8311, 10780, null], [10780, 10811, null], [10811, 12392, null], [12392, 14252, null], [14252, 15973, null], [15973, 18160, null], [18160, 19637, null], [19637, 21840, null], [21840, 23520, null], [23520, 25661, null], [25661, 27718, null], [27718, 29504, null], [29504, 31164, null], [31164, 33009, null], [33009, 34904, null], [34904, 36556, null], [36556, 38621, null], [38621, 40603, null], [40603, 42696, null], [42696, 44188, null], [44188, 46837, null], [46837, 47996, null], [47996, 49111, null], [49111, 50233, null], [50233, 52071, null], [52071, 52265, null], [52265, 52417, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1032, true], [1032, 1181, null], [1181, 1851, null], [1851, 5161, null], [5161, 8311, null], [8311, 10780, null], [10780, 10811, null], [10811, 12392, null], [12392, 14252, null], [14252, 15973, null], [15973, 18160, null], [18160, 19637, null], [19637, 21840, null], [21840, 23520, null], [23520, 25661, null], [25661, 27718, null], [27718, 29504, null], [29504, 31164, null], [31164, 33009, null], [33009, 34904, null], [34904, 36556, null], [36556, 38621, null], [38621, 40603, null], [40603, 42696, null], [42696, 44188, null], [44188, 46837, null], [46837, 47996, null], [47996, 49111, null], [49111, 50233, null], [50233, 52071, null], [52071, 52265, null], [52265, 52417, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52417, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52417, null]], "pdf_page_numbers": [[0, 1032, 1], [1032, 1181, 2], [1181, 1851, 3], [1851, 5161, 4], [5161, 8311, 5], [8311, 10780, 6], [10780, 10811, 7], [10811, 12392, 8], [12392, 14252, 9], [14252, 15973, 10], [15973, 18160, 11], [18160, 19637, 12], [19637, 21840, 13], [21840, 23520, 14], [23520, 25661, 15], [25661, 27718, 16], [27718, 29504, 17], [29504, 31164, 18], [31164, 33009, 19], [33009, 34904, 20], [34904, 36556, 21], [36556, 38621, 22], [38621, 40603, 23], [40603, 42696, 24], [42696, 44188, 25], [44188, 46837, 26], [46837, 47996, 27], [47996, 49111, 28], [49111, 50233, 29], [50233, 52071, 30], [52071, 52265, 31], [52265, 52417, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52417, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
1e631cc0ffbf87689ecb8db6995ed5632a01d596
|
Early detection of design faults relative to requirement specifications in agent-based models
Yoosef Abushark*
RMIT University
Melbourne, Australia
yoosef.abushark@rmit.edu.au
John Thangarajah
RMIT University
Melbourne, Australia
john.t@rmit.edu.au
Michael Winikoff
University of Otago
Dunedin, New Zealand
michael.winikoff@otago.ac.nz
Tim Miller
University of Melbourne
Melbourne, Australia
tmiller@unimelb.edu.au
James Harland
RMIT University
Melbourne, Australia
james.harland@rmit.edu.au
ABSTRACT
Agent systems are used for a wide range of applications, and techniques to detect and avoid defects in such systems are valuable. In particular, it is desirable to detect issues as early as possible in the software development lifecycle. We describe a technique for checking the plan structures of a BDI agent design against the requirements models, specified in terms of scenarios and goals. This approach is applicable at design time, not requiring source code. A lightweight evaluation demonstrates that a range of defects can be found using this technique.
Categories and Subject Descriptors
D.2.10 [Software Engineering]: Design—methodologies
General Terms
Reliability; Algorithm; Design
Keywords
AOSE; Requirements specification; multi-agent systems
1. INTRODUCTION
Software systems based on autonomous agents are used in a large number of applications in which the domain is highly dynamic [17, 13]. A popular model for such development is the paradigm known as the Belief-Desire-Intention (BDI) model [27], which has been used as the basis for a number of agent programming languages, such as JACK, Jason and JadeX [4]. These have been used in application areas such as robotics, automated manufacturing, financial management and flight management.
There are a number of methodologies for the development of BDI systems (see [31] for a recent survey). Many of these share a common set of design concepts, usually modelling the requirements of a system by use cases and goals. These are then used to develop plans which achieve these goals, according to the process appropriate to each methodology.
The complexity of the systems developed provides a natural motivation for verification methods to be applied to such systems. A large amount of existing work on verifying BDI agent systems focuses on formal verification [10], particularly using model checking techniques [12] and theorem proving [28], or on runtime testing [23]. These methods can generally only be applied once the application has been fully developed, as they require complete agent programs to be written, and then analysed.
It has long been established in software engineering that early detection and resolution of software defects saves time and money [3, Page 1466]. However, comparatively little work has been done on the development of methods for detection of defects in BDI systems during the design phase. There is some support for such methods in Tropos [8], which provides methods for verifying formal requirements, and for reasoning with formal models of goals. However, there is no method provided for checking the artifacts developed during the detailed design phase against the original requirements. INGENIAS [26] provides a mechanism for checking the execution of agent programs against design artifacts, but clearly this requires the programs to be written prior to the verification.
This work is the full version of an earlier extended abstract [2], and provides detail, formalisation, and evaluation. The aim of this work is to develop a suite of techniques which can be used to detect defects in BDI systems during the design phase, i.e. prior to implementation. In our previous work, we developed techniques for checking the functional correctness of agent-based designs with respect to communication protocol models [1]. In this paper, we build on that work and develop a technique for checking the functional correctness of agent designs with respect to requirements models. As with [1], our approach requires only design-phase models, and no code.
We propose a mechanism, grounded in the Prometheus methodology [24], for checking that the detailed plans conform to the requirements specified in terms of scenarios (the use-case representation in Prometheus) and goals. It is worth noting that what we are proposing goes beyond the simple static consistency checks that tools such as the Prometheus Design Tool (PDT) [21] perform, as our proposal considers the dynamic behaviour of a system. We chose the Prometheus methodology due to our expertise in it and the ease of access to the supporting tool [21]. However, we believe our approach is generalisable to other BDI methodologies.
A preliminary evaluation of this technique demonstrates that it...
can find a range of defects in agent designs. However, further work is required to detect superfluous design elements without raising a high number of false positives.
This paper is organised as follows. Section 2 introduces the necessary background. Our approach to checking the requirements specification is detailed in Section 3, and a (limited) evaluation of its scalability and effectiveness is discussed in Section 4. A brief comparison to related work is presented in Section 5, and we conclude with discussion and future work in Section 6.
2. BACKGROUND
We now briefly introduce the relevant parts of the Prometheus models, using the conference management system [22] as a running example. This system helps in managing the different phases of the conference review process, including submission, review, decision and paper collection. In the submission phase, the system should be able to assign a number to each submission and provide receipts to authors. After the specified submission deadline, the system assigns papers to the reviewers, who review the paper. After receiving the reviews, the system supports making decisions on whether to accept or reject each paper, notifying the authors. Then, the system collects the accepted papers and prints them as conference proceedings.
A fundamental aspect of any software engineering methodology is the specification of requirements. In agent-oriented software engineering (AOSE), requirements specifications generally include scenarios, which are instances of the desired execution behaviour, and goals, which are intended states of the system. In the Prometheus methodology, scenarios consist of a sequence of steps, where each step can be an action (i.e. something an agent does), a percept (i.e. an input from the environment), a goal to achieve, or a sub-scenario.1 Each step is associated with a role. Figure 1 shows a scenario for the conference management system. Note that the aim of the scenario is to capture an example trace through the system’s behaviour, and it therefore does not specify a complete set of execution traces. However, as we shall see, we can use the information in scenarios and goal overview diagrams to construct constraints that must be met by the detailed design.
Goals are commonly modelled using a goal diagram that shows the relationship between goals, including how goals are decomposed into sub-goals, and whether the relationship is disjunctive (a parent goal is achieved if one of its children is achieved, “OR”), undirected conjunctive (a parent goal is achieved if all its children are achieved in some, unspecified, order, “undirected-AND”), or directed conjunctive, i.e. sequential (a parent goal is achieved if all its children are achieved in a specified order, “directed-AND”). Figure 2 shows the goal overview diagram for the conference management system, which outlines the goals and sub-goals required to successfully review the papers. The notation used distinguishes between undirected-AND (“AND”) and directed-AND by using dashed arrows to indicate the ordering constraints, e.g. Invite Reviewers to CollectPrefs)
During the design process, roles are assigned to the agents in the system. For example, we assign the two roles ‘Review Management’ and ‘Assignment’ to the ‘Review Manager’ agent. Scenarios are realised by designing the agents that are assigned roles that are involved in the scenario. Thus, the ‘Review Manager’ agent should be designed in a way to cover all steps that are associated with the ‘Review Management’ and ‘Assignment’ roles.
The internals of agents are modelled in terms of goals, actions, percepts, and messages, which are associated with plans. Each agent type has a detailed design diagram that shows its plans, the trigger for each plan (a percept, message or goal), and the actions performed, messages sent and subgoals posted by each plan.
3. TECHNICAL APPROACH
To check the agent designs (i.e. the detailed structure of plans within agents), we compare all possible executions of the agent designs against the desired traces specified by the scenarios. We transform the design models from Prometheus-specific informal models into Petri nets. This has two benefits. First, it generalises the approach, making it applicable to other methodologies. Second, it allows us to leverage existing tools and techniques. Specifically, we transform scenarios, with additional information from the goal overview diagram, into Petri nets, and also translate agent designs into a Petri net. We then verify that all traces of the design Petri net are valid with respect to the scenario Petri net.
Our process takes a design file as input, and outputs a report of potential defects in the design. The process has three steps (see Figure 3):
1. **Transforming specification models into Petri nets** (Section 3.1)
In addition to considering the scenario, we also need to consider the goal overview diagram because a goal in the scenario may be realised in the agent design by achieving its sub-goals, or through its parent.
2. **Extracting all possible execution traces from agent designs**
(Section 3.2): For each scenario, we automatically construct a plan graph [16] from the agents’ detailed designs, which is an intermediate structure that defines the control flow between and within plan structures over all of the agents. We use information from both the scenario (to determine the starting point for the plan graph) and assignment of roles to agents $G_1$ and ... $G_n$, which can map scenario steps, which are assigned to roles, to the correct agents.
3. Executing design traces against the Petri nets (Section 3.3): We check each of the possible traces of the design’s Petri net against the scenario Petri net, and note any discrepancies, such as a failure in executing the Petri net that was due to an incorrect ordering between goals in the detailed design.
3.1 Transforming Scenarios to Petri nets
The first step of the process is translating the scenario into a Petri net, taking into account the goal overview diagram. Although a scenario is a single sequence of steps, the result is a set of sequences, because a goal step can be realised in the detailed design by implementing its children (more generally, its descendants), or its parent. For example, the goal step Invite Reviewers in Figure 1 could be implemented through its children, Invite_Reviewer_Via_Email or Invite_Reviewer_Via_Portal (see Figure 2).
In our approach, we translate scenarios to a variant of Petri net control fragments including: Choice, Parallel and Sequence.
When mapping a goal step we need to consider its parent and its children. To model the possibility that a goal step in a scenario could be realised by implementing its parent goal, we map a goal $G$ with parent $P$ as a choice fragment, with the goal $G$ as one option in the choice, and $P$ as the other option (except when $P$ is OR decomposed - see below). For example, in Figure 4 the goal Collect_Prefs is in a choice fragment with its parent, the goal Review. For completeness, we should include not just the parent goal, but all ancestor goals. However, in practice, it would be highly unusual for a scenario step to be implemented in terms of its grandparent, since the whole scenario step was ’Invite_Reviewer_Via_Email’. In this case we want to honour that choice, and not allow the design to realise the goal in terms of its parent.
We also need to consider the child goals of a scenario goal step. If the goal has no children, the goal is mapped simply as an alternative with its parent. However, there are three different cases for goals with children:
1. OR-composed children: The goal, $G$, has children $G_1$ OR $G_2$, ..., OR $G_n$. In this case, the mapping is to an alternative between the goal $G$, its parent (if there are no OR siblings), or one of its children.
2. Undirected-AND-composed children: The goal, $G$, has children $G_1$ AND $G_2$, ..., AND $G_n$. In this case, the mapping is to an alternative between the goal $G$, its parent, or ALL of its children, which can be achieved in parallel.
3. Directed-AND-composed children: The goal, $G$, has children $G_1$ AND $G_2$, ..., AND $G_n$. In this case, the mapping is to an alternative between the goal $G$, its parent, or ALL of its children in the sequence specified.
For example, in Figure 2, the goal Invite Reviewers is OR-decomposed with two children, and so in Figure 4, it is mapped to a choice with its parent (‘Review’), and with its children, where the two children are in choice with each other.
We now formalise the translation. Let $G$ be the goal corresponding to the goal step being mapped, let parent($G$) denote its parent, children($G$) denote its children as a sequence of names (where the order is the order of execution for a directed-AND decomposition, and is arbitrary otherwise), and let $\text{decompose}(G)$ denote the decomposition type of $G$, i.e., one of LEAF, OR, AND (undirected-AND), SEQ (directed-AND). For brevity we also define a simple textual notation for depicting Petri net control fragments: a name is short hand for a step and we use $\text{seq}(p_1; \ldots; p_m)$ to denote the Petri net where the $p_i$ are joined sequentially: $\text{choice}(p_1; \ldots; p_m)$ to denote the Petri net where there is a choice, and exactly one of the $p_i$ is selected; and $\text{par}(p_1; \ldots; p_m)$ to denote the Petri net where all the $p_i$ are triggered to run in parallel.
We map a scenario consisting of steps named $S_1, \ldots, S_n$ to the Petri net denoted by $\text{seq}(\hat{S}_1; \ldots; \hat{S}_n)$. If $S_i$ is an action or percept then $\hat{S}_i = S_i$. If $S_i$ is the name of a goal step then $\hat{S}_i$ depends on the decomposition type of $G$, formalised as:
$$
\hat{G} = \begin{cases}
\text{choice}(\overline{G}) & \text{if } DG = \text{LEAF} \\
\text{choice}(\overline{G}; C) & \text{if } DG = \text{OR} \\
\text{choice}(\overline{G}; \text{par}(\overline{G})) & \text{if } DG = \text{AND} \\
\text{choice}(\overline{G}; \text{seq}(\overline{G})) & \text{if } DG = \text{SEQ} \\
\end{cases}
$$
where $DG = \text{decompose}(G)$ and $(G_1, \ldots, G_n) = \text{children}(G)$ and $M = G_1; \ldots; G_n$.
We also define the auxiliary function $\overline{\text{G}}$, which maps the scenario step itself, $G$, to parent($G$), $G$, and all other goals to just themselves. This is used to allow $\hat{S}_i$ to be applied recursively to the descendants of $G$ without introducing parents of descendants. The definition of $\overline{\text{G}}$ has a special case where the scenario step being mapped is a specific child of an OR-decomposed goal (e.g. if the scenario step was ’Invite_Reviewer_Via_Email’). In this case we want to honour that choice, and not allow the design to realise the goal in terms of its parent.
$$
\overline{G} = \begin{cases}
G & \text{if } G \text{ is the scenario step being mapped and } \text{decompose}(\text{parent}(G)) \neq \text{OR} \\
G & \text{otherwise} \\
\end{cases}
$$
This definition can be easily implemented, and for the running example, yields seq(Review Phase ; choice( Invite Reviewers ; Review ; Invite_Reviewer_Via_Email ; Invite_Reviewer_Via_Portal ) ; Send_Invitations ; Reviewer_Preferences ; choice( Collect Pref ; Review ) ; choice( Assign Reviewers ; Review ) ; Give_Assignments ; Review_Report ; choice( Collect Reviews ; Review ) ; choice( Get PC Opinions ; Review ) ), the start of which is shown in expanded form in Figure 4.

3.2 Extracting Execution Traces
To verify a particular scenario against the designs of the agents involved in that scenario, we extract all possible execution traces that the agents can realise for the scenario extending the work of [1]. It is not unusual that a design of a scenario is scattered across multiple agents, since roles that are associated with steps of the scenario might be assigned to multiple agents. As a result, the extraction of the execution traces may require considering the detailed designs of multiple agents together. However, in the scenario we are using as an example, only a single agent is involved (the Review Manager agent).
3.2.1 Merging multiple agent designs
Our starting point is a detailed design, which consists of, for each agent, a collection of plans. Each plan has a defined trigger, which can be a goal, message, or percept. Plans can create sub-goals, send messages, and perform actions. A detailed design can be represented as a graph with distinguishable node types for actions, percepts, goals, messages and plans, and with edges between nodes indicating relationships (e.g. a plan posting a sub-goal, or a plan being triggered by a percept).
We create a plan graph [16] from the detailed design by starting with the entity that corresponds to the first step of the scenario, and then recursively traversing links in the agent designs. These links may be spread over several agents; for example, via the sending of a message. Therefore, the extracted plan graph is a subset of the agents’ (merged) designs.
There are three specific challenges that need to be addressed, and that require a deviation from a simple subset of the agents’ designs. The plan graph is based on the work of Miller et al. [16]. However, Miller et al. define a plan graph with respect to an interaction protocol, so their plan graphs capture only the relationship between plans and messages. By contrast, we are interested in the relationship between plans and actions, percepts, messages, and goals. This introduces additional challenges.
First, there may not be a single entity that corresponds to the first step of a scenario. If the first step is an abstract goal, then a subset of the goal’s descendants could start the scenario, meaning there may be a number of possible starting points in the scenario:
1. **OR-composed children**: In this case, the starting point is the goal or one of its children. The plan graph is derived by following links from each of the possible starting points, and then having these starting points be alternatives.
2. **Undirected-AND children**: In this case, the starting point is any of the sub-goals, but all sub-goals must occur. The plan graph is derived by introducing a dummy plan that links to all of the sub-goals, and that dummy plan is triggered by the start of the process.
3. **Directed-AND children**: The first sub-goal in the sequence is the starting point for the plan graph.
Figure 5 presents examples of each of these relationships, and their corresponding plan graphs, where G is the (abstract) goal that is the first step of the scenario being considered.
Second, we need to deal with actions. In a detailed design, an action is not followed by another step (does not have any outgoing arcs), and hence terminates the plan graph. However, in scenarios an action does not always end the process. Thus, an action step in the scenario creates a “gap” in the plan graph relative to the scenario. For example, in the Review scenario the Send_Invitations action creates a gap, since, in the detailed design, there are no outgoing arcs from the action, but the action is not the end of the scenario. We rectify this by using the scenario to “bridge the gap”.

If an action is not the final step of the scenario, then we use the steps defined in the scenario to determine the link to continue the flow of the plan graph. For example, if the step following an action is a percept, then we use the percept as a continuation of the plan graph, and if it is a goal then we use the goal. We add a dashed link from the action to the corresponding continuation point. For instance, Reviewers_Preferences follows Send_Invitations in the scenario, so we add a dashed link from the Send_Invitations action to the Reviewers_Preferences percept in Figure 6a. This approach also applies when the first step of a scenario is an action.
Third, it is possible for the first step to be assigned to a role that is associated with multiple agents, meaning that multiple plan graphs need to be considered. We therefore consider the detailed designs of all agents that are linked to that role, deriving multiple plan graphs, and positioning each plan graph as an alternative. Thus the starting nodes of each plan graph will be children of a single starting node to form one large plan graph from all designs.
Figure 6a shows the plan graph corresponding to the design of the Review Manager agent, which fulfils the role from the Review scenario. For brevity, we omit the agent internal design from which the plan graph was extracted.
3.2.2 Extracting execution traces from the plan graphs
Plan graphs are structures that show the static view of agents with respect to a particular scenario. Each path through a plan graph represents one execution trace of the system, and each of these traces should conform to the requirements specified by the scenario.
To execute traces, we translate the plan graph into a Petri net, and then use the standard reachability graph construction [18] to obtain all possible traversals of the plan graph. Translating the plan graph to a Petri net is straightforward: plans are mapped to transitions, and other node types are mapped to places. Edges between nodes are mapped across. However, there are a few exceptions to this.
First, dashed edges, which are from an action to a percept, are handled by creating a new transition node, which sits in between the two place nodes (e.g. LinkT1 and LinkT2 in Figure 6b).
Second, if the first node in the plan graph is a plan, then we create a start node (place) that links to it. However, if the first node is not a plan, then we create a start node (place) that links to a new transition called StartT that links to the first node. As noted earlier, there can also be cases where there are a number of possible alternative starting nodes. In this case we create for each possible starting point that is not a plan a corresponding transition, and the Start place node links to each of these transitions.
Third, when a plan posts multiple steps (e.g. goals or actions), the order is not specified in the design. In particular, with subgoals, the ordering of the steps to achieve those subgoals may be inter-
leaved. Therefore, we treat these steps of a plan as if they were executed in parallel to allow for the different possible interleavings – that is, we create a separate asynchronous process for each step. The synchronisation fragment in Figure 6b represents this process. Without this fragment the steps will not be executed concurrently, and hence all traces will capture the same order between the respective steps. For instance, without the sync parts in Figure 6b, a token would be simultaneously deposited on InviteReviewerViaEmail and InviteReviewerViaPortal, resulting in all traces with this order, whilst the plan graph does not specify such an order.
Finally, we exclude the plans that handle the last entities in the plan graph, as they do not affect the trace (the scenario does not include plans), and would result in transitions without output places. Figure 6b shows the Petri net resulting from translating the plan graph of Figure 6a.
After transforming the plan graph into a Petri net, we need to extract all possible trace paths for that Petri net. This is done using the reachability graph of the Petri net, which is a directed graph that shows all reachable states of the Petri net.
### 3.3 Execution and Reporting
The previous steps have resulted in a Petri net $N_S$ that corresponds to the scenario, taking into account the possibility of goals being realised through their parent or descendant goals, and another Petri net $N_P$ that corresponds to the plan graph for that scenario. In this step, we take each trace from the reachability graph of $N_P$, and check it against $N_S$. Any cases where the trace does not correspond to an execution of $N_S$ is reported.
The possible traces are extracted by traversing the reachability graph using a standard depth-first search. Each path of the reachability graph represents a possible trace of $N_S$ that corresponds to the scenario, taking into account the possibility of goals not included in $N_S$. Given a trace $\hat{S}$ of the form $S_1, S_2, \ldots, S_m$ where each $S_j$ is the name of a step, we perform the following process: (1) set $j$ to 1; (2) place a token on the place in $N_S$ corresponding to $S_j$; (3) if there are no enabled transitions, and the execution is not at a termination state then this indicates an error, otherwise repeatedly fire enabled transitions in $N_S$ until there are no more enabled transitions; (4) if $j = m$ then stop, otherwise increment $j$ by 1 and go to (2).
A failure in firing a transition (in step 3) indicates a defect in the design with respect to the scenario. A trace is considered successful when its execution consumes all entities and hits a termination state of $N_S$. Based on the execution of all traces on the Petri net, the framework provides informative feedback about agent detailed designs with respect to a particular scenario. Table 1, modified from [1], lists possible failures and their causes.
For example, consider Figure 6a, which contains four intentionally seeded defects: the plan (Invite Reviewers) posts two subgoals which should be an ‘OR’ decomposition, yet as specified in the design they are considered as ‘AND’ decompositions; a missing scenario step (Assign Reviewers) goal step); and introducing two new entities (HandleAmbiguity and SendClarification) actions that result in the existence of some traces that only cover part of the scenario.
After executing the 12,951 traces of $N_P$, four defects in the design were revealed: one inconsistent ordering, one missing step and two incomplete paths. For instance, Review Phase, Invite_Reviewer_Via_Email, Send_Invitations, Preferences, Collect Pref, and Give Assignments . . . is one of the traces of $N_P$. The execution of $N_S$ would be terminated at the transition that is associated with the Assign Reviewers goal step place, since it is missing in the trace. Since that the execution was terminated without reaching a termination place, an error was recorded.
### 3.4 Tool Support
We have implemented the proposed approach as an eclipse plug-in that integrates with the Prometheus Design Tool (PDT). The plug-in takes the design as an XML file, and asks the user to select a scenario to analyse. It then generates: (1) the requirements Petri net $N_S$; (2) the plan graph; (3) filtered execution traces; and
- Recall that this goal has been deliberately removed from Figure 6b.
Table 1: Categorisation of causes for failures
<table>
<thead>
<tr>
<th>Failure (executing specification Petri net)</th>
<th>Cause (in plan graph)</th>
</tr>
</thead>
<tbody>
<tr>
<td>1. The remaining trace is empty, but the</td>
<td>1. The trace contains fewer steps than it should, relative to the scenario.</td>
</tr>
<tr>
<td>Petri net has not terminated (there is</td>
<td>2. The plan graph trace contains more steps than it should, relative to the scenario.</td>
</tr>
<tr>
<td>no token in a termination place).</td>
<td></td>
</tr>
<tr>
<td>2. The Petri net has terminated, but the</td>
<td></td>
</tr>
<tr>
<td>remainder of the trace is non-empty.</td>
<td>3.(a) The step that needs to be executed is missing in the trace; or</td>
</tr>
<tr>
<td>3. A token is placed into the Petri net,</td>
<td>3.(b) The ordering between steps within the trace is inconsistent with</td>
</tr>
<tr>
<td>but the Petri net cannot be executed.</td>
<td>the scenario.</td>
</tr>
</tbody>
</table>
(4) a textual report that lists potential defects in agent designs.
4. EVALUATION
In this section we evaluate the framework first with respect to its scalability as the number of goals and plans in the design increases, and second with respect to its effectiveness in detecting errors.
4.1 Scalability evaluation
In the first part of the evaluation we examine how well the proposed approach scales as the size of the agent design grows. The complexity of our approach rests on the trace extraction from the resulting plan graphs, in terms of its size, but more importantly, from the level of parallelism that it contains. Therefore, we generate synthetic plan graphs systematically varying the size and the amount of parallelism up until the time taken to extract the traces are still “reasonable”. We define “reasonable” to be within one calendar day.
4.1.1 Experiment design
In terms of the process, we first generate synthetic plan graphs that are a combination of plans and other design entities including goals, messages, actions and percepts. We generated a total of 21 different plan graphs using the systematic process described below.
We extracted and executed the traces checking for conformance recording the following measures: (i) the number of traces corresponding to a plan graph; (ii) the time taken to extract all traces of plan graph; and (iii) the time taken to execute all traces against the requirements Petri net model.
Plan graph generation. In order to increase the size of the plan graph, we increase the number of the design entities including plans, actions, percepts, goals and messages. For simplicity, rather than generating graph structures we generate trees (i.e., a single root and acyclic). However, for consistency we will continue to refer to them as plan graphs.
Plan graphs capture two control fragments: choice and parallel. It is common for plan graphs to capture both control types of fragments, so we defined the following systematic process to generate a variety of plan graphs while systematically increasing the scale of the graphs.
1. We started all plan graphs with one plan that is linked to a number of posted entities (parallelism).
2. The types of each branch (choice or parallelism) was the opposite of its parent.
3. The number of nodes $N_L$ at a level $L$ is $N_L = N_{L-1} + c$, in which $N_{L-1}$ is the number of nodes at the parent level, and $c$ is a constant.
4. All nodes had one child, except the left most node, which had $c + 1$ children.
We created 21 plan graphs with different sizes, by varying the breadth and depth of the graph as illustrated in Table 2. The
<table>
<thead>
<tr>
<th>Case</th>
<th>Breadth</th>
<th>Depth</th>
<th>#Paths</th>
<th>#Plans</th>
<th>#Nodes</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>2</td>
<td>1</td>
<td>0</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>2</td>
<td>2</td>
<td>2</td>
<td>4</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>3</td>
<td>2</td>
<td>3</td>
<td>6</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>4</td>
<td>2</td>
<td>4</td>
<td>8</td>
<td>19</td>
<td>20</td>
</tr>
<tr>
<td>5</td>
<td>2</td>
<td>5</td>
<td>10</td>
<td>26</td>
<td>27</td>
</tr>
<tr>
<td>6</td>
<td>2</td>
<td>6</td>
<td>12</td>
<td>34</td>
<td>35</td>
</tr>
<tr>
<td>7</td>
<td>2</td>
<td>7</td>
<td>14</td>
<td>43</td>
<td>44</td>
</tr>
<tr>
<td>8</td>
<td>2</td>
<td>8</td>
<td>16</td>
<td>53</td>
<td>54</td>
</tr>
<tr>
<td>9</td>
<td>2</td>
<td>9</td>
<td>18</td>
<td>64</td>
<td>65</td>
</tr>
<tr>
<td>10</td>
<td>2</td>
<td>10</td>
<td>20</td>
<td>69</td>
<td>70</td>
</tr>
<tr>
<td>11</td>
<td>3</td>
<td>1</td>
<td>1</td>
<td>3</td>
<td>4</td>
</tr>
<tr>
<td>12</td>
<td>3</td>
<td>2</td>
<td>3</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>13</td>
<td>3</td>
<td>3</td>
<td>5</td>
<td>13</td>
<td>14</td>
</tr>
<tr>
<td>14</td>
<td>3</td>
<td>4</td>
<td>7</td>
<td>22</td>
<td>23</td>
</tr>
<tr>
<td>15</td>
<td>3</td>
<td>5</td>
<td>9</td>
<td>33</td>
<td>34</td>
</tr>
<tr>
<td>16</td>
<td>3</td>
<td>6</td>
<td>11</td>
<td>46</td>
<td>47</td>
</tr>
<tr>
<td>17</td>
<td>3</td>
<td>7</td>
<td>13</td>
<td>61</td>
<td>62</td>
</tr>
<tr>
<td>18</td>
<td>4</td>
<td>1</td>
<td>1</td>
<td>4</td>
<td>5</td>
</tr>
<tr>
<td>19</td>
<td>4</td>
<td>2</td>
<td>3</td>
<td>8</td>
<td>9</td>
</tr>
<tr>
<td>20</td>
<td>4</td>
<td>3</td>
<td>5</td>
<td>18</td>
<td>19</td>
</tr>
<tr>
<td>21</td>
<td>4</td>
<td>4</td>
<td>7</td>
<td>31</td>
<td>32</td>
</tr>
</tbody>
</table>
As is shown in Table 2, by varying the size of a plan graph, we vary the size of the agent design. For instance in case 3, the plan graph is of breadth 2 and depth 3 which results in a design with 8 plans and 9 other nodes (actions, percepts, goals and messages). In case 10, with depth 10, the design had 64 plans and 65 other nodes. We incremented the breadth and depth by 1 for each case, omitting cases for which execution took more than one day (e.g. breadth...
3, depth 8, and breadth 4, depth 5).
**Execution environment.** We ran all the experiments on a desktop running a 64-bit Intel core i7 processor clocked at 3.4 GHz. 1 GB of RAM is dedicated to be used by the Java Virtual Machine. We ran no other tasks on the machine. We ran each case 6 times, and took the average time for both extracting and executing all traces.
### 4.1.2 Results
Table 3 shows our findings. We see that the number of traces grows exponentially as the plan graph increases in size, as expected. Similarly, we see that the extraction time is proportionally to the number of traces. However, the extraction time, which also grows proportionally to the number of traces, is significantly lower than the execution time.
<table>
<thead>
<tr>
<th>Case</th>
<th>B</th>
<th>D</th>
<th>#Traces</th>
<th>Execution (in seconds)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Case 1</td>
<td>2</td>
<td>1</td>
<td>2</td>
<td>0.000</td>
</tr>
<tr>
<td>Case 2</td>
<td>2</td>
<td>2</td>
<td>12</td>
<td>0.001</td>
</tr>
<tr>
<td>Case 3</td>
<td>2</td>
<td>3</td>
<td>60</td>
<td>0.002</td>
</tr>
<tr>
<td>Case 4</td>
<td>2</td>
<td>4</td>
<td>280</td>
<td>0.012</td>
</tr>
<tr>
<td>Case 5</td>
<td>2</td>
<td>5</td>
<td>1260</td>
<td>0.034</td>
</tr>
<tr>
<td>Case 6</td>
<td>2</td>
<td>6</td>
<td>5544</td>
<td>0.095</td>
</tr>
<tr>
<td>Case 7</td>
<td>2</td>
<td>7</td>
<td>24025</td>
<td>0.167</td>
</tr>
<tr>
<td>Case 8</td>
<td>2</td>
<td>8</td>
<td>102960</td>
<td>0.524</td>
</tr>
<tr>
<td>Case 9</td>
<td>2</td>
<td>9</td>
<td>437580</td>
<td>2.221</td>
</tr>
<tr>
<td>Case 10</td>
<td>2</td>
<td>10</td>
<td>1847560</td>
<td>3.870</td>
</tr>
<tr>
<td>Case 11</td>
<td>3</td>
<td>1</td>
<td>6</td>
<td>0.000</td>
</tr>
<tr>
<td>Case 12</td>
<td>3</td>
<td>2</td>
<td>270</td>
<td>0.010</td>
</tr>
<tr>
<td>Case 13</td>
<td>3</td>
<td>3</td>
<td>8400</td>
<td>0.110</td>
</tr>
<tr>
<td>Case 14</td>
<td>3</td>
<td>4</td>
<td>242550</td>
<td>1.272</td>
</tr>
<tr>
<td>Case 15</td>
<td>3</td>
<td>5</td>
<td>6810804</td>
<td>36.500</td>
</tr>
<tr>
<td>Case 16</td>
<td>3</td>
<td>6</td>
<td>188684496</td>
<td>60982.540</td>
</tr>
<tr>
<td>Case 17</td>
<td>3</td>
<td>7</td>
<td>5187948480</td>
<td>172.421</td>
</tr>
<tr>
<td>Case 18</td>
<td>4</td>
<td>1</td>
<td>24</td>
<td>0.001</td>
</tr>
<tr>
<td>Case 19</td>
<td>4</td>
<td>2</td>
<td>10080</td>
<td>0.090</td>
</tr>
<tr>
<td>Case 20</td>
<td>4</td>
<td>3</td>
<td>2587200</td>
<td>13.500</td>
</tr>
<tr>
<td>Case 21</td>
<td>4</td>
<td>4</td>
<td>630630000</td>
<td>4605.390</td>
</tr>
</tbody>
</table>
Figure 8a plots the extraction time of all the cases listed in Table 3. Note the Y-axis is logarithmic. The exponential nature of this problem is hardly surprising. What we consider significant is the number of traces that can be analysed within a reasonable time (in our case, within one day). For instance, the time taken to extract over 5 billions traces in case17 took around 17 hours. However, as Table 2 shows, the equivalent design to the plan graph of case 17 consists of 61 plans and 63 other nodes (actions, percepts, goals and messages). Further, these nodes include both parallelism and choice decompositions.
Whilst the plan graphs analysed were generated artificially, we believe that this shows our approach can, at least under some circumstances, scale up relatively well. It is of course impossible to know what sizes will occur in practice without a real design of some significant size. Based on our own experience over the last 15 years of building agent systems in collaboration with industry partners, case 15 (33 plans, 35 nodes) is quite large and this system took just 38 seconds to check.
### 4.2 Effectiveness Evaluation
In this section, we present a preliminary evaluation to validate that our approach is able detect defects in a design, and to learn about the types of problems it cannot detect.
#### 4.2.1 Method
Two participants from outside our research team, both experienced in BDI agent design, were given the corrected version of the plan graph in Figure 6a. Each participant was asked to make several small changes (called **mutants**), such as adding, removing, replacing and renaming entities. In total, we received 11 mutants. We ran our approach on each mutated version and investigated whether the introduced defects were detected or not.
#### 4.2.2 Results
The resulting mutants all fell into three categories (although more are possible). First, the addition of new (irrelevant) entities (**ADD**). For instance, one participant added a new goal in between the Assign Reviewers and Collect Prefs steps. Further, they made the plan that posts the “Assign Reviewers” goal posts a new goal “Optimise Allocation”. Then, they added new plan to handle the “Optimise Allocation” goal that posts the the “Assign Reviewers” goal.
Second, the removal (deletion) of entities (**DEL**) from the plan graph including renaming them inconsistently with respect to the scenario. Third, the replacement of goal steps (**REP**) with related goals from the goal tree (parents or children).
Table 4 summarises the results obtained by applying our approach on the 11 mutants. Only one mutant (MA10) out of the five in the **ADD** category was detected. This is because a new goal was introduced that created a new step in the scenario, which was not originally specified. The remaining four added new functionality in the design that was filtered because it did not occur in the scenario (recall that traces have elements that do not occur in the scenario filtered out). This filtering is motivated by the possibility that a plan graph may include behaviour that is related to another scenario. However, the filtering does limit our ability to detect issues caused by adding elements to the design. Overall, we argue that this limitation may be acceptable in order to avoid too many false positives. However, in future work, we will investigate how to consider all scenarios in a design together to eliminate this issue.
<table>
<thead>
<tr>
<th>Category</th>
<th>ID</th>
<th>MS</th>
<th>TS</th>
<th>TL</th>
<th>OE</th>
<th>Def.</th>
<th>Det.</th>
</tr>
</thead>
<tbody>
<tr>
<td>ADD</td>
<td>MA0</td>
<td>0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td></td>
<td>MA1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>X</td>
</tr>
<tr>
<td></td>
<td>MA2</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td></td>
<td>MA3</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>X</td>
</tr>
<tr>
<td>DEL</td>
<td>MR0</td>
<td>0</td>
<td>1</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td></td>
<td>MR1</td>
<td>0</td>
<td>4</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td></td>
<td>MR2</td>
<td>0</td>
<td>2</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>X</td>
</tr>
<tr>
<td></td>
<td>MR3</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>X</td>
</tr>
<tr>
<td>REP</td>
<td>MP0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>X</td>
</tr>
<tr>
<td></td>
<td>MP1</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>0</td>
<td>✓</td>
<td>X</td>
</tr>
</tbody>
</table>
Total 11 0 7 1 0 8 4
In the **DEL** category, three of the four mutants were detected. In the undetected one, the participant modified the plan graph such that the goal Assign Reviewer was handled by one plan instead of two. This simply reduced the number of (correct) traces, and hence the design is still correct with respect to scenario.
None of REP mutants were discovered. This is because goals in the design were replaced with child/parent goals from the goal hierarchy that were valid for the given scenario. Therefore, the mutants were not defective.
This shows that our approach is promising, despite the small numbers involved. In particular, if we consider our technique as a method of classifying mutants as correct or incorrect, we correctly identified 8 out of 12 mutants as either defective or correct. As mentioned above, the 4 incorrectly classified mutants were due to the filtering process, which is the subject of future work. As in the previous section, finding real examples of agent designs is a significant problem which we are working to address. It is also encouraging to note that there were no false positives, i.e., all detected defects corresponded to actual design defects.
5. RELATED WORK
In the context of agent design methodologies, there has been little research into checking the correctness of agent design artifacts. There is a large body of work on verifying BDI agent systems using formal verification such as model checking (e.g., [10, 5, 6, 12]) and theorem proving (e.g., [28]). While these approaches can provide a higher level of assurance than our work, they assume the existence of either a formal model that abstracts the behaviour of the system, or an implementation of the system itself. In contrast, we aim to detect defects in semi-formal models.
Similarly, researchers have investigated specific methods for runtime testing of multi-agent programs [19, 20], including BDI agents [23, 16], assertion-based verification with static analysis [29], and run-time debugging of agent interaction [7, 25]. Clearly, testing or verifying an implementation also provides some level of verification of the corresponding design, however, there is clear value in being able to detect design defects before implementing a design.
Many AOSE methodologies offer development environments via their supporting tools, including frameworks for verification of design artifacts. Tropos [8] provides perhaps the most complete support for requirements verification. Tropos offers two frameworks, each including tool support, for: (i) validating formal requirements specification using T-Tool [14], and (ii) reasoning with formal goal models using GR-Tool [15]. Using symbolic reasoning, these frameworks provide a high-level of assurance, but neither support verification of agent design artifacts. Both the O-MaSE [11] and Prometheus methodologies [24] offer support for agent design artifacts. O-MaSE offers the agentTool III (aTIII), which checks for consistency between the related models using results that check static relationships between design entities, while early versions of the Prometheus Design Tool offered basic static consistency checking feature. Such ideas are complementary to our approach.
Further, there has been some related work in the area traceability for supporting verification of agent models. Cysneiros and Zisman [9], introduce a rule-based traceability approach grounded in the Prometheus methodology and JACK platform. The approach automatically generates traceability relations for verifying the models (agent designs and JACK code), and checking their completeness by identifying the missing elements. Thangarajah et al. [30] propose a mechanism that facilitates the traceability between requirements (via scenarios) and other design entities, which is used to support test case generation. They establish the concept of traceability links, which relate scenarios steps to other design entities including goals, actions, percepts and events. Their work is complementary to our approach.
6. CONCLUSION
In this paper, we presented a method, with tool support, that is able to find defects in agent designs with respect to the requirements that are specified in the form of scenarios and goal hierarchies. The tool extracts all possible execution traces from the detailed agent designs, which represent the behaviour of the system, and checks each trace against the requirements models.
We evaluated our approach on 11 versions of one design (via mutations) that were done by two participants. Our evaluation shows that our approach was able to successfully detect defects, and raised no false positives. In addition, we performed a scalability analysis on the approach, with results showing that our approach can verify large plan graphs in under one calendar day, despite the exponential explosion in traces as designs get larger.
Our approach is grounded in the Prometheus design methodology, however it can be generalised to others. This generalisation is possible due to the intermediate representations that we use. More specifically, both the requirement specifications and the detailed agent designs are translated to executable petri-net structures. The latter is used to extract traces and the former to execute the traces extracted. Thus, applying our techniques to other methodologies would simply involve transforming their requirements and detailed designs into equivalent petri-net structures.
In future work, we plan to improve the approach to consider multiple scenarios at once, which will mitigate the problem of filtering out unrelated steps that led to some defects not being detected in our evaluation. We will also apply our approach on an extensive set of Prometheus case studies to determine its effectiveness at finding defects in practice.
REFERENCES
|
{"Source-Url": "http://people.eng.unimelb.edu.au/tmiller/pubs/aamas2015-reqs.pdf", "len_cl100k_base": 11511, "olmocr-version": "0.1.49", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 32555, "total-output-tokens": 12927, "length": "2e13", "weborganizer": {"__label__adult": 0.00030803680419921875, "__label__art_design": 0.0004057884216308594, "__label__crime_law": 0.00030517578125, "__label__education_jobs": 0.0012149810791015625, "__label__entertainment": 5.537271499633789e-05, "__label__fashion_beauty": 0.00016117095947265625, "__label__finance_business": 0.00022077560424804688, "__label__food_dining": 0.00028443336486816406, "__label__games": 0.0005965232849121094, "__label__hardware": 0.0006885528564453125, "__label__health": 0.00041413307189941406, "__label__history": 0.00025916099548339844, "__label__home_hobbies": 9.900331497192384e-05, "__label__industrial": 0.0003826618194580078, "__label__literature": 0.00024330615997314453, "__label__politics": 0.0002275705337524414, "__label__religion": 0.0003941059112548828, "__label__science_tech": 0.020782470703125, "__label__social_life": 8.499622344970703e-05, "__label__software": 0.005184173583984375, "__label__software_dev": 0.966796875, "__label__sports_fitness": 0.0002815723419189453, "__label__transportation": 0.0004489421844482422, "__label__travel": 0.00018775463104248047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49896, 0.05554]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49896, 0.38688]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49896, 0.91698]], "google_gemma-3-12b-it_contains_pii": [[0, 4789, false], [4789, 9925, null], [9925, 16428, null], [16428, 23253, null], [23253, 27654, null], [27654, 32896, null], [32896, 39326, null], [39326, 44825, null], [44825, 49896, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4789, true], [4789, 9925, null], [9925, 16428, null], [16428, 23253, null], [23253, 27654, null], [27654, 32896, null], [32896, 39326, null], [39326, 44825, null], [44825, 49896, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49896, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49896, null]], "pdf_page_numbers": [[0, 4789, 1], [4789, 9925, 2], [9925, 16428, 3], [16428, 23253, 4], [23253, 27654, 5], [27654, 32896, 6], [32896, 39326, 7], [39326, 44825, 8], [44825, 49896, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49896, 0.26275]]}
|
olmocr_science_pdfs
|
2024-11-26
|
2024-11-26
|
9fdf82ac6c21b92c693c2de6c177387ec5ce4a5f
|
Anttila Henri
Continuous Integration and System Test Automation
Case Exertus
Thesis
Spring 2018
Seinäjoki University of Applied Sciences (SeAMK): School of Technology
Information technology
Thesis abstract
Faculty: School of Technology
Degree program: Information Technology
Specialization: Telecommunication technology
Author: Henri Anttila
Title of thesis: Continuous Integration and System Test Automation: Case Exertus
Supervisor: Alpo Anttonen
Year: 2018 Number of pages: 46 Number of appendices: 1
This thesis described the implementation of continuous integration and test automation systems for Exertus Oy. The purpose of the project described in the thesis was to standardize and automate the source code build process, which is a prerequisite for automated testing. To this end, the Jenkins build automation server was taken into use and a custom CAN bus based test automation system was developed. As a result, Exertus’ daily source code is automatically built and tested each night on each of their hardware modules. The tests for the test automation system can be created in Exertus’ own Guitu no-code development environment.
Keywords: automation, continuous integration, DevOps, CI, test automation, system integration, software testing, Jenkins, XStudio
# TABLE OF CONTENTS
Opinnäytetyön tiivistelmä .................................................................................. 1
Thesis abstract .................................................................................................. 2
TABLE OF CONTENTS ................................................................................. 3
Terms and Abbreviations .................................................................................. 5
Images and Figures ............................................................................................ 9
1 INTRODUCTION ............................................................................................. 10
1.1 Outline of the Thesis .................................................................................. 11
1.2 Company Introduction: Exertus Oy ............................................................ 13
2 EXERTUS PRODUCTS .................................................................................. 14
2.1 HCM2010S Hybrid Controller Module ...................................................... 14
2.2 MIC2000S Multi Information Controller .................................................. 15
2.3 Guitu Graphical Programming Environment .............................................. 16
2.4 Canto2: CAN Monitoring and Commissioning Tool ..................................... 17
2.5 ExGUI Graphics Abstraction Layer ............................................................. 18
3 AIM AND SCOPE ......................................................................................... 19
4 TOOLS ......................................................................................................... 21
4.1 Phabricator .................................................................................................. 21
4.2 Jenkins ....................................................................................................... 21
4.3 Docker and Containerization ...................................................................... 23
4.4 GNU Make and Makefiles ......................................................................... 25
4.5 XStudio Test Management Suite .................................................................. 26
4.5.1 XAgent .................................................................................................. 27
4.5.2 XContinuousIntegration, XCI ................................................................. 27
4.5.3 XStudio Launcher .................................................................................. 28
4.6 Controller Area Network (CAN) ................................................................ 28
4.7 CANopen .................................................................................................... 29
4.7.1 CANopen Object Dictionary ................................................................. 30
4.7.2 Process Data Object (PDO) Protocol .................................................... 30
4.7.3 Service Data Object (SDO) Protocol ..................................................... 31
4.7.4 Network Management (NMT) Protocol ................................................ 31
## Terms and Abbreviations
<table>
<thead>
<tr>
<th><strong>Term</strong></th>
<th><strong>Definition</strong></th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Apache Tomcat</strong></td>
<td>An open source Java servlet container. Also see: Java servlet.</td>
</tr>
<tr>
<td><strong>API</strong></td>
<td>Application Programming Interface</td>
</tr>
<tr>
<td><strong>ash</strong></td>
<td>Almquist Shell. A lightweight Unix shell and command language popular in embedded Linux systems. Also see: BusyBox.</td>
</tr>
<tr>
<td><strong>bash</strong></td>
<td>Bourne Again Shell. A Unix shell and command language widely used in Linux.</td>
</tr>
<tr>
<td><strong>BusyBox</strong></td>
<td>A software that provides a set of Unix tools in a single executable. Common in embedded systems with limited resources.</td>
</tr>
<tr>
<td><strong>C</strong></td>
<td>A popular general-purpose computer programming language. Imperative paradigm.</td>
</tr>
<tr>
<td><strong>C++</strong></td>
<td>A popular general-purpose computer programming language. Imperative, object-oriented and generic paradigms. Heavily influenced by C.</td>
</tr>
<tr>
<td><strong>CAN</strong></td>
<td>Controller Area Network. See chapter 2.7 for more details.</td>
</tr>
<tr>
<td><strong>CANOpen</strong></td>
<td>A CAN communication protocol by CiA. See CiA and chapter 2.8.</td>
</tr>
<tr>
<td><strong>CD</strong></td>
<td>Continuous delivery, practice of automatically pushing promoted release candidates to end users</td>
</tr>
<tr>
<td><strong>CI</strong></td>
<td>Continuous integration, practice of automatically turning new source code into an internally distributable software package.</td>
</tr>
<tr>
<td>Abbreviation</td>
<td>Description</td>
</tr>
<tr>
<td>--------------</td>
<td>-------------</td>
</tr>
<tr>
<td>CiA</td>
<td>CAN in Automation. International users’ and manufacturers’ group for the CAN network.</td>
</tr>
<tr>
<td>CLI</td>
<td>Command Line Interface. A text based user interface. Also see: GUI.</td>
</tr>
<tr>
<td>CPU</td>
<td>Central Processing Unit</td>
</tr>
<tr>
<td>DRY</td>
<td>Don’t repeat yourself. A software development principle to avoid code repetition and data duplication.</td>
</tr>
<tr>
<td>DSL</td>
<td>Domain-specific language. A programming language specialized in a particular application domain.</td>
</tr>
<tr>
<td>FOSS</td>
<td>Free and open-source software</td>
</tr>
<tr>
<td>Framebuffer</td>
<td>A portion of RAM that contains the bitmap to be drawn on the display.</td>
</tr>
<tr>
<td>Git</td>
<td>A distributed revision control system. See chapter 2.1</td>
</tr>
<tr>
<td>GRT</td>
<td>Guitu Runtime. See chapter 1.5.1.</td>
</tr>
<tr>
<td>GUI</td>
<td>Graphical User Interface. What you see is what you get. Also see: CLI.</td>
</tr>
<tr>
<td>HTTP</td>
<td>Hypertext Transfer Protocol, a fundamental data communication protocol of the world wide web.</td>
</tr>
<tr>
<td>I/O</td>
<td>Input / Output</td>
</tr>
<tr>
<td>IaC</td>
<td>Infrastructure as code</td>
</tr>
<tr>
<td>Java</td>
<td>A general-purpose, object-oriented computer-programming language by Sun Microsystems / Oracle.</td>
</tr>
<tr>
<td>Java bytecode</td>
<td>The instruction set of the JVM. Also see: Java, JVM.</td>
</tr>
<tr>
<td>Java servlet</td>
<td>A Java program that extends the capabilities of a server. Purpose similar to PHP and Microsoft’s ASP.NET.</td>
</tr>
<tr>
<td>Term</td>
<td>Definition</td>
</tr>
<tr>
<td>--------</td>
<td>------------</td>
</tr>
<tr>
<td>JVM</td>
<td>Java Virtual Machine. A virtual computing machine that allows running Java bytecode. Also see: Java, Java bytecode.</td>
</tr>
<tr>
<td>Linux</td>
<td>Or GNU/Linux. FOSS operating system built around the Linux kernel. Also see: FOSS.</td>
</tr>
<tr>
<td>Make</td>
<td>A build automation tool for creating executable programs and libraries from the source code based on a Makefile. Also see: Makefile and chapter 2.5.</td>
</tr>
<tr>
<td>Makefile</td>
<td>A file that directs Make on how to compile and link a program. Also see: Make and chapter 2.5.</td>
</tr>
<tr>
<td>Map</td>
<td>An abstract data type. Also known as associative array, symbol table or dictionary. A collection of key-value pairs.</td>
</tr>
<tr>
<td>MVP</td>
<td>Minimum viable product. See chapter 1.6.</td>
</tr>
<tr>
<td>OOP</td>
<td>Object-oriented programming. A programming paradigm based on the concept of objects.</td>
</tr>
<tr>
<td>OS</td>
<td>Operating system. Software that manages hardware and software resources and provides services for computer programs.</td>
</tr>
<tr>
<td>OSI model</td>
<td>The Open Systems Interconnection model. A conceptual model for describing a communication or computing system or network.</td>
</tr>
<tr>
<td>PDO</td>
<td>Process Data Object. A CANOpen communication protocol. See chapter 2.8.2 on PDOs for further details.</td>
</tr>
<tr>
<td>SDO</td>
<td>Service Data Object. A CANOpen communication protocol. See chapter 2.8.3 on SDOs for further details.</td>
</tr>
<tr>
<td>Acronym</td>
<td>Description</td>
</tr>
<tr>
<td>---------</td>
<td>-------------</td>
</tr>
<tr>
<td>QA</td>
<td>Quality assurance</td>
</tr>
<tr>
<td>SaaS</td>
<td>Software as a Service. A centrally hosted, subscription based software licensing and delivery model.</td>
</tr>
<tr>
<td>SCP</td>
<td>Secure Copy Protocol. An SSH based file transfer protocol. Also see: SSH.</td>
</tr>
<tr>
<td>SDK</td>
<td>Software development kit. A set of tools provided for creating additional functionality for an existing platform (software or hardware).</td>
</tr>
<tr>
<td>Shell</td>
<td>A user interface for access to an OS' services.</td>
</tr>
<tr>
<td>SQL</td>
<td>Standard Query Language. A DSL for managing data stored in a relational database. See: DSL.</td>
</tr>
<tr>
<td>SSH</td>
<td>Secure Shell. A cryptographic client-server network protocol for secure operation over an unsecure network.</td>
</tr>
<tr>
<td>Subversion</td>
<td>Also known as SVN. A revision control system akin to Git.</td>
</tr>
<tr>
<td>SUT</td>
<td>Service / Software / Subject / System Under Test. The target on which testing is being done.</td>
</tr>
<tr>
<td>UI</td>
<td>User interface. Also see: GUI, CLI.</td>
</tr>
<tr>
<td>Userland</td>
<td>Also user space. Code that runs outside an OS kernel, such as applications.</td>
</tr>
<tr>
<td>UX</td>
<td>User Experience</td>
</tr>
<tr>
<td>VM</td>
<td>Virtual Machine. An emulated computer system.</td>
</tr>
<tr>
<td>YAML</td>
<td>YAML Ain’t Markup Language or Yet Another Markup Language. A human readable data serialization language akin to JSON and XML.</td>
</tr>
</tbody>
</table>
Images and Figures
Image 1. HCM2010S Hybrid Controller Module ........................................... 15
Image 2. MIC2000S Multi Information Controller .......................................... 15
Image 3. Sample image of Guitu GUI .............................................................. 17
Image 4. Sample image of Canto2 GUI ............................................................ 18
Image 5. A simple example Dockerfile describing a Python container ............ 24
Figure 1. Docker container and VM comparison ............................................ 24
Figure 2. XQual XStudio test management suite data model ......................... 26
Figure 3. CAN bus cabling ........................................................................... 29
Figure 4. CAN bus encoding ........................................................................ 29
Figure 5. The CANopen object dictionary index ranges ................................ 30
Figure 6. CANopen NMT state diagram ......................................................... 32
Figure 7. A Jenkinsfile containing a map of the different build parameters ...... 36
Figure 8. A Jenkins pipeline that uses 'pipepars', a map of pipeline parameters to control the different steps ......................................................... 37
Figure 9. HCM2010 latest build artifacts in the Jenkins GUI ......................... 38
Figure 10. A YAML file containing two inputs for test id 1170 ...................... 41
Figure 11. Parts of class TestCase that show writing the CANOpen object dictionary and running the test case .................................................. 41
Figure 12. The full utility script that is required for each SUT in Guitu. ...... 43
1 INTRODUCTION
Quality assurance is an umbrella term for the practice of preventing mistakes and defects in manufactured products and provided services. The process of quality assurance can look very different depending on its target. In other words, one would not assure the quality of a 10-story skyscraper with the same methods one uses to assure the quality of a set of Lego bricks. Yet, the end goal of the process remains the same. This thesis concerns implementing automated quality assurance in the realm of embedded computer software and electronics design.
Even inside the realm of software testing the testing requirements are directly correlated with the purpose of the software. The on-board computer of the latest airplane model, where safety and reliability are of utmost importance, requires far more comprehensive testing than a web browser based game of chess does. The methods of and approaches to testing are numerous and testing can be done on multiple levels of software abstraction. Some of these methods include peer review of the produced source code, testing the units of the source code, such as functions and classes, the interfaces or the system as a whole. (Kautto 1996, 1.1.)
Quality assurance can be done by manually operating and manipulating the SUT in different ways, using different inputs and comparing the actual outcome with the expectations and making sure that they align. Manual testing is by its very nature time-consuming and prone to errors. If testing is carried out in this way, for example by the same software developer who wrote the software, there’s also a risk that the test cases may be chosen based on how the code is expected to work. In the worst-case scenario, if a formal testing protocol is not defined or properly followed, there is also a chance of parts or all the quality assurance process being neglected. (Kautto 1996, 1.2.)
It is also not enough to test just the new functionality, because in certain situations new functionality or changes made to an existing one can have unexpected and unintended side-effects and consequences in unexpected places, a phenomenon known as regression (Kautto 1996, 2.2). Thus, it is also necessary to make sure that the already verified functionality remains free of defects. The amount of testing that
needs to be carried out increases with the new functionality. It naturally follows, that manual testing will therefore consume an ever-increasing amount of time.
To overcome the issue of time consumption, testing needs to happen automatically with every new piece of functionality that has been introduced. Automation enables the application of all the available tests on every change introduced and also effortless reapplication of the tests after the errors have been fixed. This makes sure that everything that is being tested still retains its original integrity and intended functionality. Being able to run the whole suite of tests on every change increases the reliability of the subject under test.
This increased reliability opens further automation opportunities. As the code is being tested rigorously in a short period of time and in an automatic, formally defined and codified fashion and on smaller batches of changes, new software versions can be taken into use more frequently with less need to worry about them being unreliable compared to the older ones. This further enables the catching of possible defects earlier through internal user experience thus reducing their spread and impact.
A process like this is promoted by the DevOps movement and referred to as Continuous Integration. It may not be plausible to do all types of testing on all the changes and some of the testing might be difficult to automate. A more rigorous testing process can be carried out less frequently, for example before a new public release.
The type of testing described in this thesis is a type of black box system testing, where tests are run against the underlying hardware and software during runtime without considering the underlying code. This testing is used to determine that the features being tested produce results that are both predictable and conform to the formal requirement documentation.
1.1 Outline of the Thesis
The previous chapter provided background information for this thesis. The next introductory chapters will familiarize the reader with the company Exertus Oy and some of its hardware and software products that are relevant for understanding the
rest of this thesis. After that, the aim and scope of this paper is discussed providing the reader an overall view of the project that is described herein.
The thesis continues by describing the set of tools used to reach the goal of this paper. The reader will be introduced to Phabricator, Jenkins, Docker, Make and Makefiles, XStudio Test Management Suite, the CAN bus, the CANOpen specification and some of its functionality, Exertus’ own Guitu and the Wall of Test, an in-house testing configuration running the Exertus Guitu control system applications.
After these chapters, the reader should have an elementary understanding of these concepts and be able to follow through the next chapters which discuss the actual implementation details. The implementation chapters first discuss the implementation of the build automation and, after that, proceed to test automation. Both chapters have an internal structure that goes through the business requirements, challenges that arise from them and how those requirements affect the implementation decisions. The last chapter provides a summary of the end results. It also discusses some of the challenges encountered along the way and finally what the future could hold for this project.
The thesis will not provide minute details on how all the parts of the system are installed, implemented or configured where such information is not relevant for the aim and scope of this paper or doesn't considerably deviate from the documentation and intended usage of the software in question. There are a lot of smaller tools and utilities used and not all of them can be described in detail within the scope of this thesis. Describing any such tools that are considered basic professional knowledge and as auxiliary or means-to-an-end is outside the scope of this thesis. However, a rather comprehensive Terms and Abbreviations section is provided. The reader is highly suggested to look up any new concepts there. If there is a more comprehensive explanation available elsewhere in the paper, the Terms and Abbreviations will have a reference to the relevant chapter.
During the course of this thesis any source code or data will be presented with the following formatting:
```bash
#!/bin/bash
NUM1=2
```
NUM2=1
if [ $NUM1 -eq $NUM2 ]; then
echo "Equal"
else
echo "NOT equal"
fi
Where hexadecimal numbers are used instead of decimal numbers, the prefix 0x is prepended to the number.
1.2 Company Introduction: Exertus Oy
Exertus Oy, from now on referred to as just Exertus, was founded in the year 2003 in Seinäjoki, Finland. Their core competence is in developing CAN bus based, distributed machine control systems. To achieve this, Exertus manufactures its own control system hardware products based on the CAN bus technology. They also develop software for programming and diagnosing these systems and provide a comprehensive solution development service based on these products. Solution development encompasses the system's whole life-cycle, including services such as system design, prototyping, testing, series production, customer support and service. Exertus aims to provide a full technology stack for building complete control systems, both small and large. (Exertus Oy, Yritys. Accessed on 23rd Jan 2018)
For marketing purposes, Exertus' hardware products are grouped into four different product categories: displays, controllers, sensors and other products such as CAN hubs. In addition to their own hardware, Exertus is also a retailer for the IKUSI brand remote controls. (Exertus Ltd, Products. [Accessed on 23rd Jan 2018]). Exertus also has a lineup of software products that are introduced in more detail below.
2 EXERTUS PRODUCTS
During the course of this thesis references will be made to Exertus products. While the project described in this thesis is meant to cover the testing of all Exertus hardware products, only two representative examples are required from a technological point of view.
This chapter will familiarize the reader with a subset of Exertus’ hardware and software products. Instead of the marketing categories mentioned in the company introduction, this thesis uses a high-level technological division for the hardware products; bare metal products and MIC Platform products. The term bare metal product or system is used to refer to a system that runs without an intervening operating system and instead runs a monolithic, single-purpose software that interacts directly with the underlying hardware. A bare metal product used as an example in this paper is the HCM2010S.
MIC Platform system is used to refer to the Exertus line of products that run the Linux operating system. A MIC Platform product used for the purposes of this paper is the MIC2000S. This division is made because it affects the way in which these devices can be interacted with and the actual implementation details.
2.1 HCM2010S Hybrid Controller Module
The HCM2010S Hybrid Controller Module pictured in image 1 is a Guittu-programmable I/O controller with 60 configurable I/O channels and two CAN interfaces. The HCM2010S runs on an ARM Cortex M4 168MHz CPU. (Exertus Ltd, HCM2010S Tech Doc. [Accessed on 25th February 2018].)
2.2 MIC2000S Multi Information Controller
MIC2000S Multi Information Controller in image 2 is an embedded Linux based controller that combines a traditional I/O controller, display controller and data logger with USB, Ethernet, RS232 and CAN interfaces. It runs on an ARM Cortex A9 Dual Core 800 MHz main CPU and also includes an ARM Cortex M4 168MHz auxiliary CPU for dedicated handling of the I/O. The MIC2000S has a total of 40 Guitu-programmable I/Os and three CAN interfaces. (Exertus, MIC2000S Tech Doc. [Accessed on 25th February 2018].)
2.3 Guitu Graphical Programming Environment
Guitu is Exertus’ own graphical programming environment provided for Microsoft Windows operating systems. It is a multi-user tool used to create GUIs and I/O configurations for machine control systems. It also contains function block diagram based scripting tools and a debugger. Guitu creates the low-level CAN communications between the different controllers on the background without the programmer needing to understand the details of the CAN bus and the CANOpen protocol. (Exertus Ltd: Guitu Programming Environment). Guitu consists of two different parts: The Guitu software for programming the controllers and Guitu Runtime (GRT for short) that is used to run the control system configurations created with Guitu and to handle the CAN traffic and other lower level details of the CANOpen implementation. Guitu is programmed in C++. GRT is programmed in C.
2.4 Canto2: CAN Monitoring and Commissioning Tool
Canto2 is Exertus’ CAN bus monitoring and commissioning tool that conforms with the standards specified in CANOpen. It can be used to follow and record the traffic on the CAN bus, show basic information about the status of the different nodes on the bus and to set node parameters through the use of the CANOpen Service Data Object (SDO) protocol. (Exertus Ltd: Canto2 Monitoring and Commissioning Tool. [accessed on 25th Feb].)
Image 4. Sample image of Canto2 GUI (Exertus Ltd, Products. [Accessed on 30\textsuperscript{th} March 2018]).
2.5 ExGUI Graphics Abstraction Layer
Guitu Runtime uses an in-house graphics abstraction layer called ExGUI to draw its user interface. ExGUI handles the hardware details of drawing graphics, such as maintaining the frame buffer. It provides a software interface for GRT to draw its UI on the built-in or external display.
3 AIM AND SCOPE
The aim of the project described in this paper is to reinforce Exertus’ existing testing architecture and processes by setting up a framework for a build and test automation system. Benefits that can be expected from such a system when correctly implemented are:
1. Single common storage for source code
2. A unified way and environment for building the software from source code.
3. A single source for the developers to get the build products, such as software libraries and executables that they need without having to rely on other developers’ help or set up own build environments.
4. A unified process of testing the source code that is produced
5. The build and testing process is run automatically each night. The whole set of tests is applied to ensure that the software remains as defect free as possible and that there are no unexpected regressions.
6. Every binary product has gone through a set of these automated tests that verify the functionality and enhance reliability of the released binary products.
The scope of the project described in this paper is to establish a minimum viable product (MVP) of the build and test automation system. A minimum viable product is a concept that emphasizes the concept of learning. Eric Ries, author of the popular entrepreneurship blog Startup Lessons Learned and the author of Lean Startup Methodology, who coined the term MVP defined it as "that version of a new product which allows a team to collect the maximum amount of validated learning about customers with the least effort" (Ries, 2008). Customers in this context refers to users of the CI system, mainly Exertus employees.
For the MVP it was decided that the following functionalities are required:
1. Specimen of bare metal monolithic firmware and MIC platform applications are built automatically, in a repeatable and reproducible manner every night.
2. The build products are made available to Exertus' employees via a web interface
3. The build products are automatically deployed to the test bench automatically every night
4. The test bench hardware modules are updated with the latest software in an automatic fashion
5. Multiple tests on Guitu scripting block functionality are carried out on multiple SUTs in an automatic fashion
6. Detailed results of these tests are stored in the test management suite
7. Overall success / failure status of these tests is stored on a per SUT basis in the build automation system
8. The tests need to be implemented in Guitu to allow the test engineers, who might not be familiar with programming with for example C, to create these tests
Having completed these steps, all the necessary basic functionalities have been built and capability of automating the compiling and testing has been fully demonstrated. Future development is then just a matter of collecting usage experience and adapting the design based on that experience and adding more and different types of tests and adding more SUTs to the Wall of Test.
The scope of this thesis lies more in building a framework for executing tests and logging their results than it does on the actual implementation of the tests and test cases. As the project described herein includes a great deal of intercommunication between multiple different systems, this thesis also describes implementation details in the domain of system integration.
4 TOOLS
The CI pipeline is comprised of four main parts: Phabricator, Jenkins, Docker, Make, XStudio and what is colloquially referred to as The Wall of Test. A brief introduction to the relevant concepts of the CAN bus and the CANOpen protocol is also provided.
4.1 Phabricator
Phabricator is a platform for software development collaboration created by Phacility. It comprises multiple applications that each serve a different purpose. Phabricator is available in two delivery models: as a SaaS by Phacility or hosted locally on an in-house server. (Phacility Inc: Phabricator. [Accessed on 27th Jan 2018]). Exertus has chosen to host Phabricator themselves. Phabricator is a FOSS written in PHP (Phabricator, GitHub, accessed on 1st Feb 2018).
The following Phabricator applications are used in the current workflow:
1. Differential: peer review tool for source code commits
2. Diffusion: a git repository browser
3. Maniphest: for tracking bugs, ideas and enhancement proposals
4. Phriction: a wiki tool for hosting internal documentation
4.2 Jenkins
Jenkins is an automation server software that can be used to automate virtually anything that can be put into code. Its most prominent use has been in automation of repetitive software development tasks such as compiling source code to executable binaries, running automated test procedures, code analysis, software packaging and making new software versions available to company's internal users such as developers as well as end users. Jenkins is a common tool in a DevOps toolchain to facilitate continuous integration and continuous delivery.
Jenkins is a server based system that runs in a Java servlet container, such as Apache Tomcat (Jenkins.io, Installing Jenkins. Accessed on 1\textsuperscript{st} Feb 2018). Historically, development of Jenkins started as Hudson by Kohsuke Kawaguchi at Sun Microsystems. After Oracle's acquisition of Sun Microsystems, development of Jenkins began as a source code fork of Hudson. Jenkins was made available as a FOSS under the MIT license. (Kawaguchi, 2014).
Jenkins uses the concept of a pipeline to define and codify a process that involves building the software in a reliable and repeatable manner and progressing the built software through stages of testing and deployment. The pipeline is written in a domain-specific language (DSL) into a text file known as a Jenkinsfile. It provides a means to codify the build, test and deployment process and commit it into a source code control system, such as Git. Jenkins also supports creating different types of pipeline jobs through its GUI. The GUI based jobs were decided against as administratively heavy and less transparent. By writing the pipeline as code, Exertus can start putting parts of its infrastructure and processes into code. (Jenkins.io, Pipeline: What is Jenkins Pipeline? [Accessed on 1\textsuperscript{st} Feb 2018].)
The Pipeline DSL comes in two flavors: declarative and scripted. The former is a later development that aims to make writing Pipelines easier and to provide richer syntactical features over the latter. The scripted pipeline allows more flexibility. (Jenkins.io, Pipeline: Declarative versus Scripted Pipeline syntax. [Accessed on 1\textsuperscript{st} Feb 2018].)
Jenkins also includes a concept of shared libraries. In effect, a shared library is a collection of procedures written in Apache Groovy that can be shared by multiple pipelines, avoiding redundancy (Jenkins.io, Extending with Shared Libraries. [Accessed on 1\textsuperscript{st} Feb 2018]). Apache Groovy is an object-oriented programming language for the Java platform that can be compiled to bytecode executable by the JVM.
There is also a new development in Jenkins known as Blue Ocean. Blue Ocean is an enhancement for Jenkins GUI and UX. In its current form, however, the traditional Jenkins GUI is more mature. The move to Blue Ocean can be done at a later date,
when it has reached feature parity with the traditional GUI approach. (Jenkins.io, Blue Ocean [Accessed on 1st Feb 2018].)
Jenkins has a way of distributing its pipeline workloads between multiple nodes, or agents. This feature of Jenkins, however, is not utilized in this project. Every workload is run on the master node.
4.3 Docker and Containerization
Docker is a container platform developed by Docker, Inc. Containerization is a form of operating-system-level virtualization. Instead of creating a complete virtual machine with a separate guest OS, Docker shares the host machine kernel between the containers, but virtualizes the userland. Any state that is created inside a Docker container, is only available inside that container and doesn’t affect the state of the host machine or the other containers. Docker is primarily developed for Linux, although a Windows version of Docker is also available. (Docker, Inc., Get Started, Part 1: Orientation and setup. [Accessed on 2nd April 2018].)
A Docker container is launched by running a Docker image. A Docker image is an executable package that includes everything needed to run an application. The code, libraries, environment variables and configuration files. A container is a runtime instance of an image that becomes a process that holds the current state. (Docker, Inc., Get Started, Part 1: Orientation and setup. [Accessed on 2nd April 2018].)
Containers are defined by so called Dockerfiles that are simple text files used to describe what goes into the environment inside a Docker container. (Docker, Inc., Get Started, Part 2: Containers. Accessed on 2nd April 2018. [Accessed on 2nd April 2018].)
Figure 1. Docker container and VM comparison (medium.com / flow.ci: Introduction to Containers: Concept, Pros and Cons, Orchestration, Docker, and Other Alternatives. [Accessed on 2nd April 2018]).
```
# Use an official Python runtime as a parent image
FROM python:2.7-slim
# Set the working directory to /app
WORKDIR /app
# Copy the current directory contents into the container at /app
ADD . /app
# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt
# Make port 80 available to the world outside this container
EXPOSE 80
# Define environment variable
ENV NAME World
# Run app.py when the container launches
CMD ["python", "app.py"]
```
flow.ci lists in its Medium.com blog post the following pros and cons for using Docker containers:
Pros of using Docker containers
1. Small file size compared to VMs
2. Containers need less resources to run than VMs
3. Starting new containers takes a very short time
4. Application and its dependencies become portable
5. Simpler deployment
6. Cost effective
Cons of using Docker containers
2. All containers on the same server must use the same underlying OS
3. Networking containers is tricky
(medium.com / flow.ci: Introduction to Containers: Concept, Pros and Cons, Orchestration, Docker, and Other Alternatives. [Accessed on 2\textsuperscript{nd} April 2018].)
Basically, Docker reliably replicates state and moves it from the host machine and inside the containers, keeping the host machine cleaner and also easier to recreate by reducing the need so setup state and software dependencies.
4.4 GNU Make and Makefiles
GNU Make is a build automation tool that control the generation of executables from the program’s source code files. A Makefile contains a list of rules that in turn contain a series of commands to execute to build a target file from source files. It also specifies a list of the target file’s dependencies.
The Makefile takes the following pseudo-code shape:
\[
\text{target} \rightarrow \text{prerequisites} \rightarrow \text{commands}
\]
(Free Software Foundation, Make manual. [Accessed on 2nd April 2018]).
4.5 XStudio Test Management Suite
XStudio is a test management suite created by the French company XQual (XQual, Contact us. [Accessed on 3rd March 2018]). Its structure is based on the following data model:

Figure 2. XQual XStudio test management suite data model (XQual, User Guide. Introduction, Data model. [Accessed on 3rd March 2018]).
The aspects of the XStudio data model that are most relevant for this thesis are the SUTs, tests and test campaigns. Outside of the above diagram, XStudio also has the concept of test cases and campaign sessions, which are of interest to the reader.
An SUT is an abstract object that represents a target that is being tested (XQual, User Guide. The SUTs. [Accessed on 3rd March 2018]). Concretely, these are all the different Exertus products, such as the HCM2010S and the MIC2000S.
The SUTs have attached to them a set of business requirements. For example, a requirement could specify that “The module must implement the bitwise OR-operation for arbitrary signed integers”. (XQual, User Guide. The requirements.) The requirements are then fleshed out by more detailed specifications, such as “The bitwise OR-operation must handle negative integers correctly” (XQual, User Guide. The specifications. [Accessed on 3rd March 2018].)
The specifications, in turn, are backed by a set of tests. A test is the smallest executable unit in XStudio. The tests describe the steps that are necessary to make sure that the specified functionality works as expected. The steps can be automated or manual. A test can implement multiple test cases that carry out the testing in different ways and with different parameters, such as implementing different edge cases of the test scenario. (XQual, User Guide. The tests. [Accessed on 3rd March 2018].)
The tests are then collected inside different test campaigns. An example test campaign could be “Verify Guitu scripting block functionality”. This campaign would then include the test described above and lots of other, similar tests. A campaign session is then generated to have XStudio run all the tests and their test cases that belong to the campaign. (XQual, User Guide. The campaigns. [Accessed on 3rd March 2018].)
4.5.1 XAgent
XAgent is a headless executable that can be left running in the background. It polls the XStudio database at specified intervals. If it detects a test campaign that it can run, it will run it and store the results in the XStudio database. (XQual, XAgent. [Accessed on 3rd March 2018].)
4.5.2 XContinuousIntegration, XCI
XContinuousIntegration, from now on referred to as XCI, is a command line utility that can be used to schedule test campaign sessions in XStudio. It provides an
integration APIs that can be used together with automation systems such as Jenkins to build a CI pipeline. An XAgent will pick up the test campaign sessions generated by XCI and run them and provide information about the test results that can be fed back to the CI automation system. (XQual, Continuous Integration. [Accessed on 3rd March 2018].)
4.5.3 XStudio Launcher
XQual provides a collection of different launchers for running automated tests in different types of systems. The launchers are open-sourced and provided as an SDK, so that they can be modified as much as necessary. The launchers are built using Java. Their purpose is to run an external script that implements the actual testing functionality and returns information about the test results when it has finished running. (XQual, Open-Source launchers. [Accessed on 3rd March 2018].)
4.6 Controller Area Network (CAN)
A Controller Area Network, or CAN bus, was originally developed for use in passenger cars. It has since seen widespread used in different application domains, such as industrial machine control systems, home and building automation, mobile machines, medical devices as well as many other. (CiA, CAN lower- and higher-layer protocols. [Accessed on 1st April 2018].)
CAN is a multi-master serial bus system that relies on broadcast messages. This means that any node is allowed to access the bus at any time if it is idle. The messages will be received by each node on the bus. Access conflicts are resolved by a bit-wise arbitration of the CAN-ID. The bus work in two levels: recessive and dominant. The dominant level overwrites the recessive level. All nodes that are transmitting a recessive level, but detect a dominant level on the bus will lose bus arbitration and transit into listening mode. The cabling of the CAN bus is usually implemented with a twisted-pair copper cable with a common ground. (CiA, CAN data link layers in some detail. [Accessed on 1st April 2018].)
The CAN bus uses a voltage differential between CAN HIGH (CAN_H) and CAN LOW (CAN_L) conductors to physically encode the CAN messages. Using a voltage differential increases robustness and tolerance to electromagnetic interference. (CiA, CAN high-speed transmission. [Accessed on 1\textsuperscript{st} April 2018].)

Figure 3. CAN bus cabling (CiA, CAN data link layers in some detail. [Accessed on 1\textsuperscript{st} April 2018]).

Figure 4. CAN bus encoding (CiA, CAN high-speed transmission. [Accessed on 1\textsuperscript{st} April 2018]).
### 4.7 CANopen
CANopen is a communication protocol and device profile specification that implements the OSI model layers from three to seven for CAN. A CANopen compliant device has three logical parts:
1. The CANopen protocol stack, which handles the communication via the CAN network.
2. The application software, which provides internal functionality and interface to the hardware.
3. The CANopen object dictionary, that provides an interface between the protocol and application software.
(CiA, CANopen – The standardized embedded network [Accessed on 1\textsuperscript{st} April 2018].)
### 4.7.1 CANopen Object Dictionary
Every CANopen node implements an object dictionary, abbreviated as OD. It serves as a data storage that can be read and written by other nodes on the bus. It stores the node’s configuration and state. The Object Dictionary consists of 24-bit addresses that are split into a 16-bit index and an 8-bit sub index. Any OD entry is readable by the CANopen communication services, such as the SDO protocol. (CiA, CANopen internal device architecture. [Accessed on 1\textsuperscript{st} April 2018].)
<table>
<thead>
<tr>
<th>Index</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>0000h</td>
<td>reserved</td>
</tr>
<tr>
<td>0001h - 025Fh</td>
<td>Data types</td>
</tr>
<tr>
<td>0260h - 0FFFh</td>
<td>reserved</td>
</tr>
<tr>
<td>1000h - 1FFFh</td>
<td>Communication object area</td>
</tr>
<tr>
<td>2000h - 5FFFh</td>
<td>Manufacturer specific area</td>
</tr>
<tr>
<td>6000h - 9FFFh</td>
<td>Device profile specific area</td>
</tr>
<tr>
<td>A000h - BFFFh</td>
<td>Interface profile specific area</td>
</tr>
<tr>
<td>C000h - FFFFh</td>
<td>reserved</td>
</tr>
</tbody>
</table>
Figure 5. The CANopen object dictionary index ranges (CiA, CANopen internal device architecture. [Accessed on 1\textsuperscript{st} April 2018])
### 4.7.2 Process Data Object (PDO) Protocol
PDOs are used for broadcasting high priority control and status information. A PDO can be triggered by an event, it can be timer-driven, requested remotely or tied to synchronization messages. A PDO can communicate up to eight bytes of data. (CiA, Process data object (PDO). [Accessed on 1\textsuperscript{st} April 2018].)
4.7.3 Service Data Object (SDO) Protocol
SDOs enable read/write access to the CANopen object dictionary. An SDO consists of two CAN data frames. SDO facilitates peer-to-peer client-server communication between two CANopen devices. The owner of the accessed object dictionary acts as the SDO server and the device that accesses the object dictionary is the SDO client. (CiA, Service data object (SDO). [Accessed on 1st April 2018].)
4.7.4 Network Management (NMT) Protocol
A CANopen device must implement support for the CANopen network management state machine. The NMT state machine consists of following states
1. Initialization
2. Pre-operational
3. Operational
4. Stopped
(CiA, Network management (NMT). [Accessed on 1st April 2018].)
The NMT system is controlled by one node that is chosen as the NMT master. The NMT commands are sent in a single CAN frame with a data length of two bytes. When a node receives an NMT frame containing its own node id, it must perform the commanded state transition. (CiA, Network management (NMT). [Accessed on 2nd April].)
Figure 6. CANopen NMT state diagram (CiA, Network management (NMT). [Accessed on 2nd April 2018]).
5 IMPLEMENTING THE BUILD AUTOMATION
To be able to automate testing of the latest developments in the source code in the first place, the building of the source code into executable binary needs to be automated. Exertus has already done some experiments with Jenkins, but a more comprehensive implementation is required.
5.1 Requirements for MIC Platform Guitu Runtime
All the MIC Platform devices use a version of the Linux operating system and execute Guitu Runtime as a userland application on top of it. Compiling GRT is dependent on a graphics library, which is a single file generated from the ExGUI’s source codes. GRT has a Makefile available, but the building process still depends on a set of different build flags provided by the user.
An older version of the Linux kernel (from now on “The older system” as opposed to “The new system”) used on one of the MIC Platform devices also needs to be considered. The older system and the new system are built using a different build toolchain. The source code for GRT is stored in a single Git repository which is used for all MIC Platform devices.
5.2 Requirements for MIC Platform ExGUI Library
ExGUI needs to be compiled to compile GRT. Similar to Guitu Runtime, it uses two different build toolchains for the older system and the new system. Both ExGUI and GRT need to be built with the same build toolchain to be compatible with each other. The source code for ExGUI is also stored in a single Git repository.
5.3 Requirements for Bare Metal Devices
Some of the bare metal devices have their source code stored in Subversion repositories. Some have had their source code moved over to Git. It was decided that any
source code stored in Subversion repositories would be left out of the build automation scope only to be implemented when they have been moved over to Git. The bare metal devices are dependent on two different Git repositories: the hardware library, which implements the low-level hardware handling and GRT. Some bare metal devices have a built-in display and thus also need ExGUI.
These dependencies are gathered together into a Git super project using Git’s submodule functionality, which allows a Git repository to contain other repositories. These submodules can be frozen to a specific commit to allow controlled updates instead of always using the latest commits.
The hardware library needs to be built with the correct build toolchain and correct flags for make. If ExGUI is needed, it needs to be supplied with the hardware library files. After that, GRT can be built but it needs both the hardware library files and the ExGUI library file.
5.4 Additional Requirements
Exertus wants to also support the concept of different binary flavors. A binary flavor in this context means a binary executable created with a different set of build flags resulting in a different binary product. Candidate flavors could for example be a release version aimed for public release, an internal debug version with debugging symbols left intact or a version that excludes some of the more advanced GRT features in favor of backwards compatibility.
The resultant executable and binary files should also be packaged in a certain format to make them easy to use. It would also be useful for users to be able to use Jenkins to build from source code branches other than the master branch to be able to test more experimental features. Even better, if the custom branch functionality could also be extended to the downstream dependencies such as the ExGUI. Users should be able to specify an identifiable name for their builds, but a sane default should be available too.
Some of the build toolchains have already been containerized, but a few of them are installed locally on the Jenkins server. This will also need to be considered when planning the Jenkins pipeline.
When dependencies’ source code is changed, every relevant firmware and application need to be rebuilt to ensure that no module ends up being broken until someone in the future tries to compile its firmware. The CI pipeline acts as a type of smoke test in that it ensures that each and every module’s source code remains buildable and that the modules can run any tests implemented for them.
5.5 Challenges
It is clear that a single declarative style pipeline per source code repository won’t be enough to meet all these requirements, as its syntax and functionalities are quite restrictive by design (Jenkins.io, Documentation: Pipeline syntax. Accessed on 2nd April 2018). It won’t allow for the conditionality that the requirements specified in the previous chapter set. The declarative pipeline can include blocks of scripted pipeline code, which are far more flexible, to the limits imposed only by the Groovy scripting language (Jenkins.io, Documentation: Pipeline syntax. Accessed on 2nd April 2018).
However, without a way to parameterize the pipeline through some sort of external input, the pipeline structure would have to be repeated in multiple Jenkins files with different built in variable values for the different hardware. That would increase the administrative burden whenever a change must be made and opens up for introducing bugs and inconsistent behavior down the road. However, the declarative syntax is desirable, as it is the one recommended by Jenkins team and it also provides a better visualization of the CI pipeline in the Jenkins GUI. Jenkins has available a plug-in that provides parameterized builds, but the parameters for that plug-in would need to be inserted in a job specified inside the Jenkins GUI, which would further break away from the endeavor of putting parts of the infrastructure and processes into revision controlled files and add functionality duplication and administrative overhead.
5.6 Implementation
The common denominator for all the different requirement permutations is the stages and steps that are necessary to implement. What varies though is how each step is implemented for the various scenarios described above. Question then becomes how to both encapsulate the similarity of the overall Jenkins pipeline structure but facilitate different implementations details. Consult Appendix 1 for an overall structure of the pipeline and variations that need to be facilitated at each stage.
This was accomplished by reducing the actual Jenkinsfiles to maps containing parameters that describe the target of the build and include all the necessary information to facilitate runtime decisions on how to accomplish the pipeline steps.
Figure 7. A Jenkinsfile containing a map of the different build parameters
The parameters are stored inside a custom Jenkins DSL block that retrieves the necessary pipeline structure from a Jenkins shared library file. The parameters that are brought in to the pipeline environment as input from the custom Jenkins DSL block are passed through a function that validates them and computes some additional parameters based on the ones defined in the Jenkinsfile.
After validation and computation, the extended set of parameters is injected into the pipeline’s runtime environment. The pipeline can then use these parameters as input to Jenkins Shared Library functions.
Figure 8. A Jenkins pipeline that uses 'pipepars', a map of pipeline parameters to control the different steps
The function can do its workload and branch the execution based on these parameters as necessary.
Shell scripts were created to include new build targets to reduce the need for the developers to remember different sets of build flags and to provide a simple interface for Jenkins to build different binaries. Now the Jenkins functions can just call these
shell scripts to run the build process. The scripts are also available for anyone who checks out the source code repository.
Where Docker is used, Windows bat files and Linux shell scripts were added to the repositories to include suitable Docker run commands. These can be used by both Jenkins as well as anyone who checks out the source code and has Docker installed locally. The script files, whether for Windows or Linux, utilize Make and the Makefiles inside a Docker container containing the suitable build toolchain.
The resultant build artifacts are stored and made available in a predefined format for everyone through the Jenkins GUI. After this, they are deployed to WoT Controller, which acting as the bus NMT master will pick up the new firmware files and update the CAN bus nodes. After this, a suitable XContinuousIntegration call is issued and the test automation can take over.
Figure 9. HCM2010 latest build artifacts in the Jenkins GUI
6 IMPLEMENTING THE TEST AUTOMATION
It was decided that the first type of testing that would be implemented as a proof of concept would be testing of Guitu scripting block functionality. Testing the scripting blocks already tests a lot more than the blocks themselves. It also executes a lot of the underlying GRT code to verify its functionality. Testing will need to happen every night on the latest versions of each firmware. Both Jenkins and the team of testers will need to be able to trigger any single test or a set of tests using XStudio.
6.1 Challenges
In the beginning, most of the challenges stemmed from the fact that the testing needs to be implemented in Guitu. There seemed to be a lot of logic that needs to be similar between the different SUTs and possibly different Guitu test configurations in the future. All of this foretold about a lot of code duplication resulting in a heavy administrative burden, especially if some of the duplicated code units needed to be changed. Another challenge was to figure out how to provide suitable test inputs and get the test result back from the test configuration during runtime and be able to compare that to what was expected from the test. In the end, both questions had a very straightforward answer, but figuring them out took a few iterations. The intermediate iterations will be discussed in the Retrospective chapter. Integrating Guitu scripts and GRT with XStudio also poses some questions that need answering.
6.2 Implementing the Wall of Test
The WoT starts logically inside XStudio. There, a test campaign session is run. This campaign session includes one or more tests which in turn include one or more test cases. XStudio schedules this test campaign session with an XAgent that is running on a Linux laptop colloquially known as The WoT Master.
The WoT Master is connected to a CAN network through a USB-CAN adapter and the SocketCAN software interface. SocketCAN uses Berkeley socket API, the Linux
network stack and implements the CAN device drivers as standard Linux network interfaces (The Linux Kernel Archives. [Accessed on 22nd April 2018]). The laptop is also setup with python-canopen, a FOSS Python library that implements the CAN-Open protocol.
The XAgent on The WoT Master picks up this campaign session and runs XStudio Python launcher passing it a set of parameters that are used to control the actual testing. For this, the launcher was customized a bit to better suit Exertus’ needs. The launcher expects to find a Python script located in the following folder:
<test_root>/<test_name>/<test_name>.py
This is a challenge, since the current WoT implementation only uses one generic Python script instead of many specific ones. The challenge was overcome by modifying the Java code of the Python launcher so that when it is run, it creates this directory structure, but with a symbolic link pointing at the actual script.
<test_root>/<test_name>/<test_name>.py -> <test_root>/WoT.py
It would have been simpler just to hard code the actual launcher script, but because of the way XStudio expects to be notified of finished tests, this would’ve blocked any chance of running tests in parallel in the future.
The XStudio Python launcher is modified so that it launches WoT.py with the following set of parameters:
- --test_id: ID number of the test in XStudio
- --sut_name: Name of the SUT in XStudio
- --testcaseindex: Index of the test case in XStudio
- --log: Name of the test result log file to be created in format <test name>_<test case index>.txt
WoT.py then parses these command line arguments to control the rest of the testing. It reads a YAML file whose name corresponds with --test_id. The file contains a test
configuration, which for now is a map of test inputs that should be used for the test case indicated by --testcaseindex together with an expected output of the test case with the given inputs.
Figure 10. A YAML file containing two inputs for test id 1170
--test_id and the test inputs read from the YAML test configuration are then written into correct SUT’s object dictionary through the SDO protocol. When all the necessary information is written in to the OD, one last entry called runflag is set to a certain value to let the SUT know that it can now start running a test.
Figure 11. Parts of class TestCase that show writing the CANOpen object dictionary and running the test case
A Guitu script that is run periodically on the SUT then picks up this runflag signal, inspects the test-id and runs a system-global test selector script that points it to the script that implements the actual test. This test case is then run with the values written in to the OD used as inputs to the Guitu script that implements the test case. When the test is finished, the result is written in to the OD and runflag is set to a value that signals the controlling Python script that the test was finished successfully. The Python script polls the runflag value. When it detects a finished test, it reads the test result from the OD of the current SUT and outputs it into a log file in a format expected by XStudio. It then signals XStudio that the test is completed by writing an empty file with the name test_completed.txt.
XStudio launcher picks up the creation of this file, parses the log file and writes the test result in to the XStudio database. If there are remaining test cases in the test, they are run similarly. When all the test cases have been completed, the test is ready and the next one can be run until all the tests in the campaign session have been finished.
A test operator can just build a test campaign in XStudio, create the test case configuration file with YAML and implement the test scripts in Guitu. After this these can be run on demand from the XStudio or by Jenkins via XContinuousIntegration. A minimal amount of utility scripting needs to be done for each SUT in Guitu.
Figure 12. The full utility script that is required for each SUT in Guitu.
7 CONCLUSIONS
The main goal of this thesis was accomplished. Exertus made a major stride towards CI by implementing nightly build and building facilities for automated building and testing. Further developments are now a matter of implementing more and different kinds of tests and bringing in more hardware modules under CI and testing. Exertus can now start collecting experience and feedback to guide future development of the system and make informed decisions on future development based on this experience. With the power of Python, CAN bus, the CANOpen protocol and all the functionality provided by the GRT the system is very robust and extensible. The testers can implement the test scripts in the familiar Guitu environment and specify all the test inputs for the test scripts in a user-friendly YAML configuration file that can be version-controlled. The author strongly believes that it is a great compliment to Exertus’ pre-existing testing regimen given some time to mature.
The final implementation of the test automation system is surprisingly simple, but the path to that solution went through a couple of less successful iterations, that were quickly deemed sub-optimal in varying aspects. The first version of the system was based entirely on Guitu configurations, which relied on text file based inputs to parameterize the testing. Similarly, all the log output was done via Guitu scripting. This does not scale very well and introduces a lot of copy and paste scripts that build an administrative burden for the future, especially if something needs to be changed. Some of this logic would also have to be copied to other Guitu configurations to implement different kinds of testing. Another downside to this approach was the fact that one extra MIC module would have to be dedicated as a controller module for the SUTs, introducing redundant hardware to the Wall of Test.
The next implementation relied on Linux shell scripts, Exertus CLI CAN client Execan and the CANOpen PDO protocol. The goal was to put more logic into version controllable, reusable code and less inside the Guitu configuration. All the code was still run on a MIC module. This was a step into the right direction, but due to some of the properties of Execan this was not ideal either. This could have probably been overcome by modifying Execan and to some extent by using SDO instead of PDO.
The implementation after this relied on Python and the CAN bus, but was still run on a MIC module. This wouldn’t have been a problem otherwise, but an embedded hardware module such as the MIC is quite inflexible when it comes to installing new software, making it more difficult to leverage for example Python’s external libraries. This implementation used some custom code to do basic SDO input and output through a Linux character device node representing the CAN bus. However, it was left unfinished when the final epiphany of moving all the Python code to the WoT Master struck resulting in more flexible development environment and the final implementation with python-can and python-canopen together with YAML test configuration files. This results in a minimal amount of logic stored inside the Guitu configuration.
Most of these sub-optimal implementations were result of the authors’ unfamiliarity with the CAN bus and the ways that CANOpen allows interacting with the modules. The initial requirements also gave the author an impression that as much as possible of the testing should be done in Guitu, which resulted in the first implementation but also in the realization that it would not scale well to larger amounts and several types of tests. From that point onward, after having cleared that it would be acceptable to implement some logic in written source code instead of Guitu configurations, the progress towards the final implementation was relatively quick.
Implementing the build automation in Jenkins was not entirely straightforward either, but with the help of Jenkins Shared Library it was possible to create a single pipeline script that had enough intelligence built into it so that it can run the different variations of the build, deploy and test process stages. Everything is built and tested nightly to provide an overview of all the different hardware products and their software and their status after the past day’s development work. Executables and programming libraries were made available through an easy to use GUI in Jenkins and employees can retrieve them without having to rely on the developers to get what they need, freeing up time and decreasing the amount of distractions. All the build procedures have now also been codified and the toolchains required to build the software are available for Jenkins reducing reliance on individual computers and persons.
7.1 Future
When the number and variety of implemented tests grow, it might be necessary to look into running some of the tests in parallel instead of the current sequential logic. Some corner stones to enable this were already laid in the design process. Tying together Phabricator and Jenkins to create more automation into the continuous integration environment, where every introduced change is automatically built and tested in real time is also a possible path worth considering.
CAN in Automation (CiA). No date. CAN data link layers in some detail [web page]. [Accessed on 1st April 2018] Available at: https://www.can-cia.org/can-knowledge
CAN in Automation (CiA). CAN high-speed transmission [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/can-knowledge/can/high-speed-transmission/
CAN in Automation (CiA). No date. CAN lower- and higher-layer protocols [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/can-knowledge/can/can-data-link-layers/
CAN in Automation (CiA). No date. CANopen: CANopen internal device architecture [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/can-knowledge/canopen/device-architecture/
CAN in Automation (CiA). No date. CANopen: The standardized embedded network [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/canopen/
CAN in Automation (CiA). No date. Network management (NMT) [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/can-knowledge/canopen/network-management
CAN in Automation (CiA). No date. Process data object (PDO) [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/can-knowledge/canopen/pdo-protocol/
CAN in Automation (CiA). No date. Service data object (SDO) [web page]. [Accessed on 1st April 2018]. Available at: https://www.can-cia.org/can-knowledge/canopen/sdo-protocol/
Docker, Inc. No date. Get Started, Part 2: Containers [web page]: Available at: https://docs.docker.com/get-started/part2
Docker, Inc. No date. Get Started, Part 1: Orientation and setup [web page]: Available at: https://docs.docker.com/get-started/
Exertus Ltd. No date. About Us [web page]. [accessed on 23rd Jan 2018].
http://www.exertus.fi/?lang=en > About us. Available at: http://exer-
tus.fi/?lang=en&page=About%20us.
Exertus Ltd. No date. Canto2 Monitoring and Commissioning Tool [PDF Docu-
ment]. [accessed on 25th Feb]. Available at: http://www.exertus.fi/files/Tiedos-
tot/Canto2_Commissioning_Tool.pdf
Exertus Ltd. No date. Guitu Programming Environment [PDF Document]. [ac-
Exertus Ltd. No date. HCM2010S Tech Doc [PDF Document]. [accessed on 25th
Feb]. Available at: http://www.exertus.fi/files/Tiedostot/Tech-
Doc_HCM2010S.pdf
Feb]. Available at: http://www.exertus.fi/files/Tiedostot/Tech-
Doc_MIC2000S_revD.pdf
Exertus Ltd. No date. Products [web page]. [accessed on 23rd Jan 2018].
http://www.exertus.fi/?lang=en > Products. Available at: http://exer-
tus.fi/?lang=en&page=Products
flow.ci / Medium.com, 2016. Introduction to Containers: Concept, Pros and Cons,
Orchestration, Docker, and Other Alternatives [web page]. Accessed on 2nd
April 2018. USA: A Medium Corporation. Available at: https://medium.com/flow-
ci/introduction-to-containers-concept-pros-and-cons-orchestration-docker-and-
other-alternatives-9a2f1b61132c
Free Software Foundation. No date. GNU make manual [web page]. Available at:
Jenkins.io. No date. Documentation, Blue Ocean [web page]. [accessed on 3rd
March]. Available at: https://jenkins.io/doc/book/blueocean/
Jenkins.io. No date. Documentation, Extending with Shared Libraries [web page].
[accessed on 3rd March]. Available at: https://jenkins.io/doc/book/pipe-
line/shared-libraries/
Jenkins.io. No date. Documentation, Installing Jenkins [web page]. Available at:
Jenkins.io. No date. Documentation, Pipeline: Declarative versus Scripted Pipeline
syntax [web page]. [accessed on 3rd March]. Available at: https://jen-
The Linux Kernel Archives. No date. Readme file for the Controller Area Network Protocol Family (aka SocketCAN) [text document]. Available at: https://www.kernel.org/doc/Documentation/networking/can.txt
### Appendix 1: Jenkins CI pipeline overall structure
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Support checking out with or without submodules. For bare metal devices, will also need to be able to control whether to checkout the submodule commits frozen in the Git superproject or head of the master branch.</td>
<td>Some of the jobs will need to accomplish some steps before they are ready for build. For example, GRT needs to retrieve ExGUI C header and library files from the ExGUI’s artifact repository. Vary the build naming convention.</td>
<td>Build procedures for the different devices look somewhat different. The logic needs to be branched here based on which device and application the pipeline is working with and whether or not it uses Docker. Build flavor will also need to be considered.</td>
<td>Different build targets need to package different artifacts and name the resulting file archive differently.</td>
<td>Different build targets need to archive different files.</td>
<td>Different firmware and application binaries need to be deployed to the WoT Controller, but with different naming.</td>
<td>The call to XCI will need to vary based on which device and software the pipeline is producing.</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://www.theseus.fi/bitstream/handle/10024/148721/Anttila_Henri.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 15090, "olmocr-version": "0.1.50", "pdf-total-pages": 53, "total-fallback-pages": 0, "total-input-tokens": 109689, "total-output-tokens": 18056, "length": "2e13", "weborganizer": {"__label__adult": 0.00034880638122558594, "__label__art_design": 0.0006823539733886719, "__label__crime_law": 0.00016641616821289062, "__label__education_jobs": 0.003658294677734375, "__label__entertainment": 0.00015294551849365234, "__label__fashion_beauty": 0.00016617774963378906, "__label__finance_business": 0.0006570816040039062, "__label__food_dining": 0.00029158592224121094, "__label__games": 0.0008711814880371094, "__label__hardware": 0.001868247985839844, "__label__health": 0.0002498626708984375, "__label__history": 0.00030422210693359375, "__label__home_hobbies": 0.00017535686492919922, "__label__industrial": 0.0005016326904296875, "__label__literature": 0.0004830360412597656, "__label__politics": 0.00016033649444580078, "__label__religion": 0.0003437995910644531, "__label__science_tech": 0.02264404296875, "__label__social_life": 0.0001577138900756836, "__label__software": 0.01158905029296875, "__label__software_dev": 0.95361328125, "__label__sports_fitness": 0.0002187490463256836, "__label__transportation": 0.0004804134368896485, "__label__travel": 0.00017845630645751953}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 72642, 0.02885]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 72642, 0.57656]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 72642, 0.8643]], "google_gemma-3-12b-it_contains_pii": [[0, 193, false], [193, 884, null], [884, 1973, null], [1973, 5280, null], [5280, 5280, null], [5280, 6499, null], [6499, 7889, null], [7889, 9287, null], [9287, 10567, null], [10567, 12310, null], [12310, 14617, null], [14617, 16798, null], [16798, 19054, null], [19054, 20491, null], [20491, 22008, null], [22008, 22554, null], [22554, 23462, null], [23462, 23942, null], [23942, 24377, null], [24377, 26267, null], [26267, 27753, null], [27753, 29362, null], [29362, 31685, null], [31685, 33358, null], [33358, 34222, null], [34222, 35692, null], [35692, 36653, null], [36653, 38527, null], [38527, 40497, null], [40497, 41487, null], [41487, 43219, null], [43219, 44288, null], [44288, 44387, null], [44387, 46067, null], [46067, 48029, null], [48029, 50165, null], [50165, 51590, null], [51590, 52058, null], [52058, 53016, null], [53016, 54995, null], [54995, 56737, null], [56737, 57426, null], [57426, 58934, null], [58934, 59009, null], [59009, 61398, null], [61398, 63804, null], [63804, 64290, null], [64290, 66230, null], [66230, 68421, null], [68421, 70606, null], [70606, 71087, null], [71087, 71087, null], [71087, 72642, null]], "google_gemma-3-12b-it_is_public_document": [[0, 193, true], [193, 884, null], [884, 1973, null], [1973, 5280, null], [5280, 5280, null], [5280, 6499, null], [6499, 7889, null], [7889, 9287, null], [9287, 10567, null], [10567, 12310, null], [12310, 14617, null], [14617, 16798, null], [16798, 19054, null], [19054, 20491, null], [20491, 22008, null], [22008, 22554, null], [22554, 23462, null], [23462, 23942, null], [23942, 24377, null], [24377, 26267, null], [26267, 27753, null], [27753, 29362, null], [29362, 31685, null], [31685, 33358, null], [33358, 34222, null], [34222, 35692, null], [35692, 36653, null], [36653, 38527, null], [38527, 40497, null], [40497, 41487, null], [41487, 43219, null], [43219, 44288, null], [44288, 44387, null], [44387, 46067, null], [46067, 48029, null], [48029, 50165, null], [50165, 51590, null], [51590, 52058, null], [52058, 53016, null], [53016, 54995, null], [54995, 56737, null], [56737, 57426, null], [57426, 58934, null], [58934, 59009, null], [59009, 61398, null], [61398, 63804, null], [63804, 64290, null], [64290, 66230, null], [66230, 68421, null], [68421, 70606, null], [70606, 71087, null], [71087, 71087, null], [71087, 72642, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 72642, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 72642, null]], "pdf_page_numbers": [[0, 193, 1], [193, 884, 2], [884, 1973, 3], [1973, 5280, 4], [5280, 5280, 5], [5280, 6499, 6], [6499, 7889, 7], [7889, 9287, 8], [9287, 10567, 9], [10567, 12310, 10], [12310, 14617, 11], [14617, 16798, 12], [16798, 19054, 13], [19054, 20491, 14], [20491, 22008, 15], [22008, 22554, 16], [22554, 23462, 17], [23462, 23942, 18], [23942, 24377, 19], [24377, 26267, 20], [26267, 27753, 21], [27753, 29362, 22], [29362, 31685, 23], [31685, 33358, 24], [33358, 34222, 25], [34222, 35692, 26], [35692, 36653, 27], [36653, 38527, 28], [38527, 40497, 29], [40497, 41487, 30], [41487, 43219, 31], [43219, 44288, 32], [44288, 44387, 33], [44387, 46067, 34], [46067, 48029, 35], [48029, 50165, 36], [50165, 51590, 37], [51590, 52058, 38], [52058, 53016, 39], [53016, 54995, 40], [54995, 56737, 41], [56737, 57426, 42], [57426, 58934, 43], [58934, 59009, 44], [59009, 61398, 45], [61398, 63804, 46], [63804, 64290, 47], [64290, 66230, 48], [66230, 68421, 49], [68421, 70606, 50], [70606, 71087, 51], [71087, 71087, 52], [71087, 72642, 53]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 72642, 0.16592]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
326a963fd0cc65df92d4d919ffba6338ffc7a575
|
Freya is a functional web programming stack for F#. Freya emphasises expressivity, safety, and correctness and is compatible with most server technologies in the .NET space.
The quickest way to get up and running with Freya and to get a feeling for what programming with Freya is like, is to dive straight in to the Getting Started tutorial. From zero to a Freya-based Hello World in a few minutes! Once you’re ready to move on, you can move on to the more in-depth documentation, as described below...
**Hint:** The Getting Started tutorial is the perfect way to take your first steps with Freya.
The documentation for Freya is organized into sections to help you find what you’re looking for more easily:
- **Topics** – contains guides specific to certain topics and may cover background information, explanations of design choices and approaches, and may cover multiple parts of Freya when they can be used in concert.
- **Tutorials** – contains longer form guides, usually covering a complete process of building some web application, and which are likely to cover various elements of Freya along the way.
- **Recipes** – contains guides to accomplishing specific tasks with Freya. They may range from the very simple to advanced use-cases, and may span the whole range of the Freya stack.
- **Reference** – contains guides to specific libraries and components of Freya, giving a technical view of what is available from each component and how they may be used.
## 2.1 Meta
For more “meta” topics around the Freya project and community (such as contact information, guidance on contributing, etc.) see the following sections:
### 2.1.1 Community
The F# community is a friendly place and we hope for the same for Freya. We encourage everyone to come and talk in our Gitter channel where all are welcome. It’s a great place to ask questions!
For keeping up to date with news on Freya and the ecosystem around it, follow Freya on Twitter – any news, changes, announcements, releases, etc. will be posted there, along with new blog posts, etc.
Most of all, we encourage you all to get involved, try Freya out, and tell us what you think!
### 2.1.2 Contact
There are several ways to get in touch!
Help/Advice
Probably the quickest way to ask a question and chat it through is to ask on the Freya Gitter channel – while it’s not always going to be answered immediately, people are often available, and responses don’t usually take too long! If you’re on the FSSF Slack channels, some of the maintainers are also often available there.
Issues/Features
If you want to raise an issue relating to Freya, or suggest a new feature – or an improvement to an existing one – then the main Freya repository on GitHub should be your first stop.
Issues, feature requests, etc. for Freya are tracked and managed using the GitHub Issues process. While Freya is split in to multiple repositories, issues raised against the main repository can be moved as needed, and it is often easier to work out where they should live later!
Miscellaneous
If you just want to send an email to a human being, then that’s possible too. Email freya@xyncro.com for an open-ended channel.
2.1.3 Contributing
Contributions to Freya in any form are very welcome. Whether you just want to correct some grammar in the documentation (!) or you’d like to contribute a new feature, you’re involvement will be appreciated and respected. If you’re not sure how you’d like to be involved, but feel that you would in some way – get in Contact. Regardless of experience, skill level or time available, there’s probably something for you!
Hint: If you’re not comfortable with GitHub – or Git in general – or you’re not familiar with any of the processes mentioned below, don’t worry. If you contact a maintainer by Email or on Twitter, they’ll help you through anything that you need – everybody needs a helping hand sometimes and nobody knows everything!
Documentation
If you’d like to contribute to the documentation, the quickest way is to use the “Edit Page” link at the bottom of any page – that’ll allow you to edit any content and send a pull request easily via GitHub.
Although it’s very likely that your help will be accepted without any issue, if you’re planning on making major changes to the structure or content of Freya documentation it’s probably worth discussing it first. Please get in Contact and talk before expending major effort!
Code
As with documentation, the quickest way to contribute is to create a fork on GitHub and submit a pull request. You are also welcome to log issues if you’d like to suggest features, report bugs, or make sure anything else relevant gets noted.
As with documentation, if you’re planning on putting significant effort in to a feature or change, please get in Contact first, to make sure that it’s likely to be accepted in to Freya – and to make sure it’s not already being worked on!
2.1.4 Policies
Freya does not have a large set of policies, but some aspects of the project do require explicit affirmation of expectations. Please read the following on conduct!
Conduct
While Freya does not currently have an explicit code of conduct, any behaviour which prevents others from finding Freya and the Freya community a welcoming and friendly environment will not be tolerated. If you are unsure whether something is likely to be offensive or upsetting to others, that is usually a good indication that you probably shouldn’t do it.
Were Freya to adopt a formal code of conduct, it would probably look rather like the Rust Code of Conduct – please refer to that document for the kinds of behaviour expected of people taking part in the Freya community.
Open source software matters, but it matters less than people.
2.2 Topics
Topic guides are available covering various aspects of building with Freya. These guides deal broadly with usage, background information, history, design decisions, etc. The topic categories are available directly from the top level navigation.
2.3 Design
The design of some aspects of Freya merits particular discussion – understanding the approaches taken can help get the most out of the available components of the Freya stack.
In particular, the following sections are key to some elements of the Freya stack:
- Machines – the design of Freya Machines merits in-depth explanation – it is a powerful and extensible approach to web programming.
2.3.1 Hopac
The “default” implementation of Freya uses F# async functions for most operations, and the internals are built as async. However, there is an alternative implementation available using the Hopac concurrent programming library available.
The Hopac version of Freya is effectively identical in functionality and usage, but uses a different underlying concurrency model – see Functions. This can make Freya easier to integrate with existing code where Hopac is in use, and also potentially gives some performance/resource usage gains (the Freya Benchmarks project is beginning to measure these reliably).
Packages
Packages which use the Hopac concurrency model are suffixed with .Hopac. If you are using the Freya meta-package for example, rather than taking a dependency on Freya, you would take a dependency on Freya.Hopac. This convention applies to all packages available in both variants.
Note: Not all packages are dependent on a concurrency abstraction, so not all packages come in both “default” and Hopac variants. Packages which do cannot be mixed and matched – attempting to use one package built for async and one built for Hopac together will result in errors!
2.3.2 Machines
Freya Machines are a powerful tool, but the programming model can be new to many, especially given the prevalence of web frameworks (particularly MVC-style frameworks) where the logic is spread throughout the whole framework. Machines can therefore look daunting at first, but they actually represent a conceptually simpler and more straightforward approach.
The following references give a directed explanation of Machine design and implementation in Freya, using an HTTP Machine as a convenient example where relevant.
- **Decisions** – decisions are the basis of the Machine programming model. Structuring logic as well-defined decisions gives more concision and clarity while (when combined with a suitable type model) also giving opportunities for powerful optimisations.
- **Configuration** – configuration of a Machine is the means by which it can be accurately tailored to a specific purpose. Configuration can be simple and static or dynamic – enabling a surprisingly powerful execution model.
- **Optimisation** – a structured decision model combined with suitable type information enables a useful and well-defined optimisation approach to the eventual logic. Machines can be optimised to only execute the minimum necessary execution path, giving efficient implementations of complex logic.
### Decisions
**Note:** This documentation is currently being written and reviewed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
### Configuration
**Note:** This documentation is currently being written and reviewed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
### Optimisation
**Note:** This documentation is currently being written and reviewed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
2.3.3 Optics
Optics (often – and in earlier versions of Freya – referred to as lenses) are a functional technique to enable you to work with complex data structures more easily. As data structures are generally immutable, modifying a data structure (or returning a new instance with the changes reflected) can be quite onerous if the data structure is large and complex, and the area you wish to change is deep within the data structure.
Optics, as their name implies, enable you to focus on a particular part of a data structure, treating it as if it were a normal top level instance of some data. You can think of doing your work through a lens (an optic), which will handle the mechanics (or optics, rather) of data structure modification for you.
Aether
Freya uses the Aether optics library. The guides to optics found there give a good introduction to the principles, along with more general information about the library itself (which is used extensively in Freya).
- Aether Guides – guides to the principles and usage of optics, with examples and explanation.
- Aether – the main Aether website.
Freya
Optics are a key part of Freya usage, used to work with data throughout many elements of the Freya stack. They are discussed in the reference documentation, as well as being used throughout any tutorial or recipe documentation.
- Optics – reference for optic usage in the Freya.Core library.
2.4 Standards
Freya is an intentionally standards based stack, whether that is broad public standards (like RFCs for HTTP, etc.) or community based, like OWIN. More on standards and how Freya works with them can be found in the following sections:
2.4.1 OWIN
OWIN (Open Web Interface for .NET - see owin.org) is a simple, community driven, standard interface between web servers and web applications. With a simple abstraction in place, people can concentrate on writing servers or applications, confident that they will run happily with a server/application that also supports the OWIN standard.
Interface
The OWIN standard interface is not a particularly complex one, as it’s designed to be a fairly “lowest common denominator” approach, with the aim of being applicable to the broadest possible ecosystem (so no relying on .NET features only accessible from specific languages, minority versions or frameworks, etc.)
The standard, in basic form, looks like this (straying in to C# for a moment):
```csharp
using AppFunc = Func<IDictionary<string, object>, Task>;
```
In effect it’s simply saying “I’m going to give you a dictionary containing request and response data. You muck about with that, and return me a Task when you’re done with it.” The server is then responsible for taking the eventual dictionary (called the Environment) and making sure that it gets turned in to a valid HTTP response, and sent back to the client.
Data
The obvious question now is “Where’s the request and response data?” Well, it’s in the Environment, boxed up with string keys. Some of the values are boxed strings, some boxed dictionaries, some boxed streams... It isn’t elegant, but it is workable, and making it this low level is one of the only ways to give an interface that multiple languages can actually work with.
As an example, the key owin.RequestPath in the Environment will get (or set, as it’s just a dumb dictionary) the path of the request. The key owin.ResponseBody is the stream used to write the response body, and so on.
As you’ll note – if you’ve got an F# hat on (our merchandise store is coming, we assure you) – this is all based on mutation of the Environment. That’s not a lovely thing to see in F#, and Freya does quite a lot of work to tidy this up (or at least hide it where you can pretend it doesn’t happen). You can see more about how it does so in the Core Reference section – see Core.
Servers
As you can see from the simplicity of the interface (known as the AppFunc or OwinAppFunc), there’s not much that a library needs to be able to do to work with a compatible OWIN server. Different OWIN servers, however, have different ways of asking for that AppFunc, so you may need to peruse the documentation for your specific server.
In the examples and tutorials we’ll see later, we’ll often use the Katana server, and we’ll show how simple it is to host Freya using that. If you’re using something else, it may be documented – see Servers. If not, feel free to either ask for guidance or even submit documentation – see Contributing!
2.4.2 Polyfills
The OWIN standard is a good base point for developing interoperable servers and frameworks, but like any standard it requires iteration and development. Sometimes it lacks features which Freya requires to work as well as possible – and in those cases Freya provides polyfills for particular server implementations which will “extend” the OWIN standard with additional features which Freya code can then test for and use where present.
This enables Freya to drive forward and improve at a fast pace.
For documentation on the polyfills currently available for Freya see the library reference.
- Polyfills – available polyfills for Freya, providing extensions to standards such as OWIN.
2.5 Versioning
Freya follows a semantic versioning approach to versioning, with some key points, due to the multi-library nature of the Freya stack.
The overall version of Freya (and the version used to define versions of documentation, etc.) is the version of the Freya meta-package – the package which has dependencies that make up a default Freya stack. The version of this meta-package may be increased driven by changes to the dependency set.
In effect, this means that a breaking change to a dependency will likely require a major version increase of that dependency. The next release of the Freya meta-package which includes the breaking change version will therefore also likely receive a major version increment.
In this way the version of the Freya meta-package signifies the version of a Freya stack which is known and designed to work well, and it may be many versions ahead of some of the versions of the packages that it depends upon – especially when some of the core packages are very stable.
As from Freya 3.0 (including release candidate builds) the versioning of Freya packages will be less significant from a “feature announcement” perspective, but will become a simple semantic versioning tool.
### 2.5.1 Upgrading
Upgrading to newer versions of Freya may still result in breaking changes (major version changes will signify this possibility). Guidance for working through these changes can be found in the following section:
- **Upgrading** – overview and version specific guidance on managing change in Freya versions.
**Upgrading**
Like any software project, Freya evolves over time. While backwards compatibility is maintained when possible (usually with a deprecation warning to help you to update code to newer constructs), sometimes changing scope or direction requires more significant change.
Guidance for working through specific changes is given in the following sections (this list is likely to expand over time):
#### 2.x → 3.x
This page covers the broad scope of change from 2.x releases of the Freya stack to 3.x releases – including release candidate (RC) builds.
**Packages** If you are using the Freya meta-package to manage your dependency on Freya, the new packages should be installed correctly on update, especially if you’re using Paket.
**Hint:** In general, Paket comes highly recommended as a reliable way of managing your Nuget – and other – dependencies. For this guide however, standard Nuget tools will work well enough.
**Libraries**
**Arachne** In versions prior to 3.x, Freya used the Arachne family of libraries as a type system for the web. As of 3.0, the Arachne libraries have been brought under the Freya stack umbrella and renamed the Freya Types libraries. This requires a change to existing code, with *Arachne.* being replaced by *Freya.Types.* for example, `open Arachne.Http` should now be `open Freya.Types.Http`.
**Core** Various changes to functions have taken place within the Freya Core library, all of which come with backward compatible functions with deprecation warnings. The deprecation messages give suggestions for the function to replace the obsolete function with. Most of these function changes have been about simplifying the optic-based programming model, and separating Pipeline functionality from basic Freya functionality.
**Optics** The previously provided optics in the Freya Lenses libraries have been renamed and moved to the Freya Optics libraries. Namespaces have changed to reflect this, and *Freya.Lenses.* has been replaced by *Freya.Optics.*. For example, `open Freya.Lenses.Http` should now be `open Freya.Optics.Http`.
2.5. Versioning
Routers The router included with Freya prior to 3.x has been moved and renamed to open up the way for additional more specialist routers to become part of the Freya stack. While the basic URI Template based routing has not changed (although the core has been rewritten to be more performant and accurate), the namespace has changed from Freya.Router to Freya.Routers.Uri.Template. Usage should be unchanged.
The old Freya.Machine.Router library to add a resource extension to the router is now included in the URI Template Router by default.
Machines As with routers, the machine included with Freya prior to 2.x has been moved and renamed to open up the way for more Machine implementations in future. The machine was previously available in the Freya.Machine namespace – this has now been changed to Freya.Machines.Http. The requirement to include HTTP functionality through the use of using http has been removed.
Machines have gone through a more extensive rewrite than other parts of Freya, and some of the configuration of the HTTP machine has now changed and been simplified. This should all be reflected in deprecated helper methods where applicable, but please do get in Contact if you find areas where this is not the case!
The extension mechanism for machines has also been revamped, as follows:
The CORS support is now available in the namespace Freya.Machines.Http.Cors. It can be enabled for a resource by including the keyword cors in your machine – using cors is no longer needed.
PATCH support is now an extension, and can be found in the namespace Freya.Machines.Http.Patch. It can be enabled by adding the patch keyword to your machine.
Full details of the new design of HTTP machines can be found in the HTTP machine reference section. Documentation work on Machines is an ongoing process. If the detail you are looking for is not there currently, please check back soon, and follow Freya on Twitter for updates on all Freya subjects, including additions/changes to documentation.
Polyfills Polyfills have been introduced to Freya in 3.x. They allow Freya to work around deficiencies in standards (such as missing data in the OWIN standard) and move faster than current standards allow. They are currently available for Katana based servers and Kestrel. For more information see the reference section on Polyfills.
Errors/Omissions? This document is a work in progress throughout the 3.x release candidate cycle. Please get in Contact if you find any errors or omissions, or if you have any suggestions for how this document can be more useful.
To send a pull request directly, you can use the Edit Page link at the bottom of this (or any other) page.
2.6 Tutorials
For now, see the Getting Started tutorial to create your first Freya application.
Note: More Freya tutorials are currently being developed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
2.7 Getting Started
You can be up and running with Freya in minutes! This quick guide will take you from zero to Hello World, using some of the high level building blocks that Freya provides out of the box – and tell you where to go to learn more about each of them.
2.7.1 Dependencies
You’ll be creating a self-contained Hello World implementation as a simple F# console application, so go ahead and create a new empty F# console application. You’ll be able to fit the whole thing in the single file that makes up the program (easily!) so there’s no need to worry about complex application structures or any of the complexities of frameworks like ASP.NET MVC.
**Hint:** In general, Paket comes highly recommended as a reliable way of managing your Nuget – and other – dependencies. For this guide however, standard Nuget tools will work well enough.
The first thing you’ll need is Freya and a suitable web server. In this case, the simple server from the Katana project will be used, although other servers like Kestrel, IIS, etc. will also work.
Using your preferred method of managing Nuget dependencies, install the required packages. Make sure you’re using the latest available versions!
```
PM> Install-Package Freya
PM> Install-Package Microsoft.Owin.SelfHost
```
The Freya package is a meta-package – it brings in all of the packages you’ll need for a common Freya application.
2.7.2 Code
At this point you should have an empty F# program. Start off by opening some common namespaces we’ll need to write our Hello World program. In this case, you’ll need three parts of the Freya stack.
```
open Freya.Core
open Freya.Machines.Http
open Freya.Routers.Uri.Template
```
**Greeting**
Now you’re ready to implement the Freya part of your Hello World application. Start by creating these two functions:
```
let name =
freya {
let! name = Freya.Optic.get (Route.atom_ "name")
match name with
| Some name -> return name
| _ -> return "World"
}
let hello =
freya {
let! name = name
return Represent.text (sprintf "Hello %s!" name)
}
```
You now have two functions which when used together return a representation of `Hello [World|{name}]` depending on whether `{name}` was present in the route. You’ll note that these functions are computation expressions – these are very common in Freya and form the basis of the programming model (although computation expression syntax is optional). For more on functions in Freya, see the Core reference. You’ll see more about routing in a following section.
Resource
Now you need some way of handling a request and using your `hello` function to return the representation of your greeting as the response – you need a way to model an HTTP resource. You can use the Freya HTTP Machine to do this. Machines are a powerful and high level abstraction – see the Machines reference for more, but for now you can simply use the very simply configured machine below, which will return your representation when a normal “OK” response is valid.
```csharp
let machine =
freyaMachine {
handleOk hello
}
```
Router
Finally, you’ll need a way to make sure that requests to the appropriate path(s) end up at your new Machine-based resource. You can use the URI Template based Freya router to do this easily. The following function will give you a simple router which will route requests matching the given path to your machine. For more on routing in Freya, see the Routers reference.
```csharp
let router =
freyaRouter {
resource "/*/hello{/name}" machine
}
```
2.7.3 Server
Now that you have all the “logic” covered you’ll need a way of serving it. You can use a simple self-hosted server, and fire it up in the main method of your program. As you’re using Katana here, you’ll need to create a type of a suitable shape for Katana to use as a start-up object. Here’s the code you’ll need, along with a main method to start things up.
```csharp
type HelloWorld () =
member __.Configure () =
OwinAppFunc.ofFreya (router)
open System
open Microsoft.Owin.Hosting
[<EntryPoint>]
let main _ =
let _ =
WebApp.Start<HelloWorld> ("http://localhost:7000")
let _ = Console.ReadLine ()
0
```
And there you have it! Try hitting `localhost:7000/hello` or `localhost:7000/hello/name` in a browser – you should have a Hello World up and running.
**Hint:** The code for the simple Freya Hello World example can be found in the freya-examples GitHub repository here - if you have any problems, try cloning and running the pre-built example.
Hopefully now you’re keen to learn more about the Freya components you’ve seen and what more they can do – and what others are available. The rest of the Freya documentation should help – and if you find it doesn’t, please reach out and suggest improvements – Contact is a good place to begin.
2.7.4 Full Code Listing
Here’s the complete code for the Hello World program in one place.
```fsharp
open Freya.Core
open Freya.Machines.Http
open Freya.Routers.Uri.Template
let name =
freya {
let! name = Freya.Optic.get (Route.atom_ "name")
match name with
| Some name -> return name
| _ -> return "World"
}
let hello =
freya {
let! name = name
return Represent.text (sprintf "Hello %s!" name)
}
let machine =
freyaMachine {
handleOk hello
}
let router =
freyaRouter {
resource "/hello{/name}" machine
}
type HelloWorld () =
member __.Configuration () =
OwinAppFunc.ofFreya (router)
open System
open Microsoft.Owin.Hosting
[<EntryPoint>]
let main _ =
let _ = WebApp.Start<HelloWorld> ("http://localhost:7000")
let _ = Console.ReadLine ()
0
```
2.8 Recipes
Recipes are available to help with common patterns of usage, categorised by the various areas of Freya and problems solved. The recipe categories are available directly from the top level navigation.
2.9 Integration
Integrating Freya with other systems (whether servers to host Freya applications, or other software frameworks) is essential. Freya should integrate widely through the use of the OWIN open standard, but it is not always obvious how
it should work in practice. Examples and information for integration are given in the following two recipe sections:
- **Frameworks** – integrating Freya with other frameworks, for example the Suave web framework. Freya plays nicely with others, and further and better integration is always a goal.
- **Servers** – integrating Freya with servers for hosting. While OWIN is an open standard, the approaches to integrating OWIN vary between server implementations.
## 2.9.1 Frameworks
Currently documented integrations:
### Suave
**Note:** This documentation is in the process of being written and reviewed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
## 2.9.2 Servers
**Note:** Pull requests to Freya documentation adding or extending information on usage with any particular server are particularly welcome. Freya should be broadly compatible, and every effort will be made to solve compatibility issue if they are discovered.
Currently documented integrations:
### Katana
It’s very simple to integrate Freya applications with the Katana server, especially using the Microsoft OWIN SelfHost options. A simple example is show below:
```csharp
// Freya
open Freya.Core
let application =
freya { ... }
let owinApplication =
OwinAppFunc.ofFreya application
// Katana
open Microsoft.Hosting
type Application () =
member __.Configuration () =
owinApplication
// Main
```
This will give a Katana based server running Freya-delivered content in a console application.
### 2.10 Routing
Routing is a potentially complex topic which also usually conforms to various patterns under normal use. Some of the more common approaches and techniques are defined here as recipes applying to various available Freya routing features.
#### 2.10.1 URI Templates
The URI Template type library, combined with the Freya.Routers.Uri.Template library, gives a concise yet powerful approach to routing. URI Templates in routing can sometimes be slightly surprising in their behaviour (the specification has some interesting corner cases) but certain techniques are quite generically useful in routing. Some of those will be added here.
**Note:** Pull requests suggesting new techniques for routing with URI Templates are very welcome!
**Important:** The specification of URI Templates is broader than simple path templating and generation, and much of the specification deals with matching query strings, fragments, etc. This means that Freya expects to match a full path and query string. You can make sure this works when you may have an (optional) query string by defining a catch-all query string on the end of your route URI Templates like so: `{?q*}`.
**Lists**
Matching simple lists of values in URIs can be useful. Using simple URI Template matching, this is trivial:
```csharp
// This uses simple matching and list syntax to match lists of values
// separated by commas
let listTemplate =
UriTemplate.parse "/{(values*)}"
```
Freya Documentation, Release 3.0
``` ilişki
// /one,two,three ->
Freya.Optic.get (Route.list_ "values")
// -> Some [ "one"; "two"; "three" ]
```
## Pairs
Matching key/value pairs can also be a useful technique:
``` ilişki
// This uses simple matching and keys syntax to match lists of key/value
// pairs (x=y) separated by commas
let listTemplate =
UriTemplate.parse "/{pairs*}"
// /one=a,two=b,three=c ->
Freya.Optic.get (Route.keys_ "pairs")
// -> Some [ ("one", "a"); ("two", "b"); ("three", "c") ]
```
## Paths
It is often useful to want to match a whole path, regardless of what it might be – for example, a virtual file server of some kind may map a seemingly “physical” path to a different underlying abstraction.
``` ilişki
// This uses URI Template path segment matching and list syntax to
// match paths separated by "/" characters
let pathTemplate =
UriTemplate.parse "/{segments*}"
// /one/two/three ->
Freya.Optic.get (Route.list_ "segments")
// -> Some [ "one"; "two"; "three" ]
let prefixedPathTemplate =
UriTemplate.parse "/one{/segments*}"
// /one/two/three ->
Freya.Optic.get (Route.list_ "segments")
// -> Some [ "two"; "three" ]
```
### 2.11 Reference
Reference documentation for Freya contains guides to specific libraries along with guides for using Freya as part of a larger system. These are technical guides and give an overview of general use, rather than a recipe-like approach. The reference documentation is designed to be referred to when you’re using Freya.
The reference documentation is divided into the main sets of libraries that make up the Freya stack. The library references cover the complete set of Freya functionality, and given both semantic and syntactic reference to the basic usage of the libraries.
When you’re looking for more general information on how to work in Freya, and how to think about solving problems using Freya, you might want to look at some of the other documentation options, particularly:
- **Topics** – for focused guides to areas of development with Freya.
• Recipes – for Freya-based solutions to common problems.
2.12 Core
Freya.Core provides the basic abstractions on which the Freya stack is built. Most of the types and basic functionality used by the higher level parts of Freya depend on the basics defined in Freya.Core. These essential elements of Freya are defined in the following sections:
2.12.1 Functions
The main abstraction in Freya is an abstraction over the OWIN state – see OWIN. As this is functional programming, you need to pass the state around to functions which require it (and return it from functions which have modified it).
Doing such a common thing manually would become a chore very quickly. The solution is the Freya<'a> function, which has the following type:
```fsharp
type Freya<'a> = State -> Async<'a * State>
```
In the case of the Hopac variant of the Freya stack – see Hopac – the type is instead defined as:
```fsharp
type Freya<'a> = State -> Job<'a * State>
```
The State type is a wrapper around the OWIN Environment - it holds a few additional data structures, the relevant part is the OWIN Environment.
A function of type Freya<'a> takes the state, and asynchronously (or as a Hopac Job) returns a value of type ’a and the state. The concurrency options are made available here as one or other of these abstractions is commonly used in web programming. This makes it easy to integrate Freya with existing libraries and software.
Syntax
The Freya<'a> type would be awkward to implement manually throughout applications, and F# allows for useful syntactic extension in the form of computation expressions.
A freya computation expression is provided to make it simpler to write code using Freya, and the functions available throughout Freya are easily usable with this syntax.
Note: This syntax is not compulsory – it is possible to use a more operator-based style when writing Freya code if you prefer.
The computation expression syntax looks like this:
```fsharp
let double x =
freya {
return x * 2
}
```
The signature of this function is int -> Freya<int>, showing a simple way to work with functions which now have the State threaded through them. Of course, this function doesn’t do anything with the State that it has available – the next section shows how State can be used.
State
The important part of the Freya approach to programming is to make programming with state transparent and functional. The most basic way to use information contained within the state is to get the `State` instance and to use some element of it, as seen below:
```fsharp
let readPath =
freya {
let! state = Freya.Optic.get id_
return state.Environment."owin.RequestPath":?> string
}
```
The first part of this function gets the `State` instance, and the second part extracts some data from it and returns it. Note that the first line uses a `Freya<_>` function – requiring the use of the `let!` syntax for computation expressions.
This very basic usage works, but is not a compelling approach – it can be improved significantly, as detailed in the next section:
- **Optics** – using Optics in Freya for safe, typed data manipulation.
Summary
The basic abstraction of Freya has been introduced, along with the Freya computation expression.
```fsharp
// Freya<'a> (State is described)
type Freya<'a> =
State -> Async<'a * State> // (or State -> Job<'a * State>)
// Freya computation expression
freya { ... }
```
2.12.2 Optics
In the previous section, you saw that the underlying `State` instance, and elements of it, could be accessed within a Freya computation expression. While this is workable, it is an untidy and weak approach from the perspective of a strongly typed language.
The solution to this in Freya is to use optics – see the Optics topic for a general introduction – to enable a safer and more functional approach.
Approach
You saw in the previous example (and it’s defined in the OWIN specification) that the data is held within dictionary structures within the state. Here are two ways to retrieve data, the first using the previous naive approach, the second using a pre-defined optic to access the data:
```fsharp
// The previous way, using raw access to the state
let readPathRaw =
freya {
let! state = Freya.Optic.get id_
return state.Environment."owin.RequestPath":?> string
}
// The optics way
let readPath =
freya {
return! Freya.Optic.get Request.path_
}
```
The optic approach is clearer and simpler, and also safer – the optic gives type-safe access to the data. Here the `Request.path_` optic, defined in the `Freya.Optics.Http` library, is used to focus on the correct part of the state, and ensure that the data contained is present and correctly mapped to an appropriate type.
The same optic can be used to set the data, or to map a function over the data – the optics are bi-directional. Here’s an example of a function which instead writes to the request path.
```fsharp
let writePath path =
freya {
do! Freya.Optic.set Request.path_ path }
```
The same lens can be used, the only difference is the function used – `Freya.Optic.set` versus `Freya.Optic.get`.
**Lenses and Prisms**
The OWIN specification makes it clear that not all data in the OWIN *Environment* will always be present. Some data is optional, so you might find yourself trying to read data that doesn’t exist. In a more general sense, you can construct optics that may not always be able to traverse a data structure to the data that you want. These lenses are often called prisms, as opposed to the simpler optics – lenses – you saw in the previous section. A lens is an optic to a value of ’a – a prism to a value of ’a option.
In versions of Freya prior to 3.0 (due to the way that earlier versions of Aether worked), you needed to use different functions to work with lenses and prisms (then termed lenses and partial lenses). However, from 3.0 onwards, you can use the same methods to work with lenses or prisms, giving a smaller and more consistent API.
Here’s an example using a prism:
```fsharp
let readStatusCode =
freya {
return! Freya.Optic.get Response.statusCode_ }
```
This function is of type `Freya<int option>`, as the prism returns an option of the value (the response status code is not a required data element in the OWIN specification).
**Morphisms and Types**
You might be wondering about the description of optics as providing typed access to the data here. In the underlying data, it is defined in the OWIN specification that this data is stored as an obj (boxed) in a dictionary. How can you work with it as a string, or an int (and in the case of more complex elements of HTTP as a full typed representation of a header, for example)?
The optics defined are composed with morphisms – functions which can convert a data structure to and from another form. In the case above, the response status code is being converted to and from an `int` transparently as part of the optic access.
This is an important (and powerful) feature of Freya – you can work with strongly typed, expressive representations of data, even though underneath the surface the data is the old string-based web world.
Here’s a quick example, retrieving a header value from the request and receiving a strongly typed representation of that header back, which can be used with all of the type-based F# techniques and tools:
```fsharp
let readAccept =
freya {
return! Freya.Optic.get Request.Headers.accept_ }
```
// Might return something like...
Here a strongly typed representation of the “Accept” header is retrieved if it’s present – and you’ll receive a fully decomposed, typed representation of that header which you can pattern match, inspect and work with – see Types for more on the type system that Freya uses.
**Summary**
The Freya approach to working with stateful data has been defined, giving the common functions for working with data, and some optics that are provided with Freya.
```freya
// Get a value from the state using an optic
Freya.Optic.get : optic 'a -> Freya<'a>
// Set a value in the state using an optic
Freya.Optic.set : optic 'a -> 'a -> Freya<unit>
// Map a function over a value in the state using an optic
Freya.Optic.map : optic 'a -> ('a -> 'a) -> Freya<unit>
// Additionally, common Freya provided optics are available in:
open Freya.Optics.Http
open Freya.Optics.Http.Cors
```
### 2.12.3 Pipelines
Functional programming makes much of the ability to compose functions simply – one of the joys of functional programming is being able to compose complex functionality from simpler parts with confidence.
The common Freya<'a> functions are quite simple to use together in various ways (the computation expression syntax being the most obvious – calling another Freya<'a> function within a computation expression is as simple as using the let! or do! syntax. However, it turns out to be useful to introduce another building block, which makes it easier to build systems which compose at a more coarse-grained level.
**Definition**
Freya introduces the concept of a Pipeline function, which is defined like this:
```fsharp
type Pipeline =
Freya<PipelineChoice>
and PipelineChoice =
| Next
| Halt
```
It’s simply a normal Freya<'a> function, where ‘a is constrained to be PipelineChoice. This is used as a building block throughout various Freya libraries.
Composition
The simplest example of this is the basic composition of some `Pipeline` functions, composed. The `Pipeline.compose` function can be used to do this. This function has a basic logical model – compositions of pipeline functions will halt when the first value of `Halt` is returned:
```ocaml
let yes = freya { return Next }
let no = freya { return Halt }
// Both of these functions will be run
Pipeline.compose yes no
// Only the first of these functions will be run
Pipeline.compose no yes
```
This becomes a useful technique when you want to stop processing a request in a certain situation – for example, you may have written a function which should halt processing if the user making the request is not authorized.
Operators
Freya always provides named functions for every piece of functionality, but some parts of libraries lend themselves well to the use of custom operators to make definition more concise and readable. As an alternative to the `Pipeline.compose` function, the infix syntax `>=` is also available. This has the advantage that chains of composition become significantly simpler to read and write:
```ocaml
open Freya.Core.Operators
let functionComposed = Pipeline.compose (Pipeline.compose yes no) yes
let operatorComposed = yes >= no >= yes
// or if you prefer...
yes
>?= no
>?= yes
```
It’s a matter of taste and is definitely subjective – but if you find the operator approach clearer, Freya makes them available.
Summary
The `Pipeline` function concept has been defined, and a simple approach to composing them.
```ocaml
// Types
type Pipeline = Freya<PipelineChoice>
```
2.12.4 Integration
As previously detailed, Freya is built on the OWIN open standard for interoperability between .NET web servers and web frameworks (or stacks).
You should be able to use Freya with any OWIN compatible web server – if you can’t, please raise an issue and we’ll help you however we can.
Functions
For recipes for integrating with specific servers and frameworks, see the Integration documentation. In a general sense however, it is usually only needed to use one function to bridge the Freya and OWIN worlds. We need to be able to turn a Freya function in to an OWIN Application Function, or AppFunc.
```fsharp
let freyaSystem =
freya {
...
}
let freyaAppFunc =
OwinAppFunc.ofFreya freyaSystem
```
The OwinAppFunc module contains functions to take a Freya<_> function and turn it in to an OwinAppFunc. Note that the return value of the function converted will be discarded when it’s run, as there is no use for it in this case (this does mean that any Freya<_> function can be used).
**Hint:** OWIN specifies signatures for middleware functions – OwinMidFunc – as well as application functions – OwinAppFunc. The OwinMidFunc module contains useful functions, but it is currently considered experimental and is not yet documented.
Summary
The basic conversion of a Freya function to an OWIN compatible function has been demonstrated.
```fsharp
// Convert any Freya<_> function to an OwinAppFunc
OwinAppFunc.ofFreya : Freya<_> -> OwinAppFunc
```
2.13 Types
Freya is driven by a strongly-typed approach to working with the web, and so includes a set of libraries (Freya.Types.*) which model many of the constructs found in web specifications, particularly those dealing with HTTP, URIs, etc. These libraries were previously known as the Arachne project, but were brought under the Freya umbrella in the 3.0 release.
2.13.1 HTTP
The Freya.Types.Http library implements types which represent the semantics of the following standards:
- RFC 7230 – Message Syntax and Routing
- RFC 7231 – Semantics and Content
- RFC 7232 – Conditional Requests
- RFC 7233 – Range Requests
- RFC 7234 – Caching
- RFC 7235 – Authentication
This set of RFCs covers basic types present in HTTP requests and responses, principally the data found in the headers of HTTP messages. Strongly typed representations and parsers are given.
Note: Full documentation for the individual type designs within Freya.Types.Http is not currently available, but will be added at a later stage. Inspecting the values returned however should be straightforward and logical, and all typed representations map very closely to the logical design/grammar defined within the appropriate RFC or Recommendation.
To use the types:
```
// Working with the types
open Freya.Types.Http
```
2.13.2 HTTP CORS
The Freya.Types.Http.Cors library implements types which represent the semantics of the following standards:
- W3C Recommendation on CORS
- RFC 6454 – The Web Origin Concept
The implementation of the Recommendation consists of a set of typed headers. Additionally the Origin header is implemented as defined in RFC 6454. Strongly typed representations and parsers are given.
Note: Full documentation for the individual type designs within Freya.Types.Http.Cors is not currently available, but will be added at a later stage. Inspecting the values returned however should be straightforward and logical, and all typed representations map very closely to the logical design/grammar defined within the appropriate RFC or Recommendation.
To use the types:
2.13.3 Language
The Freya.Types.Language library implements types which represent the semantics of the following standards:
- RFC 4647 – Language Ranges (Matching of Language Tags)
- RFC 5646 – Language Tags (Tags for Identifying Languages)
Strongly typed representations and parsers are given.
No optics are given as a corresponding Freya.Optics.* library as these types are not present directly within HTTP messages, but they are used within some types in the HTTP and HTTP CORS libraries, and may be used directly when working with some of the higher levels of abstraction in the Freya stack which expect strongly typed Language Tags/Ranges as configuration values.
Note: Full documentation for the individual type designs within Freya.Types.Language is not currently available, but will be added at a later stage. Inspecting the values returned however should be straightforward and logical, and all typed representations map very closely to the logical design/grammar defined within the appropriate RFC or Recommendation.
To use the types:
```haskell
// Working with the types
open Freya.Types.Language
```
2.13.4 PATCH
The Freya.Types.Patch library implements types which represent the semantics of the following standard:
- RFC 5789 – PATCH Method for HTTP
Strongly typed representations and parsers are given, along with matching and rendering logic.
Note: Full documentation for the individual type designs within Freya.Types.Patch is not currently available, but will be added at a later stage. Inspecting the values returned however should be straightforward and logical, and all typed representations map very closely to the logical design/grammar defined within the appropriate RFC or Recommendation.
To use the types:
```haskell
// Working with the types
open Freya.Types.Patch
```
2.13.5 URI
The Freya.Types.Uri library implements types which represent the semantics of the following standard:
- RFC 3986 – Uniform Resource Identifier (URI): Generic Syntax
Strongly typed representations and parsers are given.
No optics are given as a corresponding `Freya.Optics.*` library as these types are not present directly within HTTP messages, but they are used within some types in the HTTP and HTTP CORS libraries. They are also used in higher levels of abstraction within the Freya stack.
**Note:** Full documentation for the individual type designs within Freya.Types.Uri is not currently available, but will be added at a later stage. Inspecting the values returned however should be straightforward and logical, and all typed representations map very closely to the logical design/grammar defined within the appropriate RFC or Recommendation.
To use the types:
```ml
// Working with the types
open Arachne.Uri
```
### 2.13.6 URI Template
The `Freya.Types.Uri.Template` library implements types which represent the semantics of the following standard:
- RFC 6570 – URI Template
Strongly typed representations and parsers are given, along with matching and rendering logic.
No optics are given as a corresponding `Freya.Optics.*` library as these types are not present directly within HTTP messages. These types are used extensively in the Uri Template Routing library, and in work on the representation of Hypermedia standards.
**Note:** Full documentation for the individual type designs within Freya.Types.Uri.Template is not currently available, but will be added at a later stage. Inspecting the values returned however should be straightforward and logical, and all typed representations map very closely to the logical design/grammar defined within the appropriate RFC or Recommendation.
To use the types:
```ml
// Working with the types
open Freya.Types.Uri.Template
```
### 2.14 Optics
The `Freya.Optics.*` libraries provide optics from the Freya `State` type to strongly typed properties of the request, response, etc.
#### 2.14.1 HTTP
The `Freya.Optics.Http` library provides optics from the `State` to the various aspects of the request and response, modelled using the types from `Freya.Types.Http` (and other Freya.Types.* libraries where needed). These optics are usable directly within a `freya` computation expression, working with the optic functions – see Optics.
The HTTP optics are likely to be the most commonly used optics dealing with request and response data. To use the optic the following modules should be opened:
// Working with Freya optics
open Freya.Optics.Http
// Working with the Freya types (maybe required)
open Freya.Types.Http
The optics are all provided under the Request and Response modules (e.g. Request.path_), along with sub-modules for headers (e.g. Request.Headers.accept_).
### 2.14.2 HTTP CORS
The Freya.Optics.Http.Cors library provides optics from the State to the various aspects of the request and response modelled using the types from Freya.Types.Http.Cors (and other Freya.Types.* libraries where needed). These optics are usable directly within a freya computation expression, working with the optic functions detailed in Optics.
These optics are probably not likely to be commonly used, especially when relying on some of the higher level abstractions available in the Freya stack, but they can be useful for writing new low-level code.
// Working with Freya optics
open Freya.Optics.Http.Cors
// Working directly with the types if required
open Freya.Types.Http.Cors
The optics are all provided under the Request.Headers and Response.Headers modules (e.g. Request.Headers.accessControlAllowOrigin_).
### 2.14.3 HTTP PATCH
The Freya.Optics.Http.Patch library provides optics from the State to the various aspects of the request and response modelled using the types from Freya.Types.Http.Patch (and other Freya.Types.* libraries where needed). These optics are usable directly within a freya computation expression, working with the optic functions detailed in Optics.
These optics are probably not likely to be commonly used, especially when relying on some of the higher level abstractions available in the Freya stack, but they can be useful for writing new low-level code.
// Working with Freya optics
open Freya.Optics.Http.Patch
// Working directly with the types if required
open Freya.Types.Http.Patch
The optics are all provided under the Request.Headers and Response.Headers modules (e.g. Response.Headers.acceptPatch_).
### 2.15 Routers
The Core library, along with the Types and Optics libraries, allow for the creation of powerful handlers for HTTP requests, but they don’t provide support for routing requests to specific handlers.
Routers are used to solve this problem, and allow for the aggregation of multiple handlers in to a more complex application. Freya allows for the possibility of multiple different implementations of routing, to support differing requirements. Currently Freya includes one router, based on URI Templates.
- **URI Template** – a router which efficiently uses URI Templates to dispatch HTTP requests to handlers, and exposing the matched data as strongly typed URI Template data types.
### 2.15.1 URI Template
The URI Template router uses URI Templates – supported by the URI Template library – to define and match routes. This is both powerful and useful – the same templates can be used to generate URIs when needed.
#### Routes
The URI Template router is based on mapping requests to Pipeline functions – see Pipelines if you’re not familiar with the Freya pipeline concept. It maps the request by matching the method and the path and query against a URI Template.
#### Syntax
The URI Template Router defines a custom computation expression (simpler and more limited than the freya computation expression. The computation expression uses a custom operation to let you define routes in a simple, expressive and typed way. The computation expression is named freyaUriTemplateRouter but is also aliased to freyaRouter for convenience!
#### Definitions
Routes are defined by specifying a requirement for the HTTP method (or verb), a requirement for the path, and the Pipeline function to call if the route is matched. Route matching effectively happens in definition order precedence, although the router internally converts the route definitions to an optimised trie for performance reasons.
Strongly typed values are used for the requirements, using types taken from the Types libraries, in this case Freya.Types.Http and Freya.Types.Uri.Template, as well as types from Freya.Routers.Uri.Template. Here’s an annotated example of setting up a router, including opening appropriate modules/namespace:
```ocaml
open Freya.Core
open Freya.Routers.Uri.Template
open Freya.Types.Http
open Freya.Types.Uri.Template
// Handlers
let handlerA = freya {
return Next
}
let handlerB = freya {
return Next
}
// Routing
let routeA =
```
2.15. Routers
UriTemplate.parse "/a/{id}"
let routeB = UriTemplate.parse "/b/{name}"
let routes = freyaRouter {
route Any routeA handlerA
route (Methods [ GET; OPTIONS ]) routeB handlerB }
Breaking this down, the first thing you will notice is the definition of two handlers, which are simple Pipeline functions:
let handlerA : Pipeline = freya {
return Next }
let handlerB : Pipeline = freya {
return Next }
Next in the code you will see two simple URI Templates defined. URI Templates can be used to generate URIs given a template and suitable data – Freya also allows to match on URI Templates, extracting the data to then be used. There are some caveats to matching URI Templates, but in general it is a good fit for many applications.
Two URI Templates are defined which will match the paths shown. The syntax for a match in this case is likely familiar – a simple match, capturing the braced terms (e.g. {id}).
let routeA : UriTemplate = UriTemplate.parse "/a/{id}"
let routeB : UriTemplate = UriTemplate.parse "/b/{name}"
Finally the router itself with the routes defined. The routes are defined using the route keyword in the computation expression. This takes three arguments:
- A UriTemplateRouteMethod, which may be All – matching any method, or Methods which takes a list of Method values which are allowed. In the example, the first route will match any method, the second only GET or OPTIONS requests.
- A UriTemplate which will be matched against the request path and query.
- A Pipeline which will be called if the method, and the path and query are matched.
let routes = freyaRouter {
route Any routeA handlerA
route (Methods [ GET; OPTIONS ]) routeB handlerB }
The router will call the Pipeline function of the first matched route. If no route matches, no pipeline will be called.
Type Inference
Freya 3.0 introduced a more extensive use of statically resolved type parameters (don’t worry if these are not familiar) to give more concise and flexible APIs. One of the places where this is used is in this computation expression. Rather than only taking a literal UriTemplateRouteMethod as the first parameter, the route function can actually take any value which has a static UriTemplateRouteMethod member. By default, this is defined for a few different types, all of which can be used interchangeably. That means that the following are all valid routes:
You will see that this potentially makes things clearer and more readable, allowing for simpler expressions of the same concepts. In addition to the Methods, both the template and the handler are also inferred - anything which has UriTemplate and anything which has Pipeline can be used. By default, this means that you can just use strings and they will be statically inferred as templates, and any Freya<_> function can be inferred as a Pipeline. This can mean that a previously more complex configuration can be made much simpler:
```plaintext
let routes1 =
freyaRouter {
route (Methods [ GET ]) (UriTemplate.parse "/hello") handlerA }
// is the same as...
let routes2 =
freyaRouter {
route GET "/hello" handlerA }```
**Pipeline**
In earlier versions of Freya, it was neccessary to call an explicit toPipeline function to use a router as a pipeline. This is no longer needed in 3.0+ – the router implements Pipeline and thus anything which expects to be able to infer a pipeline can accept a router.
**URI Templates**
In this example the URI Templates have been defined separately from the router. This could be done inline, saving space. However, it is often useful for multiple parts of a program to be able to refer to the URI Template as a first class item, so they are commonly defined outside of the router itself.
This becomes especially useful when you wish to return the URI of a resource as part of a response. You can use the same URI Template for routing and generating linking URIs, which prevents the two ever becoming unsynchronised, using the typed approach to prevent a class of error.
**Values**
As seen in Routes, it’s quite simple to map routes (the combination of method and path specification) to Pipeline functions. Once a route is matched however, you will likely need the handler to have access to the data that was matched as part of the URI Template.
Here is one of the URI Templates from the previous section:
```plaintext
let routeA =
UriTemplate.parse "/a/{id}"
```
You can see that if this route has been matched, a value for \{id\} should now exist. Freya aims for a consistent model of programming throughout, and so the approach to accessing this data is aligned to accessing any other data – it is considered to be part of the state.
Optics
As with accessing data from the request or response, accessing data from the route requires the use of a suitable set of optics. These are provided under the `Route` module. Here’s a function which will return the (id) value from the example:
```ocaml
let readId =
freya {
return! Freya.Optic.get (Route.atom_ "id")
}
```
There are several things to note here. The first is that route optics are prisms. You can’t statically be sure that a value will be present (even though intuitively you can know that it will be in certain contexts), so the optics must be prisms. Additionally, route optics are parameterised – as shown, it is passed the name of the value sought, in this case “id”).
Another key point to note is that there are three prisms available (all within the `Route` module). In this case, `Route.atom_` is used, but `Route.list_` and `Route.keys_` are also available. Briefly, this is due to the nature of data within the URI Template specification. It is possible to render and match more complex data structures with URI Templates (see the URI Template RFC for a sense of how URI Templates can be used in more advanced ways). Simple values will only usually require the use of the `Route.atom_` optic, but much more is possible – see the relevant recipes for more information.
Summary
Techniques for accessing matched values using optics have been shown.
```ocaml
open Freya.Routers.Uri.Template
// Optic for extracting string values from a matched route
Route.atom_ : string -> Prism<State, string>
// Optic for extracting string list values from a matched route
Route.list_ : string -> Prism<State, string list>
// Optic for extracting string pair values from a matched route
Route.keys_ : string -> Prism<State, (string * string) list>
```
Recipes
See also:
- **Routing** – as well as the library reference, a growing collection of routing recipes covering various techniques is maintained.
See also:
- **Routing** – as well as the library reference, a growing collection of routing recipes covering various techniques is maintained.
2.16 Machines
Freya provides powerful ways to interact with the web which are safe, expressive, and relatively low-level. However, Freya also provides some higher level abstractions to enable more effective and concise programming when interacting with complex standards.
Machines are one way of approaching this, and provide a different model of web programming, based around decision trees and declarative programming (don’t worry – this sounds complex and scary, but it isn’t!)
Understanding the way that Machines are built and used helps make the most of this powerful Freya feature, and the underlying approach and computational model is covered in some depth in the topic: Machines – design and implementation of a theoretical Machine.
Freya currently includes one machine (with extensions) for working with HTTP – additions may be made in future for complementary protocols, etc.
- **HTTP** – a Freya Machine for working with HTTP in a safe and semantically correct way, based on a purely functional declarative approach.
In addition to the documentation on specific Machines, all Freya Machines follow a defined set of Conventions which are useful to note.
### 2.16.1 HTTP
Freya lets you work with HTTP implicitly, using the typed but low-level tools found in Core combined with types and optics, such as the provided Optics. These are expressive and effective, but provide little in the way of structure.
HTTP is a fairly involved set of standards, and properly implementing the correct semantics of HTTP is not a trivial matter. Dealing with the correct logical approach to negotiating content types, working out the right approach to cache control and correctly expressing the state of the underlying resources, can be quite a lot to design when taken holistically.
**Freya.Machines.Http** is designed to solve this. The Machine lets you define just the properties of a resource you care about, and the Machine library handles the rest. You can specify as much or as little as you wish, all in a type safe manner, and be confident that HTTP semantics will remain consistent and correct.
As noted in the topic on the design of Machines, configuration of a machine is the key step in effective use. The HTTP Machine has extensive configuration options.
- **Decisions** – decisions influence the overall execution of the HTTP Machine, and enable you to define the behaviour of key aspects of your resource by answering true/false questions about the resource.
- **Handlers** – handlers enable the response to return representations of the resource when appropriate, as well as providing a potential point in the execution of the Machine to set additional headers, etc.
### Decisions
**Note:** This documentation is currently being written and reviewed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
### Handlers
**Important:** This documentation is currently partially complete and is in the process of being written and reviewed. Please check back soon. Documentation updates are also announced on the Freya Twitter feed – follow Freya there for up to the minute information on changes to this documentation, and other Freya news.
Handlers are called as the final step in an HTTP Machine execution – they are used to set properties of the response, usually a payload (where applicable) and potentially additional headers. Handlers are always optional – when a handler
is not defined, the response will simply be returned without a payload being set (and associated headers). This is a valid approach in many situations, especially in HTTP cases where a payload is not common for the response.
**Representations**
The HTTP Machine allows you to declare handlers in three ways, allowing you to use a simpler formulation when it is all that’s required. All handlers must return a `Representation`, which defines the content and associated metadata (such as media type, language, etc. where relevant), but this may be done in the following ways:
**Dynamic Negotiated** The most comprehensive case allows for the selection of a representation according to the content negotiation which the HTTP Machine may have performed (if you have configured the Machine to do so – see the section on Properties). In this case, the handler defined within the Machine must be of the form `Acceptable -> Freya<Representation>`, where `Acceptable` is a type giving the results of content negotiation. The handler may use this information to select the most appropriate representation.
**Dynamic** A simpler case occurs when content negotiation is not realistically required – this may often be the case for simpler APIs, or where the API only offers limited options (an all JSON API for example). In this case the handler must be of the form `Freya<Representation>` – the handler may work with the request, response, and other data, but is not given information regarding content negotiation.
**Static** The simplest case is for instances when the representation is known at compile time, and a handler of the form `Representation` can be defined. This is useful for simple static content, etc.
**Status Codes**
Handlers are defined and named according to the following tables, categorised by response status code (these codes, along with other commonly recommended/required headers will be set automatically). Note that some status codes may be returned by more than one handler, such as the handlers for a normal 200 response for OPTIONS requests, and for other requests.
### 2.16.2 Conventions
Freya Machines follow a package naming convention to make it clear what is available and how it should be used. The convention for naming is as follows:
- `Freya.Machines.<Machine>[.<Extension>]`
Using the example of the Freya HTTP Machine, this gives:
- `Freya.Machines.Http`
as the name of the core HTTP Machine library. The HTTP Machine also has extensions available to implement further web standards, or to integrate with other technologies/frameworks. Following the convention, this gives (for example):
- `Freya.Machines.Http.Cors`
- `Freya.Machines.Http.Patch`
2.17 Polyfills
Polyfills provide functionality which is not (and may never be) part of an open standard. Existing polyfills add existing data to the OWIN standard, enabling such things as more accurate routing. Polyfills are available for the following servers:
- **Katana** – polyfills for Katana-based implementations, including self-hosted and IIS hosted approaches.
- **Kestrel** – polyfills for Kestrel-based servers.
### 2.17.1 Katana
The Katana framework is the basis of self-host OWIN applications and also IIS applications. The **Freya.Polyfills.Katana** polyfill should be used whenever you are taking one of these hosting approaches. The polyfill should be used by inserting it in front of your Freya application in a pipeline composition:
```fsharp
open Freya.Core
open Freya.Core.Operators
open Freya.Polyfills.Katana
// Some pre-existing Freya pipeline (could be a router, function, etc.)
let myApp =
freya {
...
return Next }
// Compose a polyfill with the pre-existing pipeline
let composedApp =
Polyfill.katana
>?>= myApp
// Use as normal...
let owinApp =
OwinAppFunc.ofFreya composedApp
...
```
The polyfill currently adds additional data to the OWIN environment which enables routing to work more accurately (giving routers access to the raw, encoded form of the path and query).
### 2.17.2 Kestrel
The Kestrel server is the newer HTTP server built by Microsoft. The **Freya.Polyfills.Kestrel** polyfill should be used whenever you are taking one of these hosting approaches. The polyfill should be used by inserting it in front of your Freya application in a pipeline composition:
```fsharp
open Freya.Core
open Freya.Core.Operators
open Freya.Polyfills.Kestrel
// Some pre-existing Freya pipeline (could be a router, function, etc.)
let myApp =
freya {
...
return Next }
```
```javascript
// Compose a polyfill with the pre-existing pipeline
let composedApp =
Polyfill.kestrel
>>= myApp
// Use as normal...
let owinApp =
OwinAppFunc.ofFreya composedApp
...'''
The polyfill currently adds additional data to the OWIN environment which enables routing to work more accurately (giving routers access to the raw, encoded form of the path and query).
|
{"Source-Url": "https://buildmedia.readthedocs.org/media/pdf/freya/latest/freya.pdf", "len_cl100k_base": 15623, "olmocr-version": "0.1.50", "pdf-total-pages": 40, "total-fallback-pages": 0, "total-input-tokens": 77859, "total-output-tokens": 17775, "length": "2e13", "weborganizer": {"__label__adult": 0.0002772808074951172, "__label__art_design": 0.00025463104248046875, "__label__crime_law": 0.00015079975128173828, "__label__education_jobs": 0.0003159046173095703, "__label__entertainment": 5.418062210083008e-05, "__label__fashion_beauty": 8.946657180786133e-05, "__label__finance_business": 0.0001118779182434082, "__label__food_dining": 0.0002148151397705078, "__label__games": 0.0003948211669921875, "__label__hardware": 0.0003197193145751953, "__label__health": 0.00013315677642822266, "__label__history": 0.00012958049774169922, "__label__home_hobbies": 4.76837158203125e-05, "__label__industrial": 0.0001462697982788086, "__label__literature": 0.00015604496002197266, "__label__politics": 0.00012683868408203125, "__label__religion": 0.0002586841583251953, "__label__science_tech": 0.0012464523315429688, "__label__social_life": 6.99162483215332e-05, "__label__software": 0.0086669921875, "__label__software_dev": 0.986328125, "__label__sports_fitness": 0.00015652179718017578, "__label__transportation": 0.00021266937255859375, "__label__travel": 0.0001442432403564453}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 71748, 0.01946]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 71748, 0.52593]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 71748, 0.89266]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 0, null], [0, 0, null], [0, 174, false], [174, 174, null], [174, 599, null], [599, 599, null], [599, 2545, null], [2545, 5093, null], [5093, 7600, null], [7600, 9790, null], [9790, 12640, null], [12640, 15985, null], [15985, 18624, null], [18624, 21937, null], [21937, 24213, null], [24213, 26532, null], [26532, 27870, null], [27870, 29428, null], [29428, 30986, null], [30986, 33039, null], [33039, 35332, null], [35332, 37503, null], [37503, 40610, null], [40610, 42479, null], [42479, 44104, null], [44104, 45591, null], [45591, 47663, null], [47663, 49652, null], [49652, 52052, null], [52052, 54229, null], [54229, 56484, null], [56484, 58871, null], [58871, 61184, null], [61184, 63540, null], [63540, 66816, null], [66816, 69510, null], [69510, 71369, null], [71369, 71748, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 0, null], [0, 0, null], [0, 174, true], [174, 174, null], [174, 599, null], [599, 599, null], [599, 2545, null], [2545, 5093, null], [5093, 7600, null], [7600, 9790, null], [9790, 12640, null], [12640, 15985, null], [15985, 18624, null], [18624, 21937, null], [21937, 24213, null], [24213, 26532, null], [26532, 27870, null], [27870, 29428, null], [29428, 30986, null], [30986, 33039, null], [33039, 35332, null], [35332, 37503, null], [37503, 40610, null], [40610, 42479, null], [42479, 44104, null], [44104, 45591, null], [45591, 47663, null], [47663, 49652, null], [49652, 52052, null], [52052, 54229, null], [54229, 56484, null], [56484, 58871, null], [58871, 61184, null], [61184, 63540, null], [63540, 66816, null], [66816, 69510, null], [69510, 71369, null], [71369, 71748, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 71748, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 71748, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 0, 4], [0, 174, 5], [174, 174, 6], [174, 599, 7], [599, 599, 8], [599, 2545, 9], [2545, 5093, 10], [5093, 7600, 11], [7600, 9790, 12], [9790, 12640, 13], [12640, 15985, 14], [15985, 18624, 15], [18624, 21937, 16], [21937, 24213, 17], [24213, 26532, 18], [26532, 27870, 19], [27870, 29428, 20], [29428, 30986, 21], [30986, 33039, 22], [33039, 35332, 23], [35332, 37503, 24], [37503, 40610, 25], [40610, 42479, 26], [42479, 44104, 27], [44104, 45591, 28], [45591, 47663, 29], [47663, 49652, 30], [49652, 52052, 31], [52052, 54229, 32], [54229, 56484, 33], [56484, 58871, 34], [58871, 61184, 35], [61184, 63540, 36], [63540, 66816, 37], [66816, 69510, 38], [69510, 71369, 39], [71369, 71748, 40]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 71748, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
98b0d5090722a894b43f9a5a2068513cfa402548
|
Program Verification: Lecture 11
José Meseguer
Computer Science Department
University of Illinois at Urbana-Champaign
Given unsorted $\Sigma$-algebras $\mathbb{A} = (A, \_\_A)$ and $\mathbb{B} = (B, \_\_B)$, a $\Sigma$-homomorphism $h$ from $\mathbb{A}$ to $\mathbb{B}$, written $h : \mathbb{A} \rightarrow \mathbb{B}$, is a function $h : A \rightarrow B$ that preserves the operations $\Sigma$, i.e.,
- for each constant $a : \epsilon \rightarrow s$ in $\Sigma$, $h(a_A) = a_B$ (preservation of constants)
- for each $f : s \rightarrow s$ in $\Sigma$, $n \geq 1$, and each $(a_1, \ldots, a_n) \in A^n$, we have $h(f_A(a_1, \ldots, a_n)) = f_B(h(a_1), \ldots, h(a_n))$ (preservation of (non-constant) operations).
Example of Unsorted Homomorphism
Ex.11.1. The natural numbers \( \mathbb{N} \), and the natural numbers modulo \( n, \mathbb{N}_n \) (for any \( n \geq 1 \)) are all \( \Sigma_{\text{NAT-MIXFIX}} \)-algebras (Lecture 3, pages 3–4). Prove in detail that (for any \( n \geq 1 \)) we have a \( \Sigma_{\text{NAT-PREFIX}} \)-homomorphism:
\[
res_n : \mathbb{N} \longrightarrow \mathbb{N}_n
\]
where \( res_n \) sends each number to its residue after dividing by \( n \). For example, \( res_7(23) = 2 \), and \( res_5(23) = 3 \).
Note that \( \Sigma_{\text{NAT-MIXFIX}} = \{0, s, +, *\} \). So you have to prove the \( \Sigma_{\text{NAT-PREFIX}} \)-homomorphism property of \( res_n \) for 0 and for the operations \( \{s, +, *\} \).
Ex. 11.2. Recall (Lecture 3, pgs. 6–8) the powerset algebra $\mathbb{P}(X) = (\mathcal{P}(X), \_\mathbb{P}(X))$ over the Boolean signature $\Sigma_{BOOL}$. Let $X$ and $Y$ be any sets, and let $f : X \rightarrow Y$ be any function. Prove in detail that the function:
$$f^{-1}[\_] : \mathcal{P}(Y) \rightarrow \mathcal{P}(X)$$
defined for any $A \subseteq Y$ by: $f^{-1}[A] = \{x \in X \mid f(x) \in A\}$, is a $\Sigma_{BOOL}$-homomorphism $f^{-1}[\_] : \mathbb{P}(Y) \rightarrow \mathbb{P}(X)$. Consider also a function $g : Y \rightarrow Z$. Prove that we have the identity $(f; g)^{-1}[\_] = g^{-1}[\_] \circ f^{-1}[\_]$, and therefore that $g^{-1}[\_]; f^{-1}[\_] : \mathcal{P}(Z) \rightarrow \mathcal{P}(X)$ is also a $\Sigma_{BOOL}$-homomorphism from $\mathbb{P}(Z)$ to $\mathbb{P}(X)$.
Many-Sorted Homomorphisms
Given (many-sorted) $\Sigma$-algebras $A = (A, \_A)$ and $B = (B, \_B)$, a $\Sigma$-homomorphism $h$ from $A$ to $B$, written $h : A \rightarrow B$, is an $S$-indexed family of functions $h = \{h_s : A_s \rightarrow B_s\}_{s \in S}$ such that:
- for each constant $a : \epsilon \rightarrow s$, $h_s(a_{A}^{\text{nil},s}) = a_{B}^{\text{nil},s}$ (preservation of constants)
- for each $f : w \rightarrow s$ with $w = s_1 \ldots s_n$, $n \geq 1$, and each $(a_1, \ldots, a_n) \in A^w$, we have
$h_s(f_{A}^{w,s}(a_1, \ldots, a_n)) = f_{B}^{w,s}(h_{s_1}(a_1), \ldots, h_{s_n}(a_n))$ (preservation of (non-constant) operations).
Ex. 11.3. Recall the module NAT-LIST in Lecture 2, and the two \( \Sigma_{\text{NAT-LIST}} \)-algebras, let us call them \( \mathbb{A} \) and \( \mathbb{B} \), defined on pages 4–5 of Lecture 4, namely \( \mathbb{A} = \) lists of natural numbers and \( \mathbb{B} = \) (finite) sets of natural numbers. Show that there cannot be any \( \Sigma_{\text{NAT-LIST}} \)-homomorphism \( h : \mathbb{A} \rightarrow \mathbb{B} \).
Ex. 11.4. For \( \Sigma \) the signature in picture 4.1, consider the first family of algebras for it described in point 1, pages 5–6 of Lecture 4, namely \( n \)-dimensional vector spaces on the rational, the real, or the complex numbers. Let us be specific and fix the reals. Let \( \mathbb{A} \) be the 3-dimensional real vector space, and \( \mathbb{B} \) the 2-dimensional real vector space. What is then a \( \Sigma \)-homomorphism \( h : \mathbb{A} \rightarrow \mathbb{B} \)? Prove that any such homomorphism \( h \) can be completely described by a \( 2 \times 3 \) matrix \( M_h \) with real coefficients, so that applying to a
3-dimensionsl vector $\vec{v}$ the homomorphims $h$, that is, computing $h(\vec{v})$ exactly corresponds to computing the matrix multiplication $\vec{v} \circ M_h$. Generalize this to $\mathbb{A}$ and $\mathbb{B}$ real vector spaces of arbitrary finite dimensions $n$ and $m$. Generalize it further to rational, resp. complex, vector spaces of any pair of finite dimensions $n$ and $m$.
Now generalize this even further to characterize by means of matrices all $\Sigma$-homomorphims between $\Sigma$-algebras in cases 2–3 in page 6 of Lecture 4. Give for each of these cases specific examples of $h : \mathbb{A} \rightarrow \mathbb{B}$ showing how this works and how $h$ is thus applied to specific elements in the corresponding algebra $\mathbb{A}$.
Order-Sorted Homomorphisms
For $\Sigma = ((S, <), F, \Sigma)$ an order-sorted signature, and $A$ and $B$ order-sorted $\Sigma$-algebras, a $\Sigma$-homomorphism $h$ from $A$ to $B$, written $h : A \to B$, is an $S$-indexed family of functions $h = \{h_s : A_s \to B_s\}_{s \in S}$ such that:
- $h : A \to B$ is a many-sorted $(S, F, \Sigma)$-homomorphism; and
- if $[s] = [s']$ and $a \in A_s \cap A_{s'}$, then $h_s(a) = h_{s'}(a)$ (agreement on data in the same connected component)
Examples of Order-Sorted Homomorphisms
Ex.11.5. Consider the order-sorted signature $\Sigma$ of the \texttt{NAT-LIST-II} example in Lecture 2, the two algebras on such a signature, let us call them $\mathbb{A}$ and $\mathbb{B}$, defined on page 8 of Lecture 4, with $\mathbb{A}$ case (1), and $\mathbb{B}$ case (2). Show that there is exactly one order-sorted $\Sigma$-homomorphism $h : \mathbb{A} \to \mathbb{B}$. Describe such a homomorphism $h$ in complete detail. Show that there cannot be any other $\Sigma$-homomorphisms $h' : \mathbb{A} \to \mathbb{B}$ with $h \neq h'$.
What is a Pocket Calculator?
Consider a pocket calculator for expressions on the signature
\( \Sigma = \{0, 1, \_ + \_, \_ * \_\} \), evaluated on the integers
\( \mathbb{Z} = (\mathbb{Z}, \_ \_ \_ \_ \_ \_ \_ \mathbb{Z}) \).
Q: What is a pocket calculator as a computable function?
A: A function, say, \( \_ \mathbb{Z} : T_\Sigma \rightarrow \mathbb{Z} \). Call it evaluation in \( \mathbb{Z} \).
Q: What is the recursive definition of \( \_ \mathbb{Z} : T_\Sigma \rightarrow \mathbb{Z} \)?
A: It is defined by the recursive equations:
\( 0_\mathbb{Z} = 0, \ 1_\mathbb{Z} = 1, \ (t + t')_\mathbb{Z} = t_\mathbb{Z} +_\mathbb{Z} t'_\mathbb{Z}, \ (t * t')_\mathbb{Z} = t_\mathbb{Z} *_\mathbb{Z} t'_\mathbb{Z} \).
Q: What is the essential property of the function \( \_ \mathbb{Z} : T_\Sigma \rightarrow \mathbb{Z} \)?
A: It is a \( \Sigma \)-homomorphism \( \_ \mathbb{Z} : T_\Sigma \rightarrow \mathbb{Z} \) because, for example,
\( (0_{T_\Sigma})_\mathbb{Z} = (0)_\mathbb{Z} = 0_\mathbb{Z} = 0, \ (t +_{T_\Sigma} t')_\mathbb{Z} = (t + t')_\mathbb{Z} = t_\mathbb{Z} +_\mathbb{Z} t'_\mathbb{Z}. \)
In the same way we also have pocket calculators for the ground terms of \( \Sigma = \{0, 1, \_ \_ + \_ \_ , \_ \_ \times \_ \_ \} \), evaluated on the natural numbers \( \mathbb{N} = (\mathbb{N}, \_ \_ \mathbb{N}) \), the natural numbers modulo \( k \geq 1 \), \( \mathbb{N}_k = (\mathbb{N}_k, \_ \_ \mathbb{N}_k) \), or the rational numbers \( \mathbb{Q} = (\mathbb{Q}, \_ \_ \mathbb{Q}) \).
More generally, we shall see shortly, that for \( \Sigma \) a sensible order-sorted signature and any order-sorted \( \Sigma \)-algebra \( \mathbb{A} = (A, \_ \_ \mathbb{A}) \) there is a unique pocket calculator evaluating the terms \( T_\Sigma \) in \( \mathbb{A} \), that is, a unique \( \Sigma \)-homomorphism \( \_ \_ \mathbb{A} : T_\Sigma \to \mathbb{A} \), defined by the recursive equations:
- \((a)_\mathbb{A} = a_\mathbb{A}\) for each constant \( a \) in \( \Sigma \), and
- \(f(t_1, \ldots, t_n)_\mathbb{A} = f_\mathbb{A}(t_1_\mathbb{A}, \ldots, t_n_\mathbb{A})\) for each \( f : s_1 \ldots s_n \to s \) in \( \Sigma \).
If a signature is sensible, then different terms denote different things. In the argot of algebraic specifications, this is expressed by saying that the term algebra $T_{\Sigma}$ has no confusion.
Furthermore, the term algebra $T_{\Sigma}$ is in some sense minimal, since it has only the elements it needs to have to be an algebra: the constants, and the terms needed so that the operations can yield a result; that is why this minimality is expressed saying that it has no junk.
The key intuition of why there is a unique pocket calculator $\_\_A : T_{\Sigma} \to A$ for any $\Sigma$-algebra $A$, is that: (i) no junk ensures uniqueness of $\_\_A$, and (ii) no confusion ensures the existence of $\_\_A$.
The intuition that no confusion ensures the existence of
\( \_A : T_\Sigma \to A \) suggests that confusion/ambiguity in \( T_\Sigma \), i.e., \( \Sigma \) non-sensible, will prevent/block the existence of \( \_A : T_\Sigma \to A \). Let us see an example.
For example, \( \_K : T_\Sigma \to K \) cannot be defined for \( \Sigma \) the non-sensible signature we showed in pg. 16 of Lecture 4 and the \( \Sigma \)-algebra
\( K = (K, \_K) \) with: \( K_A = \{a\} \), \( K_B = \{b\} \), \( K_C = \{c\} \), \( K_D = \{d, d'\} \),
and with \( f_{K \rightarrow K}^A,B(a) = b \), \( f_{K \rightarrow K}^A,C(a) = c \), \( g_{K \rightarrow K}^B,D(b) = d \), and \( g_{K \rightarrow K}^C,D(c) = d' \).
Indeed, there in no \( \Sigma \)-homomorphism \( h : T_\Sigma \longrightarrow K \) at all, since
\( h_D(g(f(a))) \) must be either \( d \) or \( d' \). But if \( h_D(g(f(a))) = d \), then \( h \) fails to preserve the operation \( g : C \longrightarrow D \), and if \( h_D(g(f(a))) = d' \), then \( h \) fails to preserve the operation \( g : B \longrightarrow D \).
In summary, the claim is that, if \( \Sigma \) is sensible, then for any \( \Sigma \)-algebra \( A \) there is a unique pocket calculator for \( A \), i.e., a unique \( \Sigma \)-homomorphism \( _A : T_\Sigma \rightarrow A \). This is called the initiality property of \( T_\Sigma \). This unique \( \Sigma \)-homomorphism \( _A \) is the obvious evaluation function, mapping each term \( t \) to the result of evaluating it in \( A \). As already mentioned, \( _A \) is defined inductively as follows:
- for a constant \( a \) we define \( (a)_A = a_A \), and
- for a term \( f(t_1, \ldots, t_n) \) we define
\[
(f(t_1, \ldots, t_n))_A = f_A((t_1)_A, \ldots, (t_n)_A).
\]
Let us prove it in detail.
**Theorem.** If \( \Sigma \) is a sensible order-sorted signature, then \( T_\Sigma \) satisfies the initiality property.
Proof of the Initiality Theorem
Proof: For \( \mathbb{A} \) any \( \Sigma \)-algebra Let us first prove the uniqueness of \( \_ \mathbb{A} \), and then its existence.
Proof of uniqueness. Let us suppose that we have two different homomorphisms \( h, h' : T_{\Sigma} \rightarrow \mathbb{A} \). We can prove that \( h = h' \) by induction on the depth of the terms.
For terms of depth 0 let \( a \) be a constant in \( T_{\Sigma,s} \). That means that there is a sort \( s' \leq s \) with an operator declaration \( a : nil \rightarrow s' \) and therefore, by \( h \) and \( h' \) being \( \Sigma \)-homomorphisms we must have \( h_s(a) = h'_s(a) = a_{\mathbb{A}}^{nil,s'} \).
Proof of the Initiality Theorem (II)
Assume that the equality $h = h'$ holds for terms of depth less or equal to $n$, and let $f(t_1, \ldots, t_n) \in T_{\Sigma,s}$ have depth $n + 1$. That means that there is an operator declaration $f : s_1 \ldots s_n \to s'$ with $s' \leq s$ and $t_i \in T_{\Sigma,s_i}, 1 \leq i \leq n$. Again, by $h$ and $h'$ being $\Sigma$-homomorphisms we must have:
$$h_s(f(t_1, \ldots, t_n)) =$$
$$= f^{s_1 \ldots s_n,s'}(h_{s_1}(t_1), \ldots, h_{s_n}(t_n)) \quad (h \text{ homomorphism and } s' \leq s)$$
$$= f^{s_1 \ldots s_n,s'}(h'_{s_1}(t_1), \ldots, h'_{s_n}(t_n)) \quad (\text{induction hypothesis})$$
$$= h'_s(f(t_1, \ldots, t_n)) \quad (h' \text{ homomorphism and } s' \leq s).$$
Proof of Existence. We can both define $A_\Sigma$ and show that it is a $\Sigma$-homomorphism by induction on the (tree) depth of ground terms. For terms of depth 0, let $a \in T_{\Sigma,s}$ be a constant. That means that there is a sort $s' \leq s$ with an operator declaration $a : \text{nil} \rightarrow s'$; we then define $(a)_A = a^{\text{nil},s'}_A$.
Note that the constant $a$ could be subsort-overloaded (cannot be ad-hoc overloaded, since this is ruled out by $\Sigma$ being sensible) but the above assignment is well-defined (does not depend on the particular declaration $a : \epsilon \rightarrow s'$ chosen), because by our definition of order-sorted $\Sigma$-algebra the interpretations of all subsort overloaded versions of a constant $a$ must coincide in the algebra $A$. Furthermore, $A_\Sigma$ preserves constants, so it is a $\Sigma$-homomorphism for ground terms of depth 0.
Assume that $\_A$ has already been defined and is a $\Sigma$-homomorphism for ground terms of depth less or equal to $n$, and let $f(t_1, \ldots, t_n) \in T_{\Sigma,s}$ be a term of depth $n + 1$. That means that there is an operator declaration $f : s_1 \ldots s_n \to s'$ with $s' \leq s$ and $t_i \in T_{\Sigma,s_i}$, $1 \leq i \leq n$. We define
$$(f(t_1, \ldots, t_n))_A = f_{\Lambda}^{s_1 \ldots s_n,s'}((t_1)_A, \ldots, (t_n)_A).$$
Note that, by the induction hypothesis, $\_A$ has already been defined for terms of depth less or equal to $n$ and is an order-sorted $\Sigma$-homomorphism on those terms.
Note also that, by the Proof of the Lemma on sensible signatures, for any other $f : s'_1 \ldots s'_n \to s''$ such that $t_i \in T_{\Sigma,s'_i}$, $1 \leq i \leq n$, we must have, $[s_i] = [s'_i]$, $1 \leq i \leq n$, and $[s'] = [s'']$.
Proof of the Initiality Theorem (V)
Since we have \([s_i] = [s'_i], 1 \leq i \leq n\), by definition of order-sorted \(\Sigma\)-homomorphism this then forces, \(\_A{s_i}(t_i) = \_A{s'_i}(t_i), 1 \leq i \leq n\).
But since \(A\) is a \(\Sigma\)-algebra, all its subsort overloaded operators must agree on common data, we must have,
\[
f_A^{s_1 \ldots s_n, s'}((t_1)_A, \ldots, (t_n)_A) = f_A^{s'_1 \ldots s'_n, s''}((t_1)_A, \ldots, (t_n)_A).
\]
Therefore, the definition of \(\left( f(t_1, \ldots, t_n) \right)_A = f_A^{s_1 \ldots s_n, s'}((t_1)_A, \ldots, (t_n)_A)\) does not depend on the choice of the subsort overloaded operator \(f\). As a consequence, the extension of \(\_A\) to the step \(n + 1\) is well-defined and, by construction, it is a \(\Sigma\)-homomorphism for ground terms of depth less or equal to \(n + 1\). Therefore, we have inductively proved the existence of the \(\Sigma\)-homomorphism \(\_A\). q.e.d.
Ex.11.6. Recall the canonical term algebra
\( \mathbb{C}_{\Sigma/E,B} = (C_{\Sigma/E,B}, \_c_{\Sigma/E,B}) \), defined in page 17 of Lecture 6 for a functional \( \text{fmod} (\Sigma, E \cup B) \text{endfm} \), where \( \Sigma \) is \( B \)-preregular and satisfies the Unique Termination, Sufficient Completeness and Sort Preservation requirements.\(^a\) What is the pocket calculator of \( \mathbb{C}_{\Sigma/E,B} \)?
By the Initiality Theorem, it is the unique \( \Sigma \)-homomorphism \( \_c_{\Sigma/E,B} : T \Sigma \rightarrow \mathbb{C}_{\Sigma/E,B} \). Prove that, as an \( S \)-sorted function on \( S \)-sorted sets, \( \_c_{\Sigma/E,B} : T \Sigma \rightarrow C_{\Sigma/E,B} \) is exactly the \( S \)-sorted function: \( \{ T_{\Sigma,s} \ni t \mapsto [t!_{E/B}] \in C_{\Sigma/E,B,s}\}_{s \in S} \) (what Maude’s \texttt{red} command implements!!), which we used in defining \( \mathbb{C}_{\Sigma/E,B} \).
\(^a\)Which of course can be checked by checking sort-decreasingness, local confluence and termination of \( \vec{E} \) modulo \( B \), and sufficient completeness w.r.t. the constructors \( \Omega \).
More on Homomorphisms
Ex. 11.7. Prove that homomorphisms compose. That is, if $h : \mathcal{A} \to \mathcal{B}$ and $g : \mathcal{B} \to \mathcal{C}$ are $\Sigma$-homomorphisms, then $h ; g = \{h_s ; g_s\}_{s \in S}$ is a $\Sigma$-homomorphism $h ; g : \mathcal{A} \to \mathcal{C}$.
Ex. 11.8. Prove that identities are homomorphisms. That is, given a $\Sigma$-algebra $\mathcal{A} = (A, _\mathcal{A})$, the family of identity functions $id_A = \{id_{A_s}\}$ is a $\Sigma$-homomorphism $id_A : \mathcal{A} \to \mathcal{A}$.
A $\Sigma$-homomorphism $h : \mathbb{A} \rightarrow \mathbb{B}$ is called an isomorphism if there is another $\Sigma$-homomorphism $g : \mathbb{B} \rightarrow \mathbb{A}$ such that $h; g = id_A$ and $g; h = id_B$. We then may use the notation $g = h^{-1}$ and $h = g^{-1}$. We call a $\Sigma$-homomorphism $h : \mathbb{A} \rightarrow \mathbb{B}$
- injective (resp. surjective) if for each sort $s \in S$ the function $h_s$ is injective (resp. surjective)
- a monomorphism if for any pair of $\Sigma$-homomorphisms $g, q : \mathbb{C} \rightarrow \mathbb{A}$, if $g; h = q; h$ then $g = q$
- an epimorphism if for any pair of $\Sigma$-homomorphisms $g, q : \mathbb{B} \rightarrow \mathbb{C}$, if $h; g = h; q$ then $g = q$.
More on Homomorphisms (III)
For example, if \( \mathbb{N}_{bin} \), resp. \( \mathbb{N}_{dec} \), denote the natural numbers with 0, successor, and addition in binary, resp. decimal, representation, we have an obvious binary-to-decimal isomorphism \( b2d : \mathbb{N}_{bin} \to \mathbb{N}_{dec} \) preserving all operations, whose inverse is the decimal-to-binary isomorphism, \( d2b : \mathbb{N}_{bin} \to \mathbb{N}_{dec} \). Of course, \( d2b; b2d = id_{\mathbb{N}_{dec}} \), and \( b2d; d2b = id_{\mathbb{N}_{bin}} \).
For \( \mathbb{N}_n \) the residue classes modulo \( n \), the reminder function \( \mathbb{N} \xrightarrow{rem_n} \mathbb{N}_n \) is a surjective homomorphism for \( \Sigma \) containing, say, 0, 1, +, \( \times \).
Similarly, for \( \mathbb{Z}_{dec} \) the integers in decimal notation, the inclusion \( j : \mathbb{N}_{dec} \hookrightarrow \mathbb{Z}_{dec} \) is an injective homomorphism preserving all shared operations: 0, 1, +, \( \times \), etc.
Theorem: All Initial Algebras Are Isomorphic
Proof: Suppose \( \mathbb{I} \) and \( \mathbb{J} \) are \( \Sigma \)-algebras and both satisfy the initiality property of having a unique \( \Sigma \)-homomorphism to any other \( \Sigma \)-algebra. In particular, we have unique homomorphisms,
\[
h : \mathbb{I} \to \mathbb{J} \quad g : \mathbb{J} \to \mathbb{I}
\]
and therefore a composed homomorphism
\[
\mathbb{I} \xrightarrow{h} \mathbb{J} \xrightarrow{g} \mathbb{I}
\]
but we also have the identity homomorphism \( id_\mathbb{I} \), which by uniqueness forces \( h; g = id_\mathbb{I} \). Interchanging the role of \( \mathbb{I} \) and \( \mathbb{J} \) we also get, \( g; h = id_\mathbb{J} \). q.e.d.
Q1: Can we model the evaluation of expressions in a programming language using initial algebras?
A1: We first of all need a signature $\Sigma$ of operations.
For example, $\Sigma$ could be a signature for integer operations, and/or Boolean operations, and/or real number operations (typically using a floating point representation).
Assume, for example, a programming language in which we only have integers and integer operations (note that we can encode true and false as, respectively, 0 and 1). In this case $\Sigma$ can be unsorted and have two constants, 0 and 1, and three binary function symbols: $+_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_\_/
Q2: What else do we need?
A2: We need a set $X$ of variables appearing on our expressions. This means that we need to extend $\Sigma$ to $\Sigma(X)$, so that our program expressions will be terms $t \in T_{\Sigma(X)}$.
Q3: And what else do we need if we want to evaluate such expressions?
A3: We of course need a $\Sigma$-algebra in which they will be evaluated. For integers expressions the most natural choice is the algebra $\mathbb{Z} = (\mathbb{Z}, _\mathbb{Z})$ of the integers, with the standard interpretation $ _\mathbb{Z}$ for $+, *, -, 0, 1$.
Q4: And what else do we need?
A4: Since expression evaluation depends on the memory state, we need to model mathematically memory states.
Q5: And how can we model memory states?
A5: Assuming programs with just global variables, a memory state for arithmetic expressions is just a function $m : X \to \mathbb{Z}$. This is a special instance of the general notions of an assignment of values to variables in an algebra.
Given variables in $X = \{ X_s \}$ we will often be interested in assignments (also called valuations) of data elements in a given $\Sigma$-algebra $\mathcal{A} = (A, _\mathcal{A})$ to those variables. Of course, if $x \in X_s$ then the value, say $a(x)$, assigned to $x$ should be an element of $A_s$. That is the assignments should be well-sorted. This can be made precise by defining an assignment to the variables $X$ in a $\Sigma$-algebra $\mathcal{A} = (A, _\mathcal{A})$ to be an $S$-indexed family of functions, $a = \{ a_s : X_s \rightarrow A_s \}_{s \in S}$, denoted $a : X \rightarrow A$.
Often what we want to do with such assignments is to extend them from variables to terms on such variables in the obvious, homomorphic way. This is what expression evaluation is all about.
Evaluating Program Expressions (VI)
Q6: Now that we have everything we need, how can evaluation of arithmetic expressions be precisely defined relative to a memory (state) $m : X \rightarrow \mathbb{Z}$?
A6: As a function $\_ \_ (\_ , m) : T_{\Sigma (X)} \rightarrow \mathbb{Z}$ defined inductively by:
1. $x (\_ , m) = m (x)$ for $x \in X$
2. $0 (\_ , m) = 0 \in \mathbb{Z}$, $1 (\_ , m) = 1 \in \mathbb{Z}$
3. $f (t, t') (\_ , m) = f (t (\_ , m), t' (\_ , m))$ for $f \in \{ +, *, - \}$.
Q7: Conditions (2)–(3) show that \(\_ (\mathbb{Z}, m)\) is a \(\Sigma\)-homomorphism. What about condition (1)?
A7: Condition (1) plus (2)–(3) show that it is a \(\Sigma(X)\)-homomorphism, when we extend the algebra \(\mathbb{Z}\) of the integers with the additional constants \(X\), where each \(x \in X\) is interpreted in \(\mathbb{Z}\) as \(m(x)\). Therefore, the extension of \(\mathbb{Z}\) to a \(\Sigma(X)\)-algebra is just \((\mathbb{Z}, \_ \mathbb{Z} \oplus m)\), which we abbreviate to: \((\mathbb{Z}, m)\). Then the evaluation of arithmetic expressions is the unique \(\Sigma(X)\)-homomorphism:
\[
\_ (\mathbb{Z}, m) : T_{\Sigma(X)} \rightarrow (\mathbb{Z}, m)
\]
to the \(\Sigma(X)\)-algebra \((\mathbb{Z}, m)\) (extending the \(\Sigma\)-algebra \(\mathbb{Z}\) with memory \(m\)) ensured by the initiality of \(T_{\Sigma(X)}\).
Ex.11.9. Show that a homomorphism is injective iff it is a monomorphism. Prove that every surjective homomorphism is an epimorphism. Construct an epimorphism that is not surjective.
Ex.11.10. Show that any many-sorted $\Sigma$-homomorphism that is surjective and injective is an isomorphism.
Construct an order-sorted homomorphism that is surjective and injective but is not an isomorphism. Give a sufficient condition on the poset $(S, \leq)$ (more general of course than being a discrete poset, since that is the many-sorted case) so that $h$ is an isomorphism iff $h$ is surjective and injective.
Ex.11.11. Prove that if an algebra $\mathcal{J}$ is isomorphic to an initial algebra $\mathcal{I}$, then $\mathcal{J}$ itself is initial.
Ex.11.12. Show that the natural numbers in Peano notation (zero and successor) and in base 2 are isomorphic $\Sigma$-algebras (both initial) for $\Sigma$ the signature with one sort $\text{Natural}$ and zero and successor operations.
|
{"Source-Url": "https://courses.grainger.illinois.edu/CS476/fa2022/lectures/pv11-slides.pdf", "len_cl100k_base": 8406, "olmocr-version": "0.1.50", "pdf-total-pages": 32, "total-fallback-pages": 0, "total-input-tokens": 68009, "total-output-tokens": 10397, "length": "2e13", "weborganizer": {"__label__adult": 0.0004317760467529297, "__label__art_design": 0.0006833076477050781, "__label__crime_law": 0.0007252693176269531, "__label__education_jobs": 0.0130157470703125, "__label__entertainment": 0.00013136863708496094, "__label__fashion_beauty": 0.0002779960632324219, "__label__finance_business": 0.0006289482116699219, "__label__food_dining": 0.0006809234619140625, "__label__games": 0.0010204315185546875, "__label__hardware": 0.0021076202392578125, "__label__health": 0.0013751983642578125, "__label__history": 0.0005435943603515625, "__label__home_hobbies": 0.0003247261047363281, "__label__industrial": 0.0014486312866210938, "__label__literature": 0.0006151199340820312, "__label__politics": 0.0006570816040039062, "__label__religion": 0.0008306503295898438, "__label__science_tech": 0.420166015625, "__label__social_life": 0.0002651214599609375, "__label__software": 0.00847625732421875, "__label__software_dev": 0.5439453125, "__label__sports_fitness": 0.0003905296325683594, "__label__transportation": 0.0009765625, "__label__travel": 0.00025534629821777344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 24267, 0.00936]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 24267, 0.67334]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 24267, 0.74013]], "google_gemma-3-12b-it_contains_pii": [[0, 120, false], [120, 718, null], [718, 1452, null], [1452, 2246, null], [2246, 2904, null], [2904, 3964, null], [3964, 4717, null], [4717, 5204, null], [5204, 5784, null], [5784, 6890, null], [6890, 7918, null], [7918, 8627, null], [8627, 9690, null], [9690, 10521, null], [10521, 11199, null], [11199, 11919, null], [11919, 12815, null], [12815, 13668, null], [13668, 14600, null], [14600, 15719, null], [15719, 16245, null], [16245, 16971, null], [16971, 17951, null], [17951, 18658, null], [18658, 20185, null], [20185, 20743, null], [20743, 21164, null], [21164, 21954, null], [21954, 22450, null], [22450, 23293, null], [23293, 23895, null], [23895, 24267, null]], "google_gemma-3-12b-it_is_public_document": [[0, 120, true], [120, 718, null], [718, 1452, null], [1452, 2246, null], [2246, 2904, null], [2904, 3964, null], [3964, 4717, null], [4717, 5204, null], [5204, 5784, null], [5784, 6890, null], [6890, 7918, null], [7918, 8627, null], [8627, 9690, null], [9690, 10521, null], [10521, 11199, null], [11199, 11919, null], [11919, 12815, null], [12815, 13668, null], [13668, 14600, null], [14600, 15719, null], [15719, 16245, null], [16245, 16971, null], [16971, 17951, null], [17951, 18658, null], [18658, 20185, null], [20185, 20743, null], [20743, 21164, null], [21164, 21954, null], [21954, 22450, null], [22450, 23293, null], [23293, 23895, null], [23895, 24267, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 24267, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 24267, null]], "pdf_page_numbers": [[0, 120, 1], [120, 718, 2], [718, 1452, 3], [1452, 2246, 4], [2246, 2904, 5], [2904, 3964, 6], [3964, 4717, 7], [4717, 5204, 8], [5204, 5784, 9], [5784, 6890, 10], [6890, 7918, 11], [7918, 8627, 12], [8627, 9690, 13], [9690, 10521, 14], [10521, 11199, 15], [11199, 11919, 16], [11919, 12815, 17], [12815, 13668, 18], [13668, 14600, 19], [14600, 15719, 20], [15719, 16245, 21], [16245, 16971, 22], [16971, 17951, 23], [17951, 18658, 24], [18658, 20185, 25], [20185, 20743, 26], [20743, 21164, 27], [21164, 21954, 28], [21954, 22450, 29], [22450, 23293, 30], [23293, 23895, 31], [23895, 24267, 32]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 24267, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
b825f99b127a15d4f1dd3430da42ff913e1e5c9b
|
Self-Supervised Learning (Continued)
Large Vision and Language Models
Pretext tasks from image transformations
- Image completion
- Rotation prediction
- “Jigsaw puzzle”
- Colorization
Learned representations may be tied to a specific pretext task!
Can we come up with a more general pretext task?
A more general pretext task?
same object
A more general pretext task?
same object
different object
Contrastive Representation Learning
Today’s Agenda
Pretext tasks from image transformations
- Rotation, inpainting, rearrangement, coloring
Contrastive representation learning
- Intuition and formulation
- Instance contrastive learning: SimCLR and MOCO
- Sequence contrastive learning: CPC
Contrastive Representation Learning
Contrastive Representation Learning
\[ x^+ \]
\[ \mathbf{x} \]
\[ x^- \] reference
\[ x^+ \] positive
\[ x^- \] negative
A formulation of contrastive learning
What we want:
\[ \text{score}(f(x), f(x^+)) >> \text{score}(f(x), f(x^-)) \]
\( x \): reference sample; \( x^+ \) positive sample; \( x^- \) negative sample
Given a chosen score function, we aim to learn an encoder function \( f \) that yields high score for positive pairs \( (x, x^+) \) and low scores for negative pairs \( (x, x^-) \).
A formulation of contrastive learning
Loss function given 1 positive sample and $N - 1$ negative samples:
$$L = -\mathbb{E}_X \left[ \log \left( \frac{\exp(s(f(x), f(x^+)))}{\exp(s(f(x), f(x^+)) + \sum_{j=1}^{N-1} \exp(s(f(x), f(x_j^-)))} \right) \right]$$
A formulation of contrastive learning
Loss function given 1 positive sample and \( N - 1 \) negative samples:
\[
L = -\mathbb{E}_x \left[ \log \frac{\exp(s(f(x), f(x^+)))}{\exp(s(f(x), f(x^+))) + \sum_{j=1}^{N-1} \exp(s(f(x), f(x_j^-)))} \right]
\]
A formulation of contrastive learning
Loss function given 1 positive sample and N - 1 negative samples:
\[
L = -\mathbb{E}_x \left[ \log \frac{\exp(s(f(x), f(x^+)))}{\exp(s(f(x), f(x^+))) + \sum_{j=1}^{N-1} \exp(s(f(x), f(x_j^-)))} \right]
\]
This seems familiar ...
A formulation of contrastive learning
Loss function given 1 positive sample and N - 1 negative samples:
\[
L = -\mathbb{E}_x \left[ \log \frac{\exp(s(f(x), f(x^+)))}{\exp(s(f(x), f(x^+))) + \sum_{j=1}^{N-1} \exp(s(f(x), f(x_j^-)))} \right]
\]
This seems familiar ...
Cross entropy loss for a N-way softmax classifier!
I.e., learn to find the positive sample from the N samples
A formulation of contrastive learning
Loss function given 1 positive sample and N - 1 negative samples:
\[
L = -\mathbb{E}_x \left[ \log \frac{\exp(s(f(x), f(x^+))}{\exp(s(f(x), f(x^+)) + \sum_{j=1}^{N-1} \exp(s(f(x), f(x_j^-)))} \right]
\]
Commonly known as the InfoNCE loss (van den Oord et al., 2018)
A lower bound on the mutual information between \( f(x) \) and \( f(x^+) \)
\[
MI[f(x), f(x^+)] - \log(N) \geq -L
\]
The larger the negative sample size (N), the tighter the bound
Detailed derivation: Poole et al., 2019
SimCLR: A Simple Framework for Contrastive Learning
Cosine similarity as the score function:
\[ s(u, v) = \frac{u^T v}{||u||||v||} \]
Use a projection network \( h(\cdot) \) to project features to a space where contrastive learning is applied
Generate positive samples through data augmentation:
- random cropping, random color distortion, and random blur.
Source: Chen et al., 2020
SimCLR: generating positive samples from data augmentation
Source: Chen et al., 2020
SimCLR
Generate a positive pair by sampling data augmentation functions
Algorithm 1 SimCLR’s main learning algorithm.
```
input: batch size $N$, constant $\tau$, structure of $f$, $g$, $\mathcal{T}$.
for sampled minibatch $\{x_k\}_{k=1}^{N}$ do
for all $k \in \{1, \ldots, N\}$ do
draw two augmentation functions $t \sim \mathcal{T}$, $t' \sim \mathcal{T}$
# the first augmentation
$\tilde{x}_{2k-1} = t(x_k)$
$h_{2k-1} = f(\tilde{x}_{2k-1})$ # representation
$z_{2k-1} = g(h_{2k-1})$ # projection
# the second augmentation
$\tilde{x}_{2k} = t'(x_k)$
$h_{2k} = f(\tilde{x}_{2k})$ # representation
$z_{2k} = g(h_{2k})$ # projection
end for
for all $i \in \{1, \ldots, 2N\}$ and $j \in \{1, \ldots, 2N\}$ do
$s_{i,j} = z_i^{\top} z_j/(\|z_i\|\|z_j\|)$ # pairwise similarity
end for
define $\ell(i,j)$ as $\ell(i,j) = -\log \frac{\exp(s_{i,j}/\tau)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \neq i]} \exp(s_{i,k}/\tau)}$
$\mathcal{L} = \frac{1}{2N} \sum_{k=1}^{N} [\ell(2k-1, 2k) + \ell(2k, 2k-1)]$
update networks $f$ and $g$ to minimize $\mathcal{L}$
end for
return encoder network $f(\cdot)$, and throw away $g(\cdot)$
```
Source: Chen et al., 2020
SimCLR
Algorithm 1 SimCLR’s main learning algorithm.
input: batch size $N$, constant $\tau$, structure of $f$, $g$, $\mathcal{T}$.
for sampled minibatch $\{x_k\}_{k=1}^N$
do
for all $k \in \{1, \ldots, N\}$ do
draw two augmentation functions $t \sim \mathcal{T}$, $t' \sim \mathcal{T}$
# the first augmentation
$\tilde{x}_{2k-1} = t(x_k)$
$h_{2k-1} = f(\tilde{x}_{2k-1})$ # representation
$z_{2k-1} = g(h_{2k-1})$ # projection
# the second augmentation
$\tilde{x}_{2k} = t'(x_k)$
$h_{2k} = f(\tilde{x}_{2k})$ # representation
$z_{2k} = g(h_{2k})$ # projection
end for
for all $i \in \{1, \ldots, 2N\}$ and $j \in \{1, \ldots, 2N\}$ do
$s_{i,j} = z_i^T z_j / (\|z_i\| \|z_j\|)$ # pairwise similarity
end for
define $\ell(i,j)$ as $\ell(i,j) = -\log \frac{\exp(s_{i,j}/\tau)}{\sum_{k=1}^{2N} \mathbb{1}_{[k \neq i]} \exp(s_{i,k}/\tau)}$
$L = \frac{1}{2N} \sum_{k=1}^{N} [\ell(2k-1, 2k) + \ell(2k, 2k-1)]$
update networks $f$ and $g$ to minimize $L$
end for
return encoder network $f(\cdot)$, and throw away $g(\cdot)$
Source: Chen et al., 2020
Generate a positive pair by sampling data augmentation functions
InfoNCE loss: Use all non-positive samples in the batch as $x^-$
SimCLR
Source: Chen et al., 2020
**Algorithm 1** SimCLR’s main learning algorithm.
**input:** batch size $N$, constant $\tau$, structure of $f$, $g$, $\mathcal{T}$.
for sampled minibatch $\{x_k\}_{k=1}^{N}$ do
for all $k \in \{1, \ldots, N\}$ do
draw two augmentation functions $t \sim \mathcal{T}$, $t' \sim \mathcal{T}$
# the first augmentation
$\tilde{x}_{2k-1} = t(x_k)$
$h_{2k-1} = f(\tilde{x}_{2k-1})$ # representation
$z_{2k-1} = g(h_{2k-1})$ # projection
# the second augmentation
$\tilde{x}_{2k} = t'(x_k)$
$h_{2k} = f(\tilde{x}_{2k})$ # representation
$z_{2k} = g(h_{2k})$ # projection
end for
for all $i \in \{1, \ldots, 2N\}$ and $j \in \{1, \ldots, 2N\}$ do
$s_{i,j} = z_i^\top z_j / (\|z_i\| \|z_j\|)$ # pairwise similarity
end for
define $\ell(i, j)$ as
\[
\ell(i, j) = -\log \frac{\exp(s_{i,j}/\tau)}{\sum_{k=1}^{2N} \mathbbm{1}_{[k \neq i]} \exp(s_{i,k}/\tau)}
\]
$L = \frac{1}{2N} \sum_{k=1}^{N} [\ell(2k-1, 2k) + \ell(2k, 2k-1)]$
update networks $f$ and $g$ to minimize $L$
end for
return encoder network $f(\cdot)$, and throw away $g(\cdot)$
SimCLR: mini-batch training
Each 2k and 2k + 1 element is a positive pair
\[ s_{i,j} = \frac{z_i^T z_j}{\|z_i\| \|z_j\|} \]
"Affinity matrix"
SimCLR: mini-batch training
Each 2k and 2k + 1 element is a positive pair.
\( s_{i,j} = \frac{z_i^T z_j}{||z_i|| \cdot ||z_j||} \)
"Affinity matrix"
\[ z \in \mathbb{R}^{2N \times D} \]
\[ 2N \]
\[ 2N \]
\[ \boxed{\text{classification label for each row}} \]
Training linear classifier on SimCLR features
Train feature encoder on ImageNet (entire training set) using SimCLR.
Freeze feature encoder, train a linear classifier on top with labeled data.
Source: Chen et al., 2020
Semi-supervised learning on SimCLR features
<table>
<thead>
<tr>
<th>Method</th>
<th>Architecture</th>
<th>Label fraction</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td></td>
<td>1%</td>
</tr>
<tr>
<td></td>
<td></td>
<td>Top 5</td>
</tr>
<tr>
<td>Supervised baseline</td>
<td>ResNet-50</td>
<td>48.4</td>
</tr>
<tr>
<td>Methods using other label-propagation:</td>
<td></td>
<td></td>
</tr>
<tr>
<td>Pseudo-label</td>
<td>ResNet-50</td>
<td>51.6</td>
</tr>
<tr>
<td>VAT+Entropy Min.</td>
<td>ResNet-50</td>
<td>47.0</td>
</tr>
<tr>
<td>UDA (w. RandAug)</td>
<td>ResNet-50</td>
<td>-</td>
</tr>
<tr>
<td>FixMatch (w. RandAug)</td>
<td>ResNet-50</td>
<td>-</td>
</tr>
<tr>
<td>S4L (Rot+VAT+En. M.)</td>
<td>ResNet-50 (4×)</td>
<td>-</td>
</tr>
<tr>
<td>Methods using representation learning only:</td>
<td></td>
<td></td>
</tr>
<tr>
<td>InstDisc</td>
<td>ResNet-50</td>
<td>39.2</td>
</tr>
<tr>
<td>BigBiGAN</td>
<td>RevNet-50 (4×)</td>
<td>55.2</td>
</tr>
<tr>
<td>PIRL</td>
<td>ResNet-50</td>
<td>57.2</td>
</tr>
<tr>
<td>CPC v2</td>
<td>ResNet-161(*)</td>
<td>77.9</td>
</tr>
<tr>
<td>SimCLR (ours)</td>
<td>ResNet-50</td>
<td>75.5</td>
</tr>
<tr>
<td>SimCLR (ours)</td>
<td>ResNet-50 (2×)</td>
<td>83.0</td>
</tr>
<tr>
<td>SimCLR (ours)</td>
<td>ResNet-50 (4×)</td>
<td><strong>85.8</strong></td>
</tr>
</tbody>
</table>
Train feature encoder on **ImageNet** (entire training set) using SimCLR.
**Finetune** the encoder with 1% / 10% of labeled data on ImageNet.
Source: [Chen et al., 2020](#)
SimCLR design choices: projection head
Linear / non-linear projection heads improve representation learning.
A possible explanation:
- contrastive learning objective may discard useful information for downstream tasks
- representation space $z$ is trained to be invariant to data transformation.
- by leveraging the projection head $g(\cdot)$, more information can be preserved in the $h$ representation space
Source: Chen et al., 2020
SimCLR design choices: large batch size
Large training batch size is crucial for SimCLR!
Large batch size causes large memory footprint during backpropagation: requires distributed training on TPUs (ImageNet experiments)
Figure 9. Linear evaluation models (ResNet-50) trained with different batch size and epochs. Each bar is a single run from scratch.\textsuperscript{10}
Source: Chen et al., 2020
Momentum Contrastive Learning (MoCo)
Key differences to SimCLR:
- Keep a running queue of keys (negative samples).
- Compute gradients and update the encoder only through the queries.
- Decouple min-batch size with the number of keys: can support a large number of negative samples.
Source: He et al., 2020
Momentum Contrastive Learning (MoCo)
Key differences to SimCLR:
- Keep a running queue of keys (negative samples).
- Compute gradients and update the encoder only through the queries.
- Decouple min-batch size with the number of keys: can support a large number of negative samples.
- The key encoder is slowly progressing through the momentum update rules:
\[ \theta_k \leftarrow m\theta_k + (1 - m)\theta_q \]
Source: He et al., 2020
MoCo
Generate a positive pair by sampling data augmentation functions
No gradient through the positive sample
Update the FIFO negative sample queue
Use the running queue of keys as the negative samples
InfoNCE loss
Update f_k through momentum
Source: He et al., 2020
“MoCo V2”
Improved Baselines with Momentum Contrastive Learning
Xinlei Chen Haoqi Fan Ross Girshick Kaiming He
Facebook AI Research (FAIR)
A hybrid of ideas from SimCLR and MoCo:
- **From SimCLR**: non-linear projection head and strong data augmentation.
- **From MoCo**: momentum-updated queues that allow training on a large number of negative samples (no TPU required!).
Source: Chen et al., 2020
MoCo vs. SimCLR vs. MoCo V2
Key takeaways:
- Non-linear projection head and strong data augmentation are crucial for contrastive learning.
Table 1. Ablation of MoCo baselines, evaluated by ResNet-50 for (i) ImageNet linear classification, and (ii) fine-tuning VOC object detection (mean of 5 trials). “MLP”: with an MLP head; “aug+”: with extra blur augmentation; “cos”: cosine learning rate schedule.
<table>
<thead>
<tr>
<th>case</th>
<th>unsup. pre-train</th>
<th>ImageNet acc.</th>
<th>VOC detection</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>MLP</td>
<td>aug+</td>
<td>cos</td>
</tr>
<tr>
<td>supervised</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>MoCo v1</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>(a)</td>
<td>✓</td>
<td></td>
<td>✓</td>
</tr>
<tr>
<td>(b)</td>
<td></td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>(c)</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>(d)</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
<tr>
<td>(e)</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
</tr>
</tbody>
</table>
Source: Chen et al., 2020
MoCo vs. SimCLR vs. MoCo V2
<table>
<thead>
<tr>
<th>case</th>
<th>MLP</th>
<th>aug+</th>
<th>cos</th>
<th>epochs</th>
<th>batch</th>
<th>ImageNet acc.</th>
</tr>
</thead>
<tbody>
<tr>
<td>MoCo v1 [6]</td>
<td></td>
<td>✓</td>
<td>✓</td>
<td>200</td>
<td>256</td>
<td>60.6</td>
</tr>
<tr>
<td>SimCLR [2]</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>200</td>
<td>256</td>
<td>61.9</td>
</tr>
<tr>
<td>SimCLR [2]</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>200</td>
<td>8192</td>
<td>66.6</td>
</tr>
<tr>
<td>MoCo v2</td>
<td>✓</td>
<td>✓</td>
<td>✓</td>
<td>200</td>
<td>256</td>
<td><strong>67.5</strong></td>
</tr>
</tbody>
</table>
Table 2. **MoCo vs. SimCLR**: ImageNet linear classifier accuracy (ResNet-50, 1-crop 224×224), trained on features from unsupervised pre-training. “aug+” in SimCLR includes blur and stronger color distortion. SimCLR ablations are from Fig. 9 in [2] (we thank the authors for providing the numerical results).
**Key takeaways:**
- Non-linear projection head and strong data augmentation are crucial for contrastive learning.
- Decoupling mini-batch size with negative sample size allows MoCo-V2 to outperform SimCLR with smaller batch size (256 vs. 8192).
Source: Chen et al., 2020
MoCo vs. SimCLR vs. MoCo V2
Key takeaways:
- Non-linear projection head and strong data augmentation are crucial for contrastive learning.
- Decoupling mini-batch size with negative sample size allows MoCo-V2 to outperform SimCLR with smaller batch size (256 vs. 8192).
- ... all with much smaller memory footprint! (“end-to-end” means SimCLR here)
<table>
<thead>
<tr>
<th>mechanism</th>
<th>batch</th>
<th>memory / GPU</th>
<th>time / 200-ep.</th>
</tr>
</thead>
<tbody>
<tr>
<td>MoCo</td>
<td>256</td>
<td>5.0G</td>
<td>53 hrs</td>
</tr>
<tr>
<td>end-to-end</td>
<td>256</td>
<td>7.4G</td>
<td>65 hrs</td>
</tr>
<tr>
<td>end-to-end</td>
<td>4096</td>
<td>93.0G†</td>
<td>n/a</td>
</tr>
</tbody>
</table>
Table 3. Memory and time cost in 8 V100 16G GPUs, implemented in PyTorch. †: based on our estimation.
Source: Chen et al., 2020
Instance vs. Sequence Contrastive Learning
Instance-level contrastive learning: contrastive learning based on positive & negative instances. Examples: SimCLR, MoCo
Sequence-level contrastive learning: contrastive learning based on sequential / temporal orders. Example: Contrastive Predictive Coding (CPC)
Source: van den Oord et al., 2018
Contrastive Predictive Coding (CPC)
Contrastive: contrast between “right” and “wrong” sequences using contrastive learning.
Predictive: the model has to predict future patterns given the current context.
Coding: the model learns useful feature vectors, or “code”, for downstream tasks, similar to other self-supervised methods.
Source: van den Oord et al., 2018,
Figure source
Contrastive Predictive Coding (CPC)
1. Encode all samples in a sequence into vectors $z_t = g_{\text{enc}}(x_t)$
Source: van den Oord et al., 2018,
Contrastive Predictive Coding (CPC)
1. Encode all samples in a sequence into vectors $z_t = g_{enc}(x_t)$
2. Summarize context (e.g., half of a sequence) into a context code $c_t$ using an auto-regressive model ($g_{ar}$).
Figure source: van den Oord et al., 2018,
Contrastive Predictive Coding (CPC)
1. Encode all samples in a sequence into vectors $z_t = g_{enc}(x_t)$
2. Summarize context (e.g., half of a sequence) into a context code $c_t$ using an auto-regressive model ($g_{ar}$).
3. Compute InfoNCE loss between the context $c_t$ and future code $z_{t+k}$ using the following time-dependent score function:
$$s_k(z_{t+k}, c_t) = z_{t+k}^T W_k c_t$$
, where $W_k$ is a trainable matrix.
Source: van den Oord et al., 2018,
CPC example: modeling audio sequences
Source: van den Oord et al., 2018,
CPC example: modeling audio sequences
Figure 2: t-SNE visualization of audio (speech) representations for a subset of 10 speakers (out of 251). Every color represents a different speaker.
<table>
<thead>
<tr>
<th>Method</th>
<th>ACC</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>Phone classification</strong></td>
<td></td>
</tr>
<tr>
<td>Random initialization</td>
<td>27.6</td>
</tr>
<tr>
<td>MFCC features</td>
<td>39.7</td>
</tr>
<tr>
<td>CPC</td>
<td>64.6</td>
</tr>
<tr>
<td>Supervised</td>
<td>74.6</td>
</tr>
<tr>
<td><strong>Speaker classification</strong></td>
<td></td>
</tr>
<tr>
<td>Random initialization</td>
<td>1.87</td>
</tr>
<tr>
<td>MFCC features</td>
<td>17.6</td>
</tr>
<tr>
<td>CPC</td>
<td>97.4</td>
</tr>
<tr>
<td>Supervised</td>
<td>98.5</td>
</tr>
</tbody>
</table>
Linear classification on trained representations (LibriSpeech dataset)
Source: van den Oord et al., 2018,
CPC example: modeling visual context
Idea: split image into patches, model rows of patches from top to bottom as a sequence. I.e., use top rows as context to predict bottom rows.
Source: van den Oord et al., 2018,
CPC example: modeling visual context
- Compares favorably with other pretext task-based self-supervised learning method.
- Doesn’t do as well compared to newer instance-based contrastive learning methods on image feature learning.
<table>
<thead>
<tr>
<th>Method</th>
<th>Top-1 ACC</th>
</tr>
</thead>
<tbody>
<tr>
<td>Using AlexNet conv5</td>
<td></td>
</tr>
<tr>
<td>Video [28]</td>
<td>29.8</td>
</tr>
<tr>
<td>BiGan [35]</td>
<td>34.8</td>
</tr>
<tr>
<td>Colorization [10]</td>
<td>35.2</td>
</tr>
<tr>
<td>Jigsaw [29] *</td>
<td>38.1</td>
</tr>
<tr>
<td>Using ResNet-V2</td>
<td></td>
</tr>
<tr>
<td>Motion Segmentation [36]</td>
<td>27.6</td>
</tr>
<tr>
<td>Exemplar [36]</td>
<td>31.5</td>
</tr>
<tr>
<td>Relative Position [36]</td>
<td>36.2</td>
</tr>
<tr>
<td>Colorization [36]</td>
<td>39.6</td>
</tr>
<tr>
<td>CPC</td>
<td>48.7</td>
</tr>
</tbody>
</table>
Table 3: ImageNet top-1 unsupervised classification results. *Jigsaw is not directly comparable to the other AlexNet results because of architectural differences.
Source: van den Oord et al., 2018
Summary: Contrastive Representation Learning
A general formulation for contrastive learning:
\[
\text{score}(f(x), f(x^+)) \gg \text{score}(f(x), f(x^-))
\]
InfoNCE loss: N-way classification among positive and negative samples
\[
L = -\mathbb{E}_x \left[ \log \frac{\exp(s(f(x), f(x^+)))}{\exp(s(f(x), f(x^+))) + \sum_{j=1}^{N-1} \exp(s(f(x), f(x_j^-)))} \right]
\]
Commonly known as the InfoNCE loss \(\text{van den Oord et al., 2018}\)
A lower bound on the mutual information between \(f(x)\) and \(f(x^+)\)
\[
MI[f(x), f(x^+)] - \log(N) \geq -L
\]
**Summary: Contrastive Representation Learning**
**SimCLR**: a simple framework for contrastive representation learning
- **Key ideas**: non-linear projection head to allow flexible representation learning
- Simple to implement, effective in learning visual representation
- Requires large training batch size to be effective; large memory footprint
**Summary: Contrastive Representation Learning**
**MoCo (v1, v2):** contrastive learning using momentum sample encoder
- Decouples negative sample size from minibatch size; allows large batch training without TPU
- MoCo-v2 combines the key ideas from SimCLR, i.e., nonlinear projection head, strong data augmentation, with momentum contrastive learning
Summary: Contrastive Representation Learning
**CPC**: sequence-level contrastive learning
- Contrast “right” sequence with “wrong” sequence.
- InfoNCE loss with a time-dependent score function.
- Can be applied to a variety of learning problems, but not as effective in learning image representations compared to instance-level methods.
Other examples
Contrastive learning between image and natural language sentences
1. Contrastive pre-training
Contrastive Language–Image Pre-training (CLIP) Radford et al., 2021
2. Create dataset classifier from label text
3. Use for zero-shot prediction
Other examples
Contrastive learning on pixel-wise feature descriptors
Dense Object Net, Florence et al., 2018
Other examples
Dense Object Net, Florence et al., 2018
Vision and Language Models: Connecting the Pixel and Semantic Worlds at Scale
Why Vision-Language Models?
- Language is the most intuitive interface for an unstructured data space (e.g., natural images)
- Important to ground sensory information to semantic concepts
- Complementary information sources for a given task
- Claim: you cannot learn language without grounding
History: the first captioning model (Ordonez, 2011)
Im2Text: Describing Images Using 1 Million Captioned Photographs
Vicente Ordonez Girish Kulkarni Tamara L Berg
Stony Brook University
Stony Brook, NY 11794
{vordonezroma or tlberg}@cs.stonybrook.edu
Abstract
History: the first captioning model (Ordonez, 2011)
Query image
Gist + Tiny images ranking
Extract High Level Information
Top re-ranked images
Top associated captions
Across the street from Yannicks apartment. At night the headlight on the handlebars above the door lights up.
The building in which I live. My window is on the right on the 4th floor.
This is the car I was in after they had removed the roof and successfully removed me to the ambulance.
I really like doors. I took this photo out of the car window while driving by a church in Pennsylvania.
History: the first deep captioning model (Vinyals, 2015)
Show and Tell: A Neural Image Caption Generator
Oriol Vinyals
Google
vinyals@google.com
Alexander Toshev
Google
toshev@google.com
Samy Bengio
Google
bengio@google.com
Dumitru Erhan
Google
dumitru@google.com
History: the first deep captioning model (Vinyals, 2015)
History: the first VQA model (Agrawal, 2015)
VQA: Visual Question Answering
www.visualqa.org
Abstract—We propose the task of free-form and open-ended Visual Question Answering (VQA). Given an image and a natural language question about the image, the task is to provide an accurate natural language answer. Mirroring real-world scenarios, such as helping the visually impaired, both the questions and answers are open-ended. Visual questions selectivity target different areas of an image, including background details and underlying context. As a result, a system that succeeds at VQA typically needs a more detailed understanding of the image and complex reasoning than a system producing generic image captions. Moreover, VQA is amenable to automatic evaluation, since many open-ended answers contain only a few words or a closed set of answers that can be provided in a multiple-choice format. We provide a dataset containing ~0.25M images, ~0.76M questions, and ~10M answers (www.visualqa.org), and discuss the information it provides. Numerous baselines and methods for VQA are provided and compared with human performance. Our VQA demo is available on CloudCV (http://cloudcv.org/vqa).
History: the first VQA model (Agrawal, 2015)
Foundation VLM (2019-)
Hand-drawn sketch to website source code
GPT 4v(ision) (OpenAI, 2023)
Major Areas
- **Representation**: how to convert raw data into meaningful features
- **Translation**: transform one modality to another
- **Alignment**: discover relationships between elements across modalities
- **Fusion**: join features from modalities to support prediction
- **Co-learning**: transferring knowledge from one modality to another
Language->Vision: Language-guided Image Gen
**TEXT DESCRIPTION**
An astronaut Teddy bears A bowl of soup
riding a horse lounging in a tropical resort in space playing basketball with cats in space
in a photorealistic style in the style of Andy Warhol as a pencil drawing
---
https://openai.com/dall-e-2/
A cat sitting on a suitcase on the floor
A cat is sitting on a tree branch
A dog is running in the grass with a frisbee
A white teddy bear sitting in the grass
Two people walking on the beach with surfboards
A tennis player in action on the court
Two giraffes standing in a grassy field
A man riding a dirt bike on a dirt track
Image – Language Association
Contrastive learning between image and natural language sentences
1. Contrastive pre-training
2. Create dataset classifier from label text
3. Use for zero-shot prediction
CLIP (Contrastive Language–Image Pre-training) Radford et al., 2021
Image – language encoding architectures
**Associative**
- NCE
- $f_\phi$
- $f_\theta$
- image
- text
**Joint**
- $f_\theta$
- image
- text
- text
CLIP: Associative Encoding
CLIP (Contrastive Language–Image Pre-training) Radford et al., 2021
CLIP: Training
```python
# image_encoder - ResNet or Vision Transformer
# text_encoder - CBOW or Text Transformer
# I[n, h, w, c] - minibatch of aligned images
# T[n, l] - minibatch of aligned texts
# W_i[d_i, d_e] - learned proj of image to embed
# W_t[d_t, d_e] - learned proj of text to embed
# t - learned temperature parameter
# extract feature representations of each modality
I_f = image_encoder(I) # [n, d_i]
T_f = text_encoder(T) # [n, d_t]
# joint multimodal embedding [n, d_e]
I_e = l2_normalize(np.dot(I_f, W_i), axis=1)
T_e = l2_normalize(np.dot(T_f, W_t), axis=1)
# scaled pairwise cosine similarities [n, n]
logits = np.dot(I_e, T_e.T) * np.exp(t)
# symmetric loss function
labels = np.arange(n)
loss_i = cross_entropy_loss(logits, labels, axis=0)
loss_t = cross_entropy_loss(logits, labels, axis=1)
loss = (loss_i + loss_t)/2
```
CLIP: Zero-shot Classification
CLIP (Contrastive Language–Image Pre-training) Radford et al., 2021
CLIP: Zero-shot Classification
```python
# Load the model
device = "cuda" if torch.cuda.is_available() else "cpu"
model, preprocess = clip.load('ViT-B/32', device)
# Download the dataset
cifar100 = CIFAR100(root=os.path.expanduser("~/.cache"), download=True, train=False)
# Prepare the inputs
image, class_id = cifar100[3637]
image_input = preprocess(image).unsqueeze(0).to(device)
text_inputs = torch.cat([clip.tokenize(f"a photo of a {c}" for c in cifar100.classes)].to(device)
# Calculate features
with torch.no_grad():
image_features = model.encode_image(image_input)
text_features = model.encode_text(text_inputs)
# Pick the top 5 most similar labels for the image
image_features /= image_features.norm(dim=-1, keepdim=True)
text_features /= text_features.norm(dim=-1, keepdim=True)
similarity = (100.0 * image_features @ text_features.T).softmax(dim=-1)
values, indices = similarity[0].topk(5)
```
https://github.com/openai/CLIP
CLIP: Zero-shot Classification
PatchCamelyon (PCam)
healthy lymph node tissue (77.2%) Ranked 2 out of 2 labels
X: this is a photo of lymph node tumor tissue
✓: this is a photo of healthy lymph node tissue
ImageNet-A (Adversarial)
lyne (47.9%) Ranked 5 out of 200 labels
X: a photo of a fox equalled
X: a photo of a mongoose.
X: a photo of a shark.
X: a photo of a red fox.
✓: a photo of a lynx.
CIFAR-10
bird (40.3%) Ranked 1 out of 10 labels
✓: a photo of a bird.
X: a photo of a cali.
X: a photo of a deer.
X: a photo of a frog.
X: a photo of a dog.
CLEVR Count
4 (75.0%) Ranked 2 out of 8 labels
X: a photo of 3 objects.
✓: a photo of 4 objects.
X: a photo of 5 objects.
X: a photo of 6 objects.
X: a photo of 10 objects.
CLIP (Contrastive Language–Image Pre-training) Radford et al., 2021
Generating Images from CLIP Latents (DALL-E 2)
- Train image diffusion with classifier-free guidance using CLIP image embedding
- Train another diffusion model to predict CLIP image embedding from the CLIP embedding of the input text.
Hierarchical Text-Conditional Image Generation with CLIP Latents (Ramesh, Dhariwal, Nichol, Chu, Chen, 2022)
Generating Images from CLIP Latents (DALL-E 2)
Learning objective for the text to image CLIP embedding diffusion model:
$$L_{\text{prior}} = \mathbb{E}_{t \sim [1, T], z^{(t)}_i \sim q_t} \left[ \| f_{\theta}(z^{(t)}_i, t, y) - z^*_i \|^2 \right]$$
Hierarchical Text-Conditional Image Generation with CLIP Latents (Ramesh, Dhariwal, Nichol, Chu, Chen, 2022)
Joint Encodings: ViLBERT (2019)
Vision and Language Joint Pretraining
ViLBERT: Pretraining Task-Agnostic Visiolinguistic Representations for Vision-and-Language Tasks (Lu et al., 2019)
Joint Encodings: ViLBERT (2019)
ViLBERT: Pretraining Task-Agnostic Visiolinguistic Representations for Vision-and-Language Tasks (Lu et al., 2019)
Joint Encodings: ViLBERT (2019)
(a) Masked multi-modal learning
(b) Multi-modal alignment prediction
Vision and Language Joint Pretraining
ViLBERT: Pretraining Task-Agnostic Visiolinguistic Representations for Vision-and-Language Tasks (Lu et al., 2019)
Joint Encodings: ViLT (2021)
Categories of vision-language model in terms of model complexity / capacity
ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision (Kim and Son, 2021)
Joint Encodings: ViLT (2021)
ViLT: Vision-and-Language Transformer Without Convolution or Region Supervision (Kim and Son, 2021)
Data matters
Scaling Up Foundation Vision and Language Models
Pre-foundation model era (2015 – 2020)
Who is wearing glasses?
- man
- woman
Where is the child sitting?
- fridge
- arms
Is the umbrella upside down?
- yes
- no
How many children are in the bed?
- 2
- 1
Visual Question Answering
(Goyal and Knot, 2017)
Image Captioning
(MS-COCO)
Pre-foundation model era (2015 – 2020)
Q: Are there an equal number of large things and metal spheres?
Q: What size is the cylinder that is left of the brown metal thing that is left of the big sphere?
Q: There is a sphere with the same size as the metal cube; is it made of the same material as the small red sphere?
Q: How many objects are either small cylinders or metal things?
Diagnostic Language and Visual Reasoning
(CLEVR, Johnson et al., 2016)
The “Foundation Model Era” (2020-now)
- **LAION-400M**: 400 million image-text pairs
- Built using Common Crawl datasets,
- Extracting image-text pairs from HTML data.
- Post-processing filters unsuitable pairs using OpenAI's CLIP model.
- A10TB webdataset with CLIP embeddings and kNN indices.
The “Foundation Model Era” (2020-now)
- **LAION-5B**: Significantly larger than LAION-400M
- Crawled using 50 billion webpages + CLIP filtering
- 2.3 billion pairs in English + 2.2 billions in other languages + 1 billion unassignable languages (e.g., names).
The “Foundation Model Era” (2020-now)
Stable Diffusion
Stable Diffusion was made possible thanks to a collaboration with Stability AI and Runway and builds upon our previous work:
High-Resolution Image Synthesis with Latent Diffusion Models
Robin Rombach*, Andreas Blattmann*, Dominik Lorenz, Patrick Esser, Björn Ommer
CVPR ’22 Oral | GitHub | arXiv | Project page
Stable Diffusion is a latent text-to-image diffusion model. Thanks to a generous compute donation from Stability AI and support from LAION, we were able to train a Latent Diffusion Model on 512x512 images from a subset of the LAION-5B database. Similar to Google’s Imagen, this model uses a frozen CLIP ViT-L/14 text encoder to condition the model on text prompts. With its 860M UNet and 123M text encoder, the model is relatively lightweight and runs on a GPU with at least 10GB VRAM. See this section below and the model card.
A snapshot of vision-language dataset
Automatic data crawling is great but …
<table>
<thead>
<tr>
<th>tomclancysthedivision2_gc18images_0001</th>
<th>Enchantments-JUN16-13.jpg</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>They Shall Not Grow Old</strong>*. Watching Peter Jackson tinker with WW1 is like watching George Lucas tinker with <strong>Star Wars</strong>*. Only way more offensive. pic.twitter.com/PkteSrh9tR***</td>
<td></td>
</tr>
<tr>
<td>The International Code Council (ICC) has ratified a change to the 2021 International Building Code (IBC) to allow the use of shipping containers in commercial construction. Photo © <a href="http://www.bigstockphoto.com">www.bigstockphoto.com</a></td>
<td></td>
</tr>
</tbody>
</table>
https://laion-aesthetic.datasette.io/laion-aesthetic-6pls/images?_next=300
Composing Vision and Language Models
How to compose trained L and V models?
How to compose *trained* L and V models?
Fast finetuning
```
\[ f_\theta \rightarrow f_\phi \rightarrow \text{answer} \]
```
Language as interface
```
\[ f_\theta \rightarrow \text{text} \rightarrow f_\phi \rightarrow \text{answer} \]
```
Finetuning VLM: Frozen LM, finetune VM
• Train image encoder with frozen language model.
• At test time, can do 0-shot VQA or few-shot classification through in-context learning
Multimodal Few-Shot Learning with Frozen Language Models (Tsimpoukelli et al., 2021)
Finetuning VLM: Frozen LM, finetune VM
- Train image encoder with frozen language model.
- At test time, can do 0-shot VQA or few-shot classification through in-context learning
Multimodal Few-Shot Learning with Frozen Language Models (Tsimpoukelli et al., 2021)
### Finetuning VLM: Frozen LM, finetune VM
<table>
<thead>
<tr>
<th>n-shot Acc.</th>
<th>n=0</th>
<th>n=1</th>
<th>n=4</th>
<th>(\tau)</th>
</tr>
</thead>
<tbody>
<tr>
<td>Frozen</td>
<td>29.5</td>
<td>35.7</td>
<td>38.2</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{scratch}})</td>
<td>0.0</td>
<td>0.0</td>
<td>0.0</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{finetuned}})</td>
<td>24.0</td>
<td>28.2</td>
<td>29.2</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{train-blind}})</td>
<td>26.2</td>
<td>33.5</td>
<td>33.3</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{VQA}})</td>
<td>48.4</td>
<td>–</td>
<td>–</td>
<td>(\checkmark)</td>
</tr>
<tr>
<td>Frozen (_{\text{VQA-blind}})</td>
<td>39.1</td>
<td>–</td>
<td>–</td>
<td>(\checkmark)</td>
</tr>
<tr>
<td>Oscar [23]</td>
<td>73.8</td>
<td>–</td>
<td>–</td>
<td>(\checkmark)</td>
</tr>
<tr>
<td>(\tau) Frozen</td>
<td>5.9</td>
<td>9.7</td>
<td>12.6</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{400mLM})</td>
<td>4.0</td>
<td>5.9</td>
<td>6.6</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{finetuned}})</td>
<td>4.2</td>
<td>4.1</td>
<td>4.6</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{train-blind}})</td>
<td>3.3</td>
<td>7.2</td>
<td>0.0</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{VQA}})</td>
<td>19.6</td>
<td>–</td>
<td>–</td>
<td>(\times)</td>
</tr>
<tr>
<td>Frozen (_{\text{VQA-blind}})</td>
<td>12.5</td>
<td>–</td>
<td>–</td>
<td>(\times)</td>
</tr>
<tr>
<td>MAVEX [42]</td>
<td>39.4</td>
<td>–</td>
<td>–</td>
<td>(\checkmark)</td>
</tr>
</tbody>
</table>
- Training large VLM from scratch does not work at all
- Finetuning LM degrades performance
- “Blind” baselines till works, showing the innate power of LM
Multimodal Few-Shot Learning with Frozen Language Models (Tsimpoukelli et al., 2021)
Finetuning VLM: freeze both LM and VM
- Interleaved text-image input
- Only finetune the cross attention (XATTN-DENSE) layers
Flamingo: a Visual Language Model for Few-Shot Learning (Alayrac et al., 2022)
Finetuning VLM: freeze both LM and VM
- Largely outperforms previous zero/few shot SotA
- More in-context learning examples do help
- Larger model gives better results
Flamingo: a Visual Language Model for Few-Shot Learning (Alayrac et al., 2022)
Finetuning VLM: freeze both LM and VM
Freeze VM and LM. Train the linear layer and LORA finetune Llama 2
MiniGPT-v2: large language model as a unified interface for vision-language multi-task learning (Chen et al., 2023)
Low-rank finetuning (LORA) quickly finetune a billion-parameter model
**Problem**: finetuning still takes a lot of data, especially if the model is huge and/or the domain gap is large.
**Fact**: finetuning is just adding a $W_\delta$ to the existing weight matrix $W$, i.e., $W^* = W + W_\delta$
**Hypothesis**: $W_\delta$ is low-rank, meaning that $W_\delta$ can be decomposed into two smaller matrices $A$ and $B$, i.e., $W_\delta = A^T B$.
**So what?**: $A$ and $B$ have a lot fewer parameters than the full $W$. Requires less data and faster to train.
Hu, Edward J., et al. "Lora: Low-rank adaptation of large language models.”, 2021
Low-rank finetuning (LORA)
quickly finetune a billion-parameter model
Parameter-Efficient Fine-Tuning (PEFT) methods enable efficient adaptation of pre-trained language models (PLMs) to various downstream applications without fine-tuning all the model’s parameters. Fine-tuning large-scale PLMs is often prohibitively costly. In this regard, PEFT methods only fine-tune a small number of (extra) model parameters, thereby greatly decreasing the computational and storage costs. Recent State-of-the-Art PEFT techniques achieve performance comparable to that of full fine-tuning.
Seamlessly integrated with 📦 Accelerate for large scale models leveraging DeepSpeed and Big Model Inference.
Supported methods:
1. LoRA: LORA: LOW-RANK ADAPTATION OF LARGE LANGUAGE MODELS
2. Prefix Tuning: Prefix-Tuning: Optimizing Continuous Prompts for Generation, P-Tuning v2: Prompt Tuning Can Be Comparable to Fine-tuning Universally Across Scales and Tasks
3. P-Tuning: GPT Understands, Too
4. Prompt Tuning: The Power of Scale for Parameter-Efficient Prompt Tuning
5. AdaLoRA: Adaptive Budget Allocation for Parameter-Efficient Fine-Tuning
6. (J.A): Few-Shot Parameter-Efficient Fine-Tuning is Better and Cheaper than In-Context Learning
7. MultiTask Prompt Tuning: Multitask Prompt Tuning Enables Parameter-Efficient Transfer Learning
9. LoKr: Krona: Parameter Efficient Tuning with Kronecker Adapter based on Navigating Text-To-Image Customization From sCyCoris Fine-Tuning to Model Evaluation implementation
```python
import torch
from peft import inject_adapter_in_model, LoraConfig
class DummyModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.embedding = torch.nn.Embedding(10, 10)
self.linear = torch.nn.Linear(10, 10)
self.lm_head = torch.nn.Linear(10, 10)
def forward(self, input_ids):
x = self.embedding(input_ids)
x = self.linear(x)
x = self.lm_head(x)
return x
lora_config = LoraConfig(
lora_alpha=16,
lora_dropout=0.1,
r=64,
bias="none",
target_modules=["linear"],
)
model = DummyModel()
model = inject_adapter_in_model(lora_config, model)
dummy_inputs = torch.LongTensor([[0, 1, 2, 3, 4, 5, 6, 7]])
dummy_outputs = model(dummy_inputs)
```
https://github.com/huggingface/peft
How to compose trained L and V models?
Fast finetuning
Language as interface
Neural Module Networks (Andreas et al., 2015)
Idea: train modular networks (attend, classify). Use a controller network to decide how to compose the modules together to solve a task.
## Neural Module Networks (Andreas et al., 2015)
<table>
<thead>
<tr>
<th>How many different lights in various different shapes and sizes?</th>
<th>What is the color of the horse?</th>
<th>What color is the vase?</th>
<th>Is the bus full of passengers?</th>
<th>Is there a red shape above a circle?</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>measure[is](attend[red], re-attend[above](attend[circle]))</code></td>
<td>classify[is](attend[bus], attend[full])</td>
<td>classify<a href="attend%5Bvase%5D">color</a></td>
<td>classify<a href="attend%5Bhorse%5D">color</a></td>
<td>measure<a href="attend%5Blight%5D">count</a></td>
</tr>
<tr>
<td>four (four)</td>
<td>green (green)</td>
<td>brown (brown)</td>
<td>measure<a href="attend%5Blight%5D">is</a></td>
<td></td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>What is stuffed with toothbrushes wrapped in plastic?</th>
<th>Where does the shabby cat watch a horse eating hay?</th>
<th>What material are the boxes made of?</th>
<th>Is this a clock?</th>
<th>Is a red shape blue?</th>
</tr>
</thead>
<tbody>
<tr>
<td>classify<a href="attend%5Bstuff%5D">what</a></td>
<td>classify<a href="attend%5Bwatch%5D">where</a></td>
<td>classify<a href="attend%5Bbox%5D">material</a></td>
<td>measure<a href="attend%5Bclock%5D">is</a></td>
<td>measure[is](combine[and](attend[red], attend[blue]))</td>
</tr>
<tr>
<td>container (cup)</td>
<td>pen (harness)</td>
<td>leather (cardboard)</td>
<td>yes (no)</td>
<td>yes (no)</td>
</tr>
</tbody>
</table>
Inferring and Executing Programs for Visual Reasoning (Johnson et al., 2017)
Similar to NMN, but train a program generator using REINFORCE. Reward comes from whether the answer is correct.
Visual Programming: Compositional visual reasoning without training (Gupta et al., 2023)
**Visual Programming: Compositional visual reasoning without training** (Gupta et al., 2023)
**Instruction:** Replace the ground with white snow and the bear with a white polar bear
**Prediction:**
<table>
<thead>
<tr>
<th>Action</th>
<th>Image</th>
</tr>
</thead>
<tbody>
<tr>
<td>OBJ1=Seg</td>
<td><img src="image" alt="Image" /></td>
</tr>
<tr>
<td>OBJ1=Select</td>
<td><img src="image" alt="Image" /></td>
</tr>
<tr>
<td>OBJ2=Seg</td>
<td><img src="image" alt="Image" /></td>
</tr>
<tr>
<td>OBJ3=Select</td>
<td><img src="image" alt="Image" /></td>
</tr>
<tr>
<td>IMAGE=Replace</td>
<td><img src="image" alt="Image" /></td>
</tr>
</tbody>
</table>
```latex
\text{OBJ1}=\text{Seg}(\text{image}=\text{IMAGE})
\text{OBJ1}=\text{Select}(\text{image}=\text{IMAGE}, \text{object}=\text{OBJ1}, \text{query}=\text{ground}')
\text{OBJ2}=\text{Seg}(\text{image}=\text{IMAGE})
\text{OBJ3}=\text{Select}(\text{image}=\text{IMAGE}, \text{object}=\text{OBJ3}, \text{query}=\text{bear}')
\text{IMAGE}=\text{Replace}(\text{image}=\text{IMAGE}, \text{object}=\text{OBJ1}, \text{prompt}=\text{white snow}')
```
Use large language models (LLMs) to generate program-like semantic plans from natural language command.
VoxPoser (Huang et al., 2023): Program to Grounded Actions
Use LLMs to guide VMs to find where to act next in a 3D scene.
VoxPoser (Huang et al., 2023): Program to Grounded Actions
“Sort the paper trash into the blue tray.”
Summary: Large Vision and Language Models
- Very active field of research, with a history as long as modern deep learning (2011 -)
- Foundation vision and language models have revolutionized the research paradigm post 2019.
- Trending towards larger model and dataset.
- Many active research on how to finetune / adapt VLMs with small amount of compute / data.
- The future is going to be multimodal.
|
{"Source-Url": "https://sites.cc.gatech.edu/classes/AY2024/cs7643_fall/assets/L20_VLM.pdf", "len_cl100k_base": 13045, "olmocr-version": "0.1.53", "pdf-total-pages": 103, "total-fallback-pages": 0, "total-input-tokens": 110641, "total-output-tokens": 16381, "length": "2e13", "weborganizer": {"__label__adult": 0.000782012939453125, "__label__art_design": 0.004791259765625, "__label__crime_law": 0.0005831718444824219, "__label__education_jobs": 0.0065765380859375, "__label__entertainment": 0.0008330345153808594, "__label__fashion_beauty": 0.0004811286926269531, "__label__finance_business": 0.0006799697875976562, "__label__food_dining": 0.0005755424499511719, "__label__games": 0.002338409423828125, "__label__hardware": 0.00266265869140625, "__label__health": 0.0012454986572265625, "__label__history": 0.0008645057678222656, "__label__home_hobbies": 0.0003197193145751953, "__label__industrial": 0.0007481575012207031, "__label__literature": 0.0015468597412109375, "__label__politics": 0.000530242919921875, "__label__religion": 0.0011167526245117188, "__label__science_tech": 0.43310546875, "__label__social_life": 0.0003170967102050781, "__label__software": 0.034271240234375, "__label__software_dev": 0.50439453125, "__label__sports_fitness": 0.0004279613494873047, "__label__transportation": 0.0005016326904296875, "__label__travel": 0.0003361701965332031}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41498, 0.03058]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41498, 0.45809]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41498, 0.71429]], "google_gemma-3-12b-it_contains_pii": [[0, 70, false], [70, 300, null], [300, 342, null], [342, 402, null], [402, 438, null], [438, 694, null], [694, 730, null], [730, 854, null], [854, 1235, null], [1235, 1494, null], [1494, 1745, null], [1745, 2015, null], [2015, 2395, null], [2395, 2926, null], [2926, 3313, null], [3313, 3399, null], [3399, 4590, null], [4590, 5814, null], [5814, 6945, null], [6945, 7090, null], [7090, 7356, null], [7356, 7577, null], [7577, 9330, null], [9330, 9769, null], [9769, 10172, null], [10172, 10482, null], [10482, 10924, null], [10924, 11198, null], [11198, 11606, null], [11606, 12630, null], [12630, 13652, null], [13652, 14415, null], [14415, 14758, null], [14758, 15140, null], [15140, 15290, null], [15290, 15558, null], [15558, 16028, null], [16028, 16102, null], [16102, 16804, null], [16804, 17020, null], [17020, 18012, null], [18012, 18571, null], [18571, 18923, null], [18923, 19277, null], [19277, 19615, null], [19615, 19874, null], [19874, 19986, null], [19986, 20042, null], [20042, 20120, null], [20120, 20415, null], [20415, 20680, null], [20680, 21243, null], [21243, 21512, null], [21512, 21569, null], [21569, 22880, null], [22880, 22925, null], [22925, 23019, null], [23019, 23368, null], [23368, 23684, null], [23684, 24019, null], [24019, 24292, null], [24292, 24443, null], [24443, 24539, null], [24539, 25390, null], [25390, 25490, null], [25490, 26435, null], [26435, 27237, null], [27237, 27583, null], [27583, 27944, null], [27944, 28131, null], [28131, 28279, null], [28279, 28536, null], [28536, 28743, null], [28743, 28873, null], [28873, 28935, null], [28935, 29220, null], [29220, 29683, null], [29683, 29979, null], [29979, 30239, null], [30239, 31138, null], [31138, 31176, null], [31176, 31826, null], [31826, 31863, null], [31863, 31902, null], [31902, 32145, null], [32145, 32410, null], [32410, 32675, null], [32675, 33923, null], [33923, 34130, null], [34130, 34379, null], [34379, 34602, null], [34602, 35245, null], [35245, 37628, null], [37628, 37707, null], [37707, 37891, null], [37891, 39231, null], [39231, 39421, null], [39421, 39510, null], [39510, 40767, null], [40767, 40871, null], [40871, 40994, null], [40994, 41097, null], [41097, 41498, null]], "google_gemma-3-12b-it_is_public_document": [[0, 70, true], [70, 300, null], [300, 342, null], [342, 402, null], [402, 438, null], [438, 694, null], [694, 730, null], [730, 854, null], [854, 1235, null], [1235, 1494, null], [1494, 1745, null], [1745, 2015, null], [2015, 2395, null], [2395, 2926, null], [2926, 3313, null], [3313, 3399, null], [3399, 4590, null], [4590, 5814, null], [5814, 6945, null], [6945, 7090, null], [7090, 7356, null], [7356, 7577, null], [7577, 9330, null], [9330, 9769, null], [9769, 10172, null], [10172, 10482, null], [10482, 10924, null], [10924, 11198, null], [11198, 11606, null], [11606, 12630, null], [12630, 13652, null], [13652, 14415, null], [14415, 14758, null], [14758, 15140, null], [15140, 15290, null], [15290, 15558, null], [15558, 16028, null], [16028, 16102, null], [16102, 16804, null], [16804, 17020, null], [17020, 18012, null], [18012, 18571, null], [18571, 18923, null], [18923, 19277, null], [19277, 19615, null], [19615, 19874, null], [19874, 19986, null], [19986, 20042, null], [20042, 20120, null], [20120, 20415, null], [20415, 20680, null], [20680, 21243, null], [21243, 21512, null], [21512, 21569, null], [21569, 22880, null], [22880, 22925, null], [22925, 23019, null], [23019, 23368, null], [23368, 23684, null], [23684, 24019, null], [24019, 24292, null], [24292, 24443, null], [24443, 24539, null], [24539, 25390, null], [25390, 25490, null], [25490, 26435, null], [26435, 27237, null], [27237, 27583, null], [27583, 27944, null], [27944, 28131, null], [28131, 28279, null], [28279, 28536, null], [28536, 28743, null], [28743, 28873, null], [28873, 28935, null], [28935, 29220, null], [29220, 29683, null], [29683, 29979, null], [29979, 30239, null], [30239, 31138, null], [31138, 31176, null], [31176, 31826, null], [31826, 31863, null], [31863, 31902, null], [31902, 32145, null], [32145, 32410, null], [32410, 32675, null], [32675, 33923, null], [33923, 34130, null], [34130, 34379, null], [34379, 34602, null], [34602, 35245, null], [35245, 37628, null], [37628, 37707, null], [37707, 37891, null], [37891, 39231, null], [39231, 39421, null], [39421, 39510, null], [39510, 40767, null], [40767, 40871, null], [40871, 40994, null], [40994, 41097, null], [41097, 41498, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41498, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41498, null]], "pdf_page_numbers": [[0, 70, 1], [70, 300, 2], [300, 342, 3], [342, 402, 4], [402, 438, 5], [438, 694, 6], [694, 730, 7], [730, 854, 8], [854, 1235, 9], [1235, 1494, 10], [1494, 1745, 11], [1745, 2015, 12], [2015, 2395, 13], [2395, 2926, 14], [2926, 3313, 15], [3313, 3399, 16], [3399, 4590, 17], [4590, 5814, 18], [5814, 6945, 19], [6945, 7090, 20], [7090, 7356, 21], [7356, 7577, 22], [7577, 9330, 23], [9330, 9769, 24], [9769, 10172, 25], [10172, 10482, 26], [10482, 10924, 27], [10924, 11198, 28], [11198, 11606, 29], [11606, 12630, 30], [12630, 13652, 31], [13652, 14415, 32], [14415, 14758, 33], [14758, 15140, 34], [15140, 15290, 35], [15290, 15558, 36], [15558, 16028, 37], [16028, 16102, 38], [16102, 16804, 39], [16804, 17020, 40], [17020, 18012, 41], [18012, 18571, 42], [18571, 18923, 43], [18923, 19277, 44], [19277, 19615, 45], [19615, 19874, 46], [19874, 19986, 47], [19986, 20042, 48], [20042, 20120, 49], [20120, 20415, 50], [20415, 20680, 51], [20680, 21243, 52], [21243, 21512, 53], [21512, 21569, 54], [21569, 22880, 55], [22880, 22925, 56], [22925, 23019, 57], [23019, 23368, 58], [23368, 23684, 59], [23684, 24019, 60], [24019, 24292, 61], [24292, 24443, 62], [24443, 24539, 63], [24539, 25390, 64], [25390, 25490, 65], [25490, 26435, 66], [26435, 27237, 67], [27237, 27583, 68], [27583, 27944, 69], [27944, 28131, 70], [28131, 28279, 71], [28279, 28536, 72], [28536, 28743, 73], [28743, 28873, 74], [28873, 28935, 75], [28935, 29220, 76], [29220, 29683, 77], [29683, 29979, 78], [29979, 30239, 79], [30239, 31138, 80], [31138, 31176, 81], [31176, 31826, 82], [31826, 31863, 83], [31863, 31902, 84], [31902, 32145, 85], [32145, 32410, 86], [32410, 32675, 87], [32675, 33923, 88], [33923, 34130, 89], [34130, 34379, 90], [34379, 34602, 91], [34602, 35245, 92], [35245, 37628, 93], [37628, 37707, 94], [37707, 37891, 95], [37891, 39231, 96], [39231, 39421, 97], [39421, 39510, 98], [39510, 40767, 99], [40767, 40871, 100], [40871, 40994, 101], [40994, 41097, 102], [41097, 41498, 103]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41498, 0.13289]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
a0ffcbc09a47e21b4b1e8cfc3ca4bb3d0fa5709a
|
[REMOVED]
|
{"len_cl100k_base": 11598, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 56138, "total-output-tokens": 14367, "length": "2e13", "weborganizer": {"__label__adult": 0.0004413127899169922, "__label__art_design": 0.00031375885009765625, "__label__crime_law": 0.0002574920654296875, "__label__education_jobs": 0.0007100105285644531, "__label__entertainment": 7.194280624389648e-05, "__label__fashion_beauty": 0.00015795230865478516, "__label__finance_business": 0.00018596649169921875, "__label__food_dining": 0.0003323554992675781, "__label__games": 0.0005850791931152344, "__label__hardware": 0.0006022453308105469, "__label__health": 0.00030493736267089844, "__label__history": 0.0001628398895263672, "__label__home_hobbies": 9.870529174804688e-05, "__label__industrial": 0.00023734569549560547, "__label__literature": 0.000209808349609375, "__label__politics": 0.00020420551300048828, "__label__religion": 0.0003731250762939453, "__label__science_tech": 0.00299835205078125, "__label__social_life": 0.0001246929168701172, "__label__software": 0.004291534423828125, "__label__software_dev": 0.986328125, "__label__sports_fitness": 0.0003116130828857422, "__label__transportation": 0.0003659725189208984, "__label__travel": 0.00019609928131103516}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 53262, 0.05106]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 53262, 0.29174]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 53262, 0.7939]], "google_gemma-3-12b-it_contains_pii": [[0, 3914, false], [3914, 8314, null], [8314, 12928, null], [12928, 16958, null], [16958, 18170, null], [18170, 21602, null], [21602, 26274, null], [26274, 30875, null], [30875, 35538, null], [35538, 40039, null], [40039, 44274, null], [44274, 46111, null], [46111, 51172, null], [51172, 51584, null], [51584, 51737, null], [51737, 53262, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3914, true], [3914, 8314, null], [8314, 12928, null], [12928, 16958, null], [16958, 18170, null], [18170, 21602, null], [21602, 26274, null], [26274, 30875, null], [30875, 35538, null], [35538, 40039, null], [40039, 44274, null], [44274, 46111, null], [46111, 51172, null], [51172, 51584, null], [51584, 51737, null], [51737, 53262, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 53262, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 53262, null]], "pdf_page_numbers": [[0, 3914, 1], [3914, 8314, 2], [8314, 12928, 3], [12928, 16958, 4], [16958, 18170, 5], [18170, 21602, 6], [21602, 26274, 7], [26274, 30875, 8], [30875, 35538, 9], [35538, 40039, 10], [40039, 44274, 11], [44274, 46111, 12], [46111, 51172, 13], [51172, 51584, 14], [51584, 51737, 15], [51737, 53262, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 53262, 0.24498]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
85a5110bc6860592cf1960648580d97cbea43f75
|
Automatic Discovery and Quantification of Information Leaks
Michael Backes
Saarland University and MPI-SWS
backes@cs.uni-sb.de
Boris Köpf
MPI-SWS
bkoepf@mpi-sws.org
Andrey Rybalchenko
MPI-SWS
rybal@mpi-sws.org
Abstract
Information-flow analysis is a powerful technique for reasoning about the sensitive information exposed by a program during its execution. We present the first automatic method for information-flow analysis that discovers what information is leaked and computes its comprehensive quantitative interpretation. The leaked information is characterized by an equivalence relation on secret artifacts, and is represented by a logical assertion over the corresponding program variables. Our measurement procedure computes the number of discovered equivalence classes and their sizes. This provides a basis for computing a set of quantitative properties, which includes all established information-theoretic measures in quantitative information-flow. Our method exploits an inherent connection between formal models of qualitative information-flow and program verification techniques. We provide an implementation of our method that builds upon existing tools for program verification and information-theoretic analysis. Our experimental evaluation indicates the practical applicability of the presented method.
1. Introduction
Information-flow analysis keeps track of sensitive information that is processed by a program during its execution. One of the main goals of the analysis is to check whether any sensitive information is exposed to the environment. When information is leaked, the analysis needs to qualitatively and quantitatively assess the extent of the leak.
The existing approaches to information-flow analysis provide a variety of techniques for dealing with the disclosure of information, see [35]. Several approaches deal with the qualitative aspect of information-flow analysis [1], [5], [13], [18], [34], which is usually formalized by an equivalence relation over secret artifacts manipulated by the program. Security guarantees correspond to the (im)possibility of distinguishing between secret artifacts by observing program behaviors. Existing quantitative approaches characterize the magnitude of information leaks, e.g. in terms of the number of secret bits that are revealed [9], [17], or in terms of the rate at which information can be transmitted through the leak [26].
Unfortunately, the applicability of the existing information-flow analyses suffers from several limitations. The qualitative approaches assume that the equivalence relation is supplied manually; however, such relations are notoriously difficult to find due to the complexity of reasoning about how the program treats its secrets. On the quantitative side, the estimates computed by the existing approaches mostly deal with the number of leaked bits, e.g. [10], [29], which is not sufficient for establishing comprehensive security guarantees. For example, a security analysis might require a measure for the number of attempts that are needed to identify a secret value, bounds on the throughput of the program if it is used as an unwanted communication channel, or a combination of several such measures.
In this paper, we present the first automatic method for information-flow analysis that addresses these challenges. Our method delivers a complete analysis that automatically discovers the leaked information, determines its information-theoretic characteristics, and computes a comprehensive set of quantitative properties.
The leaked information is computed in the form of an equivalence relation and is represented by a logical assertion over program variables. The equivalence relation computed by our method is precise, i.e., describes only the information that is leaked, and can be used on its own, e.g., for declassification policies [4]. Our method goes beyond this qualitative characterization, and uses the assertion as an input to a measurement procedure that computes the number of discovered equivalence classes and their sizes. We demonstrate how these data provide a basis for computing a set of quantitative properties, which is comprehensive in the sense that it includes all information-theoretic measures that are commonly considered in the literature on quantitative information flow, i.e., Shannon entropy, guessing entropy, min-entropy, and channel capacity.
Our method exploits an inherent connection between qualitative information-flow and program verification techniques. The desired equivalence relation can be viewed as a precondition for safe execution of the program under consideration augmented with a ‘shadow’ copy and an assertion checking the information leakage. The assertion fails whenever the shadow copy of the program exhibits a behavior that witnesses the ability to distinguish equivalent
artifacts. Our method iteratively constructs the equivalence relation. It starts with a coarse initial candidate that claims no leakage of sensitive information, and incrementally weakens the claim by refining the candidate relation, until there is no witness of further leaks. The key to the automatic construction is the successive exclusion of counterexamples witnessing inadequacy of the current equivalence.
We identify the characteristics of the equivalence relation that provide the common basis for computing various entropy measures, as required by the quantitative analysis. These characteristics consist of the number of equivalence classes and their sizes, and can be further refined by probability distributions inside the equivalence classes. We show how, given these characteristics, one can compute the average uncertainty about the secret in bits (Shannon entropy), the average number of guesses that are needed to identify secrets (conditional and minimal guessing entropy, respectively), and the maximal rate at which information can be transmitted using the program as a communication channel (channel capacity). Finally, we present a procedure for computing these characteristics for a given equivalence relation.
The presentation of our method is aligned with the existing body of research on program verification and symbolic reasoning. It suggests a basis for an automatic tool that can be built by utilizing existing software model checkers, quantifier elimination algorithms and solution counting techniques. We use these components in a black-box fashion, hence our tool will immediately benefit from the development of the state-of-the-art in the respective areas.
We have implemented the presented method and have successfully applied it to analyze a series of example programs: a password checker, an electronic purse, a sum query, and an electronic auction. For each program, we determined the equivalence relations representing the leaked information and computed the sizes of the equivalence classes together with different information-theoretic interpretations.
In summary, our main contribution is the first automatic method for information-flow analysis that discovers what information is leaked and computes its comprehensive quantitative interpretation.
Outline. The paper is structured as follows. We present related work in the remainder of this section. In Section 2, we illustrate how our method applies to an example program. We give the basic definitions in Section 3. In Section 4, we present our method in abstract terms, before we outline its implementation in Section 5. We present experimental results in Section 6.
Related work. For an overview of language-based approaches to information-flow security, refer to [33]; for an overview on declassification, see [35].
The use of equivalence relations to characterize partial information flow was proposed in [13] and further explored in [5], [18], [41]. Several approaches use equivalence relations to specify downgrading assertions within information flow type systems [4], [34]. Our method can be used to synthesize such assertions. The idea that secure information flow can be verified by analyzing pairs of program runs can be found in [5], [16], [23], [38], [39].
Early approaches for quantifying information flow focus on the capacity of covert channels between processes in multi-user systems [20], [30], [40] rather than on information flow in programs. The first approach to connect information theory to program analysis is [17].
A type system for statically deriving quantitative bounds on the information that a program leaks is presented in [9], [10]. The analysis is based on Shannon entropy and an observer that can see, but not influence, the public inputs to the program. Our method accommodates a variety of information measures and captures attackers that can interact with the program by providing inputs.
The information leakage of loops can be characterized in terms of the loop’s output and the number of iterations [27]. In our model, the information that is revealed by the number of loop iterations can be captured by augmenting loops with observable counters. For given upper bounds on the number of iterations, our method can be used to automatically determine this information.
Information-theoretic bounds in terms of the number of program executions are presented in [24]. The algorithms for computing these bounds for a concrete system rely on an enumeration of the entire input space, and it is not yet clear how the analysis scales to larger systems.
The model in [12] captures an attacker’s belief about a secret, which may also be wrong. Reasoning about beliefs is out of the scope of entropy-based measures, such as the ones used in this paper. One advantage of entropy-based measures is the direct connection to equivalence relations, which makes them amenable to automated reasoning techniques. To the best of our knowledge, our method is the first static, quantitative analysis that has been implemented.
An automatic dynamic quantitative information flow analysis method is presented in [29]. The method enables one to derive tight bounds on the information flow in individual program runs, but does not yield bounds on the maximal information that a program can leak, which is important for security analysis.
2. Illustrative example
To illustrate our method and the kind of results that it provides, we show how it applies to an example program.
We consider an electronic sealed-bid auction in which bidders want their bids to remain confidential and the winner is publicly announced. The announcement of the winner
reveals partial information about the individual bids, e.g., about their ordering.
This kind of electronic auction can be implemented as a program \( P \) that takes as input \( n \) secret bids \( h_1, \ldots, h_n \) and outputs the winner of the auction in a variable \( l \), i.e., upon termination, \( l = i \) such that \( h_i = \max\{h_1, \ldots, h_n\} \).
```c
int l=0;
for (int i=0; i<n; i++){
if (h[i]>h[l])
l=i;
}
```
In the first step, we deduce an equivalence relation \( R \) on the set of possible secret inputs to express what an attacker can learn about the input by observing the program's output: two inputs are in the same equivalence class whenever the program produces the same result on both inputs. By observing the output of the program, the attacker can then only deduce the secret input up to its \( R \)-equivalence class. We cast such equivalence relations \( R \) as formulas over pairs of secret inputs.
Checking that a program leaks no more secret information than what is specified by \( R \) can be cast as a reachability problem on two independent instances of the program, and it can be solved using off-the-shelf model-checkers, such as BLAST [21], SLAM [3], SATSB [11], and ARMc [31]. If the check fails (i.e., if the program leaks more information), the model checker produces a counterexample: it returns two program paths \( \pi \) and \( \eta \) along which two \( R \)-related inputs produce different outputs.
Guided by this counterexample, we refine the relation \( R \) to \( R' \), such that \( R' \) distinguishes between all secret inputs that lead to different observable outputs along the paths \( \pi \) and \( \eta \). We iterate this refinement process until we have found a relation \( R \) for which the check fails; this \( R \) is a logical characterization of the maximal information that the program can leak.
For our auction program and \( n = 3 \), this iterative refinement process yields the relation
\[
R \equiv (h_1 < h_3 \land h_2 < h_3 \land \overline{h_1} < \overline{h_3} \land \overline{h_2} < \overline{h_3})
\]
\[
\lor (\overline{h_1} < \overline{h_3} \land \overline{h_1} < \overline{h_2} < h_1 \land h_3 < h_2 < \overline{h_3})
\]
\[
\lor (\overline{h_2} \leq \overline{h_1} \land h_1 < h_2 < h_3 \land h_1 < h_2 < h_3 \land h_2 < h_1)
\]
\[
\lor (h_2 < h_3 \land h_3 < h_2 \land h_1 < h_3 \land h_2 \leq \overline{h_1} \land \overline{h_3} \leq \overline{h_1})
\]
\[
\lor (h_3 < h_2 \land h_2 \leq h_1 \land \overline{h_2} \leq \overline{h_1} \land \overline{h_3} \leq \overline{h_1})
\]
which represents a set of pairs \((h_1, h_2, h_3), (\overline{h_1}, \overline{h_2}, \overline{h_3})\) of triples of input variables, i.e., a binary relation. Here \( \overline{h_1} \), \( \overline{h_2} \) and \( \overline{h_3} \) denote the secret bids that are input to the second instance of the program. Our specific implementation uses the model-checker ARMc, which does not cover arrays. To analyze the auction program, we unfold the loop and replace each array element \( h[i] \) by a variable \( h_i \). Note that this is a limitation of our implementation rather than one of our method.
In the second step, we determine the \( R \)-equivalence classes. To this end, we pick an arbitrary vector of bids (say, \((0, 0, 0)\)) and use it to instantiate the variables \( \overline{h_1}, \overline{h_2}, \overline{h_3} \) of \( R \). In this way, we obtain a formula \( B_1 \) over the variables \( h_1, h_2, h_3 \) that represents all the bids that are \( R \)-equivalent to \((0, 0, 0)\), i.e., the \( R \)-equivalence class of \((0, 0, 0)\). Then we pick a representative of another equivalence class, i.e., a model of \( \neg B_1 \) and repeat the procedure. We proceed in this way until we have enumerated all equivalence classes, i.e., until \( B_1 \lor \cdots \lor B_r \equiv \top \). The Omega-calculator [32] is a tool for manipulating formulas in Presburger Arithmetic (i.e., linear arithmetic with quantifiers) using various operations, such as computing models, relational composition, and set difference, and we use it to implement the enumeration of the equivalence classes. For our auction example, we obtain the following equivalence classes:
\[
B_1 \equiv h_2 \leq h_1 \land h_3 \leq h_1 ,
\]
\[
B_2 \equiv h_1 < h_3 \land h_2 < h_3 ,
\]
\[
B_3 \equiv (h_1 < h_3 \land h_3 \leq h_2) \lor (h_3 \leq h_1 \land h_1 < h_2) ,
\]
where the clauses of \( B_3 \) are exclusive.
In the third step, we use LattE (Lattice point Enumeration) [25], a tool for computing the number of integer solutions of linear arithmetic constraints, for counting the size of each of the equivalence classes. For this, we have to add additional constraints to bound the size of the input domain. For our auction program, we choose as inputs positive integers of 32 bits, i.e. \( 0 \leq h_1, h_2, h_3 \leq 2^{32} - 1 \).
Then LattE determines the following sizes:
\[
|B_1| = 26409387513978151235418587136 ,
\]
\[
|B_2| = 264093874955314071670935520 ,
\]
\[
|B_3| = 26409387504754779196416327680 .
\]
The result shows that the three equivalence classes \( B_1, B_2, B_3 \) are of almost equal size; the difference is due to the asymmetry with which our program determines the winner of an auction with two or more equal bids. If the input values are independently and uniformly chosen (modeled by a random variable \( U \)), the attacker’s initial uncertainty about the auction is \( H(U) = 3 \cdot 32 = 96 \) bits. Observing the output of the program reduces this uncertainty to
\[
\frac{1}{2^{96}} \sum_{i=1}^{3} |B_i| \log |B_i| \approx 94.42 ,
\]
which corresponds to an information leakage (a reduction in uncertainty) of \( 96 - 94.2 = 1.58 \) bits.
Existing quantitative approaches will return (an approximation of) this number as a result. Our approach additionally offers quantities that go beyond the number of bits that are leaked. We can, for example, answer questions about the
average number of guesses required to correctly determine the secret inputs after observing the output \((1.3204 \times 10^{28})\), the average number of guesses required to determine the weakest secrets \((1.3204 \times 10^{28})\), as the equivalence classes in our examples are almost of equal size), or simply the number of possible bid combinations that lead to a given output \((|B_1|, |B_2|, |B_3|)\). As we will show, all of these measures can be easily derived from the sizes \(|B_1|, |B_2|, |B_3|\) of the \(R\)-equivalence classes computed by our approach.
3. Preliminaries
In this section, we give the necessary definitions for dealing with programs and information-flow analysis.
3.1. Programs and computation
We model a program \(P\) as a transition system \((S, T, I, F)\) that consists of
- \(S\) : a set of program states,
- \(T\) : a finite set of program transitions such that each transition \(\tau \in T\) is associated with a binary transition relation \(\rho_\tau \subseteq S \times S\),
- \(I\) : a set of initial states, \(I \subseteq S\),
- \(F\) : a set of final states, \(F \subseteq S\).
Our exposition does not assume any further state structure; however, for the sake of concreteness we point out that usually a program state represents a valuation of program variables in scope, and a program transition corresponds to a program statement as written in a programming language.
A program computation \(\sigma\) is a sequence of program states \(s_1, \ldots, s_n\) that starts at an initial state, ends at a final state, and relates each pair of consecutive states by some program transition. Formally, we require that \(s_i \in I, s_n \in F\), and for each \(1 \leq i < n\) there exists a transition \(\tau \in T\) such that \((s_i, s_{i+1}) \in \rho_\tau\).
A program path \(\pi\) is a (non-empty) sequence of program transitions, i.e., \(\pi \in T^+\). We write \(\pi \cdot \tau\) to denote a path obtained by extending \(\pi\) using a transition \(\tau\). Given two transition relations \(\rho_1\) and \(\rho_2\), we define their relational composition \(\rho_1 \circ \rho_2\) as usual:
\[
\rho_1 \circ \rho_2 = \{ (s, s') \mid \exists s'' \in S : (s, s'') \in \rho_1 \land (s'', s') \in \rho_2 \}.
\]
Given a path \(\pi = \tau_1 \cdot \ldots \cdot \tau_n\), a path relation \(\rho_\pi\) consists of the relational composition of transition relations along the path, i.e.,
\[
\rho_\pi = \rho_{\tau_1} \circ \ldots \circ \rho_{\tau_n}.
\]
A program path \(\pi\) is feasible if the corresponding path relation is not empty, i.e., \(\rho_\pi \neq \emptyset\).
We assume that initial and final states are pairs consisting of low and high components, i.e., \(I = I_{hi} \times I_{lo}\) and \(F = F_{hi} \times F_{lo}\). We assume an observer that knows the program, i.e., the corresponding transition system, and can see the low components of the initial and final states of a given computation. That is, the observer cannot see the high components of the initial and final states, and it cannot see any intermediate states of the computation. The later condition explains why we assume the high/low structure only on the initial and final states.
3.2. Qualitative information flow
We use an equivalence relation \(R\) over \(I_{hi}\), i.e., \(R \subseteq I_{hi} \times I_{hi}\), to characterize the information that is leaked to an observed system. \(R\) represents the observer knowledge in terms of equivalence classes. After observing a program computation the observer only knows that the high component of the input state belongs to the set \([s_{hi}]_R\). If \(R\) is the identity relation, i.e.,
\[
\equiv_{hi} = \{ (s_{hi}, s_{hi}) \mid s_{hi} \in I_{hi}\},
\]
then the observer knows the values \(s_{hi}\), since the equivalence class \([s_{hi}]_{\equiv_{hi}}\) is a singleton set and hence uniquely determines \(s_{hi}\). In contrast, the largest equivalence relation \(All_{hi}\) that does not distinguish between any states, i.e., \(All_{hi} = I_{hi} \times I_{hi}\), captures that the observer knows nothing about \(I_{hi}\), since we have \([s_{hi}]_{All_{hi}} = I_{hi}\). An equivalence relation \(R\) such that \(\equiv_{hi} \subset R \subset All_{hi}\) represents a partial knowledge about the high component of the input.
The information that a program leaks partially depends on the low component of the initial states. We call such a low component of an initial state an experiment, and assume that it can be chosen by the attacker. Our goal is to characterize the secret information that a program leaks when it is run on a given set of experiments \(E \subseteq I_{lo}\). Given a program \(P\) and a set of experiments \(E\), there is an information leak with respect to an equivalence relation \(R\) if there is a pair of computations induced by paths \(\pi\) and \(\eta\) that start from initial states with \(R\)-equivalent high components and equal low components in \(E\), and lead to final states with different low components:
\[
\text{Leak}_P (R, E, \pi, \eta) \equiv
3s, t \in I \exists s', t' \in F : (s, s') \in \rho_\pi \land (t, t') \in \rho_\eta \land
s_{lo} = t_{lo} \land (s_{hi}, t_{hi}) \in R \land s_{hi} \in E \land s'_{lo} \neq t'_{lo}.
\]
The relation \(R\) over-approximates the maximal information that is leaked when the program \(P\) is run on the experiments \(E\), written as \(\text{Conf}_{leak_p} (R, E)\), if there is no witness of further leaks:
\[
\text{Conf}_{leak_p} (R, E) \equiv
\forall \pi, \eta \in T^+ : \neg \text{Leak}_P (R, E, \pi, \eta).
\]
The largest equivalence relation \(R\) with \(\text{Conf}_{leak_p} (R, E)\) is the most precise characterization of the leaked information information, denoted by \(\approx_E\).
\[
\approx_E \equiv \bigcup \{ R \mid \text{Conf}_{leak_p} (R, E) \}.
\]
Example 1. If a program \( P \) satisfies \( \text{Confin}e_p(\text{All}_{hi}, I_{hi}) \), a low observer does not learn any information about the high inputs even if he runs the program on all low inputs. This property is called non-interference.
The set of experiments \( E \) characterizes the set of low input values for which the information leakage of a program is characterized. Different instantiations of \( E \) correspond to different attack scenarios. In general, \( \approx_{E} \subseteq \approx_{E'} \) whenever \( E' \subseteq E \), i.e., more experiments allow for a more precise characterization of the secret and hence leak more information.
Example 2. Consider a password checker \( P \) that receives as high input a password and as low input a password candidate. The relation \( \approx_{\{x\}} \) captures the information that \( P \) leaks when it is run on the password candidate \( x \). The relation \( \approx_{\{hi\}} \) captures the information that \( P \) leaks in an exhaustive password search.
\( \text{Confin}e_p(R, E) \) does not capture information leaks exposed due to non-termination of \( P \). Sufficient preconditions for the termination of \( P \) can be automatically generated \[14\] and used to exclude non-terminating inputs. From now on, we will assume that \( P \) terminates on all initial states \( s \in I \).
3.3. Quantitative information flow
In the following, we use information theory to give quantitative characterizations of equivalence relations \( R \) with \( \text{Confin}e_p(R, E) \). These characterizations have the advantage of being compact and human-readable. Moreover, they yield concise interpretations, e.g., in terms of the expected guessing effort that is required to determine the secret given the available information.
We first illustrate in detail how \( R \) can be characterized using the guessing entropy as a measure. After this, we give examples of alternative information measures.
**Guessing entropy.** Let \( A \) be a finite set and \( p: A \to \mathbb{R} \) a probability distribution. For a random variable \( X: A \to X \), we define \( p_X: X \to \mathbb{R} \) as \( p_X(x) = \sum_{a \in X^{-1}(x)} p(a) \), which is often denoted by \( p(X = x) \) in the literature.
The guessing entropy of the random variable \( X \) is the average number of questions of the kind “does \( X = x \) hold” that must be asked to guess \( X \)’s value correctly \[28\]. If we assume \( p \) to be public, the optimal procedure is to try each of the possible values in order of their decreasing probabilities. Without loss of generality, let \( X \) be indexed such that \( p_X(x_i) \geq p_X(x_j) \), whenever \( i \leq j \). Then the guessing entropy \( G(X) \) of \( X \) is defined as
\[
G(X) = \sum_{1 \leq i \leq |X|} i \ p_X(x_i) .
\]
Given another random variable \( Y: A \to Y \), one denotes by \( G(X|Y = y) \) the guessing entropy of \( X \) given \( Y = y \), that is, with respect to the distribution \( p_{XY \mid Y=y} \). The conditional guessing entropy \( G(X|Y) \) is defined as the expected value of \( G(X|Y = y) \) over all \( y \in Y \), namely,
\[
G(X|Y) = \sum_{y \in Y} p_Y(y) G(X|Y = y) .
\]
This quantity represents the expected number of guesses needed to determine \( X \) when the value of \( Y \) is already known.
**Guessing entropy and programs.** We assume a given probability distribution \( p: I_{hi} \to \mathbb{R} \) and an equivalence relation \( R \subseteq I_{hi} \times I_{hi} \). We use two random variables to quantify the information that corresponds to \( R \). The first is the random variable \( U \) that models the choice of a secret in \( I_{hi} \) according to \( p \) (i.e., \( U = \text{id}_{I_{hi}} \)). The second is the random variable \( V_R \) that maps each secret to its \( R \)-equivalence class:
\[ V_R: I_{hi} \to I_{hi}/R, \quad V_R(s_{hi}) = [s_{hi}]_R. \]
Consider now a program \( P \) that satisfies \( \text{Confin}e_p(R, E) \). Then \( G(U) \) is the expected number of guesses that an attacker must perform to determine the secret input, prior to observing the output of \( P \). The value of \( G(U|V_R = [s_{hi}]_R) \) is the adversary’s remaining guessing effort after learning the \( R \)-equivalence class of \( s_{hi} \). Hence, \( G(U|V_R) \) is a lower bound on the expected number of guesses that an attacker must perform for recovering the secret input after having run \( P \) on all experiments from \( E \).
**Alternative information measures.** A number of alternative information measures, e.g., see \[7\], \[24\], \[37\], can be connected to programs along the same lines as the guessing entropy.
The minimal guessing entropy \[24\] \( \hat{G}(U|V_R) \) is defined as the expected guessing effort for the weakest secrets in \( I_{hi} \), i.e., the secrets that are easiest to guess after observing the output of \( P \). Formally, one defines
\[
\hat{G}(U|V_R) = \min \{ G(U|V_R = [s_{hi}]_R) \mid s_{hi} \in I_{hi} \} .
\]
The conditional Shannon entropy \( H(U|V_R) \) captures the attacker’s uncertainty about the secret input of the program in terms of bits, i.e., in terms of a lower bound on the shortest representation of the secret \[2\], \[36\]. Formally, one defines \( H(U|V_R) \) as the expected value of \( H(U|V_R = [s_{hi}]_R) \) over all \( s_{hi} \in I_{hi} \), where \( H(U|V_R = [s_{hi}]_R) \) is the Shannon entropy of \( U \) with respect to the distribution \( p_{U|V_R = [s_{hi}]} \).
The channel capacity
\[
C_R = \max \sum_{p} \left( H(U) - H(U|V_R) \right)
\]
is an upper bound on the rate at which information can be transmitted through the program by variation of its secret inputs \[2\], \[36\]. Here, \( p \) ranges over all probability distributions on \( I_{hi} \).
The conditional min-entropy \( H_{\text{min}}(U|V_R) \) captures the uncertainty about the secret input in terms of the probability
5
for guessing the secret in one try after observing the output of the program. There are different definitions for the conditional min-entropy in the literature; the one given in [37] is easily cast in terms of $U$ and $V_r$.
Which measure is appropriate depends on the given attack scenario. For example, the channel capacity is appropriate for assessing the damage of intentional communication, e.g., by a Trojan horse, while the minimal guessing entropy can be used to assess the impact of unintentional information release.
4. Leak discovery and quantification
In this section, we present our method, called DisQUANT (Discovery and Quantification), for the automatic discovery of leaked information and its comprehensive quantitative interpretation. DisQUANT takes as input a program $P$ and a set of experiments $E$. It produces the characterization of the leaking information in terms of the equivalence relation $\approx_E$ and performs its information-theoretic, quantitative interpretation.
DisQUANT consists of two procedures Disco and Quant that perform the qualitative and quantitative analysis, respectively. We proceed with a detailed description of each procedure below, before we provide a correctness statement for DisQUANT and discuss the scope of our method in Sections 4.3 and 4.4, respectively.
Our presentation does not rely on any particular way of representing programs and equivalence relations over program states. In Section 5, we exploit this generality to provide an implementation of DisQUANT using existing tools for program verification and information-theoretic analysis.
4.1. Discovery of information leaks
Given a program $P$ and a set of experiments $E$, our goal is to synthesize $\approx_E$, i.e., the largest equivalence relation $R$ such that $Confine_p(R, E)$ holds. The procedure Disco shown in Figure 1 computes this equivalence relation.
The computation is performed in an incremental fashion. Our procedure Disco stores the current candidate for the equivalence relation in the variable $R$. Initially, $R$ contains the coarsest equivalence relation, i.e., one that claims that no information is leaked, see line 1 in Figure 1.
During the execution of Disco, it is checked whether $R$ adequately represents the leaking information, see line 2. If $R$ is inadequate, which is witnessed by a pair of paths, say $\pi$ and $\eta$, then the candidate $R$ is refined. The refinement step eliminates the discovered inadequacy using the relation $\text{Refine}_E(\pi, \eta)$, see line 3. The refinement step guarantees that the information leak witnessed by the pair of paths $\pi$ and $\eta$ is captured by the refined relation, i.e., after executing line 3 the predicate $\text{Leak}_p(R, E, \pi, \eta)$ no longer holds.
The procedure Disco generates a symmetric and transitive relation. For nondeterministic programs $P$, this relation is not necessarily reflexive, because there can be two computations that start from the same initial state and produce different low outputs. We choose a conservative approach and assume that such non-reflexive inputs are leaked. This is achieved by adding the identity relation in Line 5, which yields an equivalence relation.
The search for leaks in Line 2 and the refinement step in Line 3 are complex tasks for which we can employ existing techniques.
Detecting leaks. Line 2 identifies pairs of paths that witness information leaks with respect to the current candidate equivalence relation $R$. We discover such paths automatically by analyzing pairs of program runs, e.g., see [5], [39]. An equivalence relation $R$ does not yet adequately capture the leaked information if and only if there is a pair of $R$-related initial high states from which this error state is reachable with low input from $E$. This reachability problem can be solved, for example, using software model checkers such as BLAST [21], SLAM [3], or SATAbs [11]. The witness paths $\pi$ and $\eta$ can be reconstructed by inspecting the counterexample produced by the model checker.
Refining equivalence. The refinement of the candidate relation $R$ is determined by the paths $\pi$ and $\eta$. This step partitions $R$ by adding new equivalence classes, see the relational intersection in line 3. To compute this refinement, we distinguish between all high input states that lead to different low-observable outputs along $(\pi, \eta)$. Formally, we use a relation $\text{Refine}_E(\pi, \eta)$ such that
\begin{verbatim}
procedure Disco(P, E)
input
P : program
E : set of experiments
vars
R : equivalence relation
output
$\approx_E$ : characterization of leaking information
begin
1. $R \Leftarrow I_h \times I_h$
2. while exists $\pi, \eta \in T^+ : \text{Leak}_p(R, E, \pi, \eta)$ do
3. $R \Leftarrow R \cap \text{Refine}_E(\pi, \eta)$
4. done
5. $R \Leftarrow R \cup \approx_{I_h}$
6. return $R$
end.
Figure 1. Procedure Disco for computing a logical representation of the leaked information during a set of experiments.
\end{verbatim}
Refine_\(\phi(\pi, \eta)\) \equiv \\
\{(s_0, t_0) \mid \forall s, t \in I \forall s', t' \in F : (s, s') \in \rho_\pi \land (t, t') \in \rho_\eta \land \\
s_{t_0} = t_0 \land s_{t_0} = t'_{s_0}\}
The relation \(\text{Refine}_E(\pi, \eta)\) can be obtained by applying existing quantifier elimination procedures, e.g., the Fourier-Motzkin algorithm for linear arithmetic.
Correctness of Disco. The procedure Disco in Figure 1 is a formalization of our counterexample-guided computation of leaking information, based on the building blocks presented above. The correctness of Disco is formalized in the following proposition.
Proposition 1. Let \(P\) be a program and let \(E\) by a set of experiments. If Disco terminates on input \((P, E)\) and returns \(R\), then
\[
R = \approx_E,
\]
that is, \(R\) is the largest equivalence relation such that \(\text{Refine}_R(P, E)\) holds.
Proof: \(\text{Confine}_R(P, E)\) follows directly from the termination condition of Disco. \(R\) is the largest relation with this property, as it is the conjunction of weakest preconditions for the equality of the low outputs. It remains to show that \(R\) is an equivalence relation, i.e., reflexive, symmetric and transitive. For symmetry, assume that there is a \((s, t) \in R\) such that \((t, s) \notin R\). Then there is a conjunct \(\text{Refine}_E(\pi, \eta)\) in \(R\) that is not satisfied by \((t, s)\), i.e., there is an experiment in which \(t\) and \(s\) lead to different low outputs along \((\pi, \eta)\). Then \(s\) and \(t\) also lead to different low outputs along \((\eta, \pi)\). As \(\text{Refine}_R(P, E)\) is satisfied, this contradicts the assumption \((s, t) \in R\). For transitivity, assume that there are \((s, t), (t, u) \in R\) such that \((s, u) \notin R\). Then there exists a pair of paths \((\pi, \eta)\) and \((s', u') \in F\) such that \((s, s') \in \rho_\pi\), \((u, u') \in \rho_\eta\), and \(s'_{t_0} \neq u'_{s_0}\). Choose \(t' \in F\) with \((t, t') \in \rho_\eta\). Such a \(t'\) exists because we assume that \(P\) terminates on all \(t \in I\). As \((s, t), (t, u) \in R\), we have \(s'_{t_0} = t'_{u_0}\) and \(t'_{s_0} = u'_{t_0}\), which contradicts the assumption \(s'_{t_0} \neq u'_{t_0}\). Reflexivity holds because the identity relation is added to \(R\) before it is returned.
4.2. Quantification of information leaks
For computing the information-theoretic characteristics presented in Section 3.2, the procedure \text{Quant} determines the number \(r\) and the sizes \(n_1, \ldots, n_r\) of the equivalence classes of an equivalence relation \(R\). See Figure 2 for its description. \text{Quant} proceeds by iteratively computing representative elements of the equivalence classes of the relation \(R\), identifying the corresponding equivalence classes and determining their sizes.
\[
\text{procedure} \quad \text{Quant}(R) \\
\text{input} \quad R : \text{equivalence relation} \\
\text{vars} \quad Q : \text{auxiliary set of high initial states} \\
\text{output} \quad \{n_1, \ldots, n_r\} : \text{sizes of the } R\text{-equivalence classes} \\
\text{begin} \quad \begin{array}{l}
1 \quad i := 1 \\
2 \quad Q := I_h \\
3 \quad \text{while } Q \neq \emptyset \text{ do} \\
4 \quad s_i := \text{select in } Q \\
5 \quad n_i := \text{Count}([s_i]_R) \\
6 \quad Q := Q \setminus [s_i]_R \\
7 \quad i := i + 1 \\
8 \quad \text{done} \\
9 \quad \text{return } \{n_1, \ldots, n_{i-1}\} \\
\text{end.}
\]
Our iteration manipulates a set of high initial states \(Q\), which is initialized to the full set in line 2. In the first iteration, we choose an arbitrary \(s_1 \in Q\) and determine the size of the \(R\)-equivalence class \([s_1]_R\) of \(s_1\). In the \(i\)-th iteration, we find \(s_i\) such that \([s_i]_R \neq [s_j]_R\) for all \(j < i\), see line 4. If such an \(s_i\) exists, we determine the size of \([s_i]_R\) in line 5 and proceed with the next iteration after excluding the equivalence class of \(s_i\) from \(Q\). Otherwise, we report the sizes of the equivalence classes.
Logical operations. Our procedure performs a number of logical operations on the set \(Q\). We assume that the set \(Q\) is given as a logical assertion over the high variables \(h\) and that the equivalence relation \(R\) is given by an assertion over \(h\) and their copies \(\overline{h}\). The while condition in line 3 is performed by a logical satisfiability check. Line 4 requires finding a satisfying assignment to the assertion \(Q(h)\). We determine the members of the equivalence class \([s_i]_R\) by the assertion \(R(h, \overline{h}) \land s_i = \overline{h}\) whose free variable \(h\) represents the high states related to \(s_i\). Line 6 amounts to logical conjunction and negation.
Counting elements. Our method requires an algorithm \text{Count} that, given a set \(A\), returns the number of elements in \(A\), i.e., \(\text{Count}(A) = |A|\). If \(A\) is represented as a formula \(\phi\), this number corresponds to the number of models for \(\phi\).
For example, if \(S\) is represented in linear arithmetic, this task can be solved as follows. Suppose \(\phi\) is in disjunctive normal form, i.e., \(\phi = \phi_1 \lor \phi_2 \lor \ldots \phi_n\), where the clauses \(\phi_i\) are conjunctions of linear inequalities. Then the number of satisfying assignments of each clause corresponds to the number of integer solutions of the corresponding system
of inequalities. We can apply Barvinok’s algorithm [6] for computing the number of integer points in convex polyhedra. The Lattice Point Enumeration Tool (LattE) [25] provides an implementation of this algorithm.
By summing over the number of solutions for every clause and removing possible duplicates, we obtain the number of models for \( \phi \).
**Correctness of QUANT**. The algorithm QUANT in Figure 2 is a formalization of the procedure sketched above. Its correctness is implied by the following proposition.
**Proposition 2**. Let \( R \) be an equivalence relation on \( I_{hi} \) with \( I_{hi}/R = \{B_1, \ldots, B_r\} \). If QUANT terminates on input \( R \), it returns the set \( \{|B_1|, \ldots, |B_r|\} \).
**Proof**: \( Q \) is a predicate representing a set of high initial states. It is initialized with \( I_{hi} \), which represents all possible high initial states. The assignment \( Q := Q \setminus \{s_i\}_R \) in removes \( \{s_i\}_R \) from this set. As the next representative element is chosen from this reduced state space, we have \( [s_i]_R \neq [s_j]_R \) for \( i \neq j \). The algorithm terminates if \( Q = \emptyset \), which implies that all equivalence classes have been found. If Count is correct, the assertion follows. \( \square \)
**Information-theoretic interpretation**. With a uniform probability distribution on \( I_{hi} \), the output of QUANT can be given various information-theoretic interpretations. We consider the attacker’s guessing effort for deducing the secret input to the program from the observable output (conditional and minimal guessing entropy), the attacker’s remaining uncertainty about the secret in terms of bits (Shannon entropy), and the maximal rate at which information can be transmitted using the program as a communication channel (channel capacity). A formula for the min-entropy in terms of \( |I_{hi}| \) and \( r \) can be found in [37].
**Proposition 3**. Let \( R \subseteq I_{hi} \times I_{hi} \) be an equivalence relation with \( I_{hi}/R = \{B_1, \ldots, B_r\} \), let \( n = |I_{hi}| \), and let \( \mathcal{U} \) and \( \mathcal{V}_R \) be defined as in Section 3.3. Then
1) \( G(\mathcal{U}|\mathcal{V}_R) = \frac{1}{2n} \sum_{i=1}^{r} |B_i|^2 + \frac{1}{2} \).
2) \( \dot{G}(\mathcal{U}|\mathcal{V}_R) = \min((|B_i| + 1)/2 \mid i \in \{i, \ldots, r\}) \).
3) \( H(\mathcal{U}|\mathcal{V}_R) = \frac{1}{2} \sum_{i=1}^{r} |B_i| \log_2 |B_i| \).
4) \( C_R = \log_2 r \), if \( P \) is deterministic.
**Proof**: Assertions 1 and 3 are due to [24]. For 2, a simple calculation shows that, on the average, \((k+1)/2\) attempts are needed for guessing one of \( k \) equally likely alternatives. For 4, observe that \( H(\mathcal{U}) = H(\mathcal{U}|\mathcal{V}_R) = H(\mathcal{V}_R) \). The last step follows because \( \mathcal{V}_R \) is determined by \( \mathcal{U} \). \( H(\mathcal{V}_R) \) reaches its maximum of \( \log r \) when \( \mathcal{V}_R \) is uniformly distributed. For deterministic programs \( P \), this uniform distribution can be achieved by a suitable choice of \( p_U \). \( \square \)
**4.3. Correctness of DisQUANT**
The following theorem states the correctness of DisQUANT.
**Theorem 1** (Correctness of DisQUANT). Let \( P \) be a program and \( E \) be a set of experiments. If DisQUANT\((P, E)\) terminates, then it outputs the sizes \( \{n_1, \ldots, n_r\} \) of the \( \approx_E \)-equivalence classes of \( I_{hi} \).
Theorem 1 implies that DisQUANT correctly determines the sizes of the \( \approx_E \)-equivalence classes. Together with Proposition 3, this gives rise to push-button technology for computing a variety of information-theoretic measures beyond those offered by existing approaches.
**4.4. Scope of our method**
We briefly discuss the scope of our method. In particular, we identify the languages for which Disco can be easily implemented, discuss the impact of nontermination, and present initial ideas for scaling-up.
**Soundness and language features**. In principle, Disco can be implemented for any programming language for which model-checkers are available, including those with arrays [22] and heap structures [8]. When implementing Disco using a model-checker that is sound but not complete, spurious leaks may be detected. In this case, the equivalence relation computed by Disco will be finer than \( \approx_E \), which corresponds to an over-approximation of the maximal information leakage, and can be used for certifying the security of a program.
Similarly, QUANT can in principle be implemented for any logical theory for which the number of models of an assertion can be counted, however, we are not aware of practical solutions for this task that go beyond Boolean propositional logic and Presburger Arithmetic.
In Section 5 we present an implementation of DisQUANT for a subset of C with expressions in linear arithmetic.
**(Non)termination of DisQUANT**. The algorithm Disco is initialized with the coarsest equivalence relation, which claims absence of leaks in the analyzed program. This equivalence relation is refined during the execution of Disco. A longer execution time of Disco corresponds to a finer equivalence relation, which corresponds to more information leakage. Disco can be interrupted at any time, and will return an equivalence relation that is coarser than \( \approx_E \), i.e., an under-approximation of the maximal information that the analyzed program can leak. If this under-approximation already violates a given security policy, the insecurity of the analyzed program is certified.
For QUANT, a longer execution time corresponds to a larger number of equivalence classes, which corresponds to more
information leakage. Quant can be interrupted at any time. In the worst-case, all equivalence classes that have not been determined at this point are singleton sets. Together with the sizes of the equivalence classes that have already been enumerated and the size of the set of secret inputs, this can be used for computing an over-approximation of the maximal information that is leaked. In this way, the output of an interrupted execution of Quant can be used for certifying the security of the analyzed program.
Scaling up. The computation of DisQuant relies on the enumeration of the leaks of a program. The number of leaks can be quadratic in the number of program paths. Hence, when applied in a vanilla fashion, our method works well on programs with few paths, e.g., programs without branching statements inside of loops. For programs with branching statements inside of loops, the number of leaks may be large. For example, in the electronic auction program given in Section 2, the number of paths is exponential in the number of bids \( n \), which does not scale.
A number of speed-up techniques, such as predicate abstraction [19] and widening [15], can be used to analyze multiple program paths in Line 2 of Disco. Applying such techniques will improve the efficiency of our method, however, these speed-up techniques may lead to incompleteness, i.e., their application may report spurious leaks. In this case, the equivalence relation computed by Disco will be finer than \( \approx_F \), which corresponds to an over-approximation of the maximal information leakage.
Our method applies self-composition, which doubles the program size. It is possible to avoid duplication of some parts of the program by making related statements share the same control-flow constructions, as proposed in [38].
5. Implementing DisQuant
In this section, we outline the implementation of a push-button tool for the quantitative information flow analysis of C programs, based on the algorithm DisQuant presented in this paper. We show how all of the building blocks on which DisQuant is based can be instantiated and combined. In Section 6, we report on experimental results obtained by using our tool to analyze a number of example programs.
5.1. Language
We use a subset of C as the programming language. In particular, we allow programs to contain all control flow statements and assignments to scalar variables. As the expression language, we use linear arithmetic, i.e. integer variables with addition and comparison operators. We use propositional logic with propositions in linear arithmetic to represent the equivalence relations \( R \) and the set \( E \).
As a convention, we assume that the high and low input states of a program (i.e. \( I_{hi} \) and \( I_{lo} \)) are stored in variables named \( h_1, \ldots, h_n \) and \( l_1, \ldots, l_m \), respectively. We sometimes use single input variables \( h \) and \( l \) to comprise all of the high and low input to a program, respectively, and we write \( P(h, l) \) to emphasize that variables \( h \) and \( l \) occur in \( P \).
5.2. Implementing Disco
The building blocks for Disco are methods for checking Confine, for computing Refine, and for detecting leaks. We show how all three can be implemented using the software model checker Armc and the Omega calculator, which is a tool for manipulating formulas in linear arithmetic with quantifiers.
Implementing Confine. We cast the check for Confine\(_p(R, E) \) as a reachability problem, which we solve using the model checker Armc. As a preprocessing step, we create a modified copy \( \tilde{P} \) of \( P \), where we replace every program variable \( x \) that occurs in \( P \) by a fresh variable \( \tilde{x} \). This ensures that \( P \) and \( \tilde{P} \) have disjoint variable sets. The existence of an \( R \)-leak corresponds to the reachability of the error state in the following program.
\[
\text{if } (l = 1 \land l \in E \land (h, \tilde{l}) \in R) \\
\quad \text{P}(h_1, l) \\
\quad \text{T}(\tilde{l}, \tilde{l}) \\
\quad \text{if } l \neq \tilde{l} \\
\quad \text{error} \\
\text{return}
\]
We apply Armc to this reachability problem. If error is reachable, Armc outputs a path to error. As the variable sets of both copies of \( P \) are disjoint, the leak \((\pi, \eta)\) can be reconstructed from this path. This directly leads to an implementation of Leak\(_p(E, R) \). As we will explain below, this direct computation of Leak\(_p(E, R) \) can be avoided due to extra information provided by Armc.
Implementing Refine. Armc not only returns the path to error, but also a formula in linear arithmetic that characterizes all initial states from which the error state is reachable along the counterexample path. This formula characterizes sets of pairs \((h, l), (\tilde{h}, \tilde{l})\) of initial states and can thus be interpreted as a binary relation \( \tilde{R} \) over \( I \). We project out the low variables from \( \tilde{R} \), i.e. we define \( \tilde{R}_E \subseteq I_{hi} \times I_{hi} \) as
\[
\begin{align*}
\tilde{R}_E &\equiv \{ (h, \tilde{h}) \mid \exists l \in E : (h, l), (\tilde{h}, l) \in \tilde{R} \}. \\
\end{align*}
\]
\( \tilde{R}_E \) characterizes all pairs of high inputs from which the error state can be reached with an experiment from \( E \). The complement of \( \tilde{R}_E \) characterizes all pairs of high initial states from which the error state is not reachable along \((\pi, \eta)\) with an experiment from \( E \), i.e., it corresponds to Refine\(_E(\pi, \eta)\):
\[
\text{Refine}_E(\pi, \eta) \equiv I_{hi} \times I_{hi} \setminus \tilde{R}_E.
\]
In our implementation, \( E \) is represented as an assertion in linear arithmetic, and we perform the projection and set difference using the Omega calculator.
### 5.3. Implementing Quant
The building blocks for the algorithm Quant presented in Section 4.1 are operations on sets and relations, such as finding models, determining equivalence classes, and counting the number of elements (the function Count). First, we show how to implement the relational operations using the Omega calculator. Subsequently, we show how to count the number of elements in a set using the Lattice Point Enumeration Tool (LattE).
#### Implementing the relational operations.
The example command of the Omega calculator implements the operation of picking an element from \( Q \), see line 4 in Figure 2. The computation of an equivalence class in line 5 can be implemented using relational composition:
\[
[s]_R \equiv \{ s \circ R = \{ t \in I_n | (s, t) \in R \} \}
\]
The loop body in Figure 2 (except for the call to Count in line 5) thus maps to the following input of the Omega calculator:
```plaintext
B:= S.R;
Q:= Q-B;
S:= example Q;
```
Here \( R \) and \( Q \) represent \( R \) and \( Q \), respectively. \( S \) corresponds to \( \{ s \} \), \( B \) corresponds to \( \{ s \}_R \), and "->" denotes the relational composition. The result of successively applying these operations to \( Q = I_n \) and the relation \( R \) given by Disco is the set
\[
I_n/R = \{ B_1, \ldots, B_n \}
\]
of \( R \)-equivalence classes, each represented as a linear arithmetic proposition in disjunctive normal form.
#### Implementing Count.
An \( R \)-equivalence class \( B \) is represented as a conjunction \( \phi \equiv c_1 \land \cdots \land c_m \) of atomic propositions \( c_i \equiv \sum_{j=1}^{n} a_{ij} h_j \leq b_i \), with \( i \in \{ 1, \ldots, m \} \) and can be interpreted as a system of linear inequalities
\[
A h \leq b ,
\]
where \( A = (a_{ij}) \), \( h = (h_1, \ldots, h_n) \), and \( b = (b_1, \ldots, b_m) \). It is not difficult to see that the number of satisfying assignments of \( \phi \) (i.e., the size of \( B \)) corresponds to the number of integer solutions to this system of inequalities. For counting the number of solutions of two disjuncts \( \phi = \phi_1 \lor \phi_2 \), we compute
\[
\text{Count}(\phi) \equiv \text{Count}(\phi_1) + \text{Count}(\phi_2) - \text{Count}(\phi_1 \land \phi_2).
\]
This easily generalizes to the DNF formulas output by the Omega calculator.
For efficiency reasons, Anemonic assumes that program variables range over rational numbers. As a consequence, the equivalence classes computed by the Omega calculator may be of unbounded size. In practice, however, the values of integers variables will be bounded by the range of their respective types. To incorporate such bounds, we extend \( A \) by additional constraints of the form
\[
I_n h \leq b_n \text{ and } -I_n h \leq b_l .
\]
Here, \( I_n \) denotes the identity matrix of dimension \( n \) and \( b_n \) and \( b_l \) are vectors of upper and lower bounds, respectively. We note that such a bounding step does not compromise the soundness of our approach, however it might sacrifice completeness, e.g., if the input leading to a leak lies outside of the bounds.
Applying LattE to the following system of inequalities
\[
\begin{pmatrix}
A \\
I_n \\
-I_n
\end{pmatrix}
\]
\[
\begin{pmatrix}
b_n \\
b_l
\end{pmatrix}
\]
yields the number of elements of the equivalence class \( B \) represented by \( \phi \). For all of our examples, the running time of LattE was largely independent of the bounds \( b_n \) and \( b_l \).
### 6. Experimental results
In this section, we report on experimental results obtained by applying our technique to determine the information that is revealed by a program. As examples, we analyze programs for checking passwords, debiting from an electronic purse, and computing sum queries.
#### 6.1. Password checker
Consider a password checker that receives a secret password \( h \) and a candidate password \( l \), and outputs whether the candidate password was correct, i.e. whether \( l = h \).
```plaintext
if (1==h)
l=1;
else
l=0;
```
A password check necessarily reveals partial information about the password. We use our approach to characterize this information for two different experiments. As shown in Section 5.2, the set of experiments \( E \) determines how the low variables are eliminated from the equivalence relation computed by Anemonic. In Section 5.2, this elimination is performed in each refinement step. For a uniform presentation of both experiments, we postpone this elimination until after the computation of the complete relation.
Then the relation \( R \) computed by Anemonic is
\[
R \equiv (\overline{h} = l \land l - h \leq -1) \lor (\overline{h} = l \land l - h \geq 1) \lor (h = l \land \overline{h} - l \leq -1) \lor (h = l \land l - \overline{h} \leq -1)
\]
We consider two experiments, where the first corresponds to a single password guess and the second corresponds to an exhaustive search of the password space.
**Single password guess.** The experiment \( E = \{x\} \) corresponds to the guess of a single password \( x \). The relation \( \approx_{\{x\}} \) captures the information that is leaked in this guess and is obtained from \( R \) as described in Section 5.2. For \( x = 0 \), the equivalence classes computed by \textsc{Quant} are
\[
\begin{align*}
B_1 & \equiv h = 0 \\
B_2 & \equiv h \leq -1 \lor h \geq 1 ,
\end{align*}
\]
which reflects that a correct guess reveals the password while all incorrect (nonzero, in this case) passwords cannot be distinguished. We obtain \(|B_1| = 1 \) and \(|B_2| = 4294967295\) if the passwords are nonnegative 32-bit integers. For uniformly distributed passwords, the attacker’s uncertainty about the password hence drops from 32 bits to
\[
\frac{1}{2^{32}} \sum_{i=1}^{2^{32}} |B_i| \log |B_i| = 31.999999992
\]
after a single guess.
**Exhaustive search.** The experiment \( E = I_{lo} \) corresponds to exhaustively running \( P \) on all password candidates. A representation \( \approx_E \) of the leaked information is obtained from \textsc{ArmC’s} output as described in Section 5.2. We obtain
\[
\approx_{I_{lo}} \equiv h = \bar{h} ,
\]
which is the identity relation on \( I_{lo} \).
This result confirms the fact that the attacker can determine every password by exhaustive search. His remaining uncertainty about the password will then be 0. Note that we derived this interpretation from the output of Disco (i.e., without applying \textsc{Quant}). \textsc{Quant} enumerates all \( \approx_{I_{lo}} \)-equivalence classes, which is infeasible for large password spaces. The overall running time of the analysis was less than 2 seconds.
### 6.2. Electronic purse
Consider a program that receives as input the balance \( h \) of a bank account and debits a fixed amount \( l \) from this account until the balance is insufficient for this transaction, i.e. until \( h < l \).
```pseudocode
lo=0;
while(h>=l){
h=h-1;
lo=lo+1;
}
```
Upon termination, the program outputs the number of times \( l \) has been successfully subtracted from \( h \) in the variable \( lo \). This number reveals partial information about the initial balance of the account. We use our approach to automatically quantify this information.
The number of loop iterations depends on the account balance \( h \). Without any restriction on the range of the input values, the number of program paths (and leaks) is infinite, and Disco will not terminate. To avoid this, we bound the maximal account balance by 20 (i.e. \( h < 20 \)). We consider a single experiment where \( l = 5 \). With these parameters, Disco computes the following equivalence relation on \( \{0, \ldots, 19\} \)
\[
\approx_{\{5\}} \equiv 10 \leq h \land h \leq 14 \land 10 \leq \bar{h} \land \bar{h} \leq 14
\land 5 \leq h \land h \leq 9 \land 5 \leq \bar{h} \land \bar{h} \leq 9
\land 0 \leq h \land h \leq 4 \land 0 \leq \bar{h} \land \bar{h} \leq 4
\land 15 \leq h \land h \leq 19 \land 15 \leq \bar{h} \land \bar{h} \leq 19 ,
\]
Given \( \approx_{\{5\}} \), \textsc{Quant} computes the equivalence classes
\[
\begin{align*}
B_1 & \equiv 0 \leq h \leq 4 \\
B_2 & \equiv 5 \leq h \leq 9 \\
B_3 & \equiv 10 \leq h \leq 14 \\
B_4 & \equiv 15 \leq h \leq 19 ,
\end{align*}
\]
from which we obtain \(|B_1| = |B_2| = |B_3| = |B_4| = 5\). This result confirms the intuition that our program leaks the result of integer division of \( h \) by \( l \).
For this example, the structure of the equivalence classes is simple and can be directly interpreted. We also give an information-theoretic interpretation in terms of guessing. If the value of \( h \) is chosen from a uniform distribution (modeled by a random variable \( U \)), the number of guesses to correctly determine the purse balance is \( G(U) = 10.5 \). Using Proposition 3, the expected number of guesses decreases to
\[
G(U|\approx_{\{5\}}) = \frac{1}{2 \cdot 20} \sum_{i=1}^{4} |B_i|^2 + \frac{1}{2} = 3
\]
by observing the low output of the program.
The overall running time for analyzing this example is dominated by the model checker’s running time of 24 seconds. The running times for computing the equivalence classes and determining their size are each below one second.
### 6.3. Sum query
Consider a program that receives as input \( n \) secret integers and computes and outputs their sum. We use our approach to characterize the information that is revealed by this program. This result corresponds to the information that a sum query reveals about a database record. For our example, we choose \( n = 3 \) and represent the input by variables \( h_1, h_2, h_3 \), i.e., we analyze the program
```
1=h1;
```
The equivalence relation synthesized by Disco is
\[ R \equiv \overline{h_3} = h_1 + h_2 + h_3 - \overline{h_1} - \overline{h_2} . \]
For determining the sizes and the number of the \( \approx \)-equivalence classes, we choose \( 0 \leq h_i < 10 \) for \( i \in \{1, 2, 3\} \).
**Quant** computes equivalence classes of the form
\[ B_i \equiv h_1 + h_2 + h_3 = i - 1 \]
for \( i \in \{1, \ldots, 28\} \) with respective sizes \( |B_1|, \ldots, |B_{28}| \) of\( 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, 63, 69, 73, 75, 75, 73, 69, 63, 55, 45, 36, 28, 21, 15, 10, 6, 3, 1 \).
For independently chosen and uniformly distributed input values (modeled by a random variable \( U \)) the expected number of guesses to correctly determine the input is
\[ G(U) = 500.5 . \]
The average number of guesses is reduced to
\[ G(U|V_\infty) = \frac{1}{2} \cdot 10^7 \sum_{i=1}^{28} |B_i|^2 + \frac{1}{2} = 28.126 \]
by observing the output of the analyzed program.
An analysis with the minimal guessing entropy shows
\[ \hat{G}(U|V_\infty) = 1 , \]
which additionally reveals that there are secrets that are very easy to guess, a fact that is not revealed by any average-case measure. This illustrates the benefit of combining multiple information measures in one analysis.
7. Conclusion
We presented the first automatic method for information-flow analysis that discovers what information is leaked and computes its comprehensive quantitative interpretation.
References
|
{"Source-Url": "http://software.imdea.org/%7Ebkoepf/papers/oakland09.pdf", "len_cl100k_base": 15916, "olmocr-version": "0.1.51", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 58460, "total-output-tokens": 20049, "length": "2e13", "weborganizer": {"__label__adult": 0.0004968643188476562, "__label__art_design": 0.0004377365112304687, "__label__crime_law": 0.0014123916625976562, "__label__education_jobs": 0.0010976791381835938, "__label__entertainment": 0.0001100301742553711, "__label__fashion_beauty": 0.0002117156982421875, "__label__finance_business": 0.00047206878662109375, "__label__food_dining": 0.0004780292510986328, "__label__games": 0.0014772415161132812, "__label__hardware": 0.0015401840209960938, "__label__health": 0.0009665489196777344, "__label__history": 0.0004162788391113281, "__label__home_hobbies": 0.0001684427261352539, "__label__industrial": 0.00080108642578125, "__label__literature": 0.0005431175231933594, "__label__politics": 0.0005612373352050781, "__label__religion": 0.000606536865234375, "__label__science_tech": 0.1829833984375, "__label__social_life": 0.00012183189392089844, "__label__software": 0.01230621337890625, "__label__software_dev": 0.79150390625, "__label__sports_fitness": 0.0003542900085449219, "__label__transportation": 0.0006651878356933594, "__label__travel": 0.00020456314086914065}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68780, 0.03122]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68780, 0.49641]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68780, 0.83526]], "google_gemma-3-12b-it_contains_pii": [[0, 4862, false], [4862, 10535, null], [10535, 16517, null], [16517, 22327, null], [22327, 28243, null], [28243, 33278, null], [33278, 38689, null], [38689, 44392, null], [44392, 50043, null], [50043, 55013, null], [55013, 59870, null], [59870, 64650, null], [64650, 68780, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4862, true], [4862, 10535, null], [10535, 16517, null], [16517, 22327, null], [22327, 28243, null], [28243, 33278, null], [33278, 38689, null], [38689, 44392, null], [44392, 50043, null], [50043, 55013, null], [55013, 59870, null], [59870, 64650, null], [64650, 68780, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68780, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68780, null]], "pdf_page_numbers": [[0, 4862, 1], [4862, 10535, 2], [10535, 16517, 3], [16517, 22327, 4], [22327, 28243, 5], [28243, 33278, 6], [33278, 38689, 7], [38689, 44392, 8], [44392, 50043, 9], [50043, 55013, 10], [55013, 59870, 11], [59870, 64650, 12], [64650, 68780, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68780, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-04
|
2024-12-04
|
1709a8e2474fb510df4044a2848245bd6f760693
|
[REMOVED]
|
{"Source-Url": "http://is.uni-paderborn.de/uploads/tx_sibibtex/Extending_DMM_Behavior_Specifications_for_Visual_Execution_and_Debugging.pdf", "len_cl100k_base": 9341, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 48234, "total-output-tokens": 11273, "length": "2e13", "weborganizer": {"__label__adult": 0.00031876564025878906, "__label__art_design": 0.00039839744567871094, "__label__crime_law": 0.0002363920211791992, "__label__education_jobs": 0.0005083084106445312, "__label__entertainment": 6.711483001708984e-05, "__label__fashion_beauty": 0.00012874603271484375, "__label__finance_business": 0.00012171268463134766, "__label__food_dining": 0.00027823448181152344, "__label__games": 0.0004787445068359375, "__label__hardware": 0.0004775524139404297, "__label__health": 0.00031185150146484375, "__label__history": 0.0001938343048095703, "__label__home_hobbies": 5.5909156799316406e-05, "__label__industrial": 0.0003032684326171875, "__label__literature": 0.0003211498260498047, "__label__politics": 0.00021207332611083984, "__label__religion": 0.0004367828369140625, "__label__science_tech": 0.0104522705078125, "__label__social_life": 6.99758529663086e-05, "__label__software": 0.005359649658203125, "__label__software_dev": 0.978515625, "__label__sports_fitness": 0.000255584716796875, "__label__transportation": 0.000370025634765625, "__label__travel": 0.000171661376953125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 50358, 0.01616]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 50358, 0.56471]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 50358, 0.92142]], "google_gemma-3-12b-it_contains_pii": [[0, 2422, false], [2422, 5629, null], [5629, 8758, null], [8758, 8878, null], [8878, 12285, null], [12285, 15151, null], [15151, 18501, null], [18501, 21707, null], [21707, 21900, null], [21900, 25280, null], [25280, 28387, null], [28387, 31661, null], [31661, 31768, null], [31768, 35070, null], [35070, 37261, null], [37261, 39319, null], [39319, 41292, null], [41292, 44339, null], [44339, 47171, null], [47171, 50358, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2422, true], [2422, 5629, null], [5629, 8758, null], [8758, 8878, null], [8878, 12285, null], [12285, 15151, null], [15151, 18501, null], [18501, 21707, null], [21707, 21900, null], [21900, 25280, null], [25280, 28387, null], [28387, 31661, null], [31661, 31768, null], [31768, 35070, null], [35070, 37261, null], [37261, 39319, null], [39319, 41292, null], [41292, 44339, null], [44339, 47171, null], [47171, 50358, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 50358, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 50358, null]], "pdf_page_numbers": [[0, 2422, 1], [2422, 5629, 2], [5629, 8758, 3], [8758, 8878, 4], [8878, 12285, 5], [12285, 15151, 6], [15151, 18501, 7], [18501, 21707, 8], [21707, 21900, 9], [21900, 25280, 10], [25280, 28387, 11], [28387, 31661, 12], [31661, 31768, 13], [31768, 35070, 14], [35070, 37261, 15], [37261, 39319, 16], [39319, 41292, 17], [41292, 44339, 18], [44339, 47171, 19], [47171, 50358, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 50358, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
ccf233ac5f08dc4986d617e9e40e865e091e327b
|
Reversible Effects as Inverse Arrows
Heunen, Chris; Kaarsgaard, Robin; Karvonen, Martti
Published in:
Electronic Notes in Theoretical Computer Science
DOI:
10.1016/j.entcs.2018.11.009
Publication date:
2018
Document Version
Publisher's PDF, also known as Version of record
Citation for published version (APA):
Reversible Effects as Inverse Arrows
Chris Heunen
School of Informatics
University of Edinburgh
United Kingdom
Robin Kaarsgaard
Datalogisk Institut
University of Copenhagen
Denmark
Martti Karvonen
School of Informatics
University of Edinburgh
United Kingdom
Abstract
Reversible computing models settings in which all processes can be reversed. Applications include low-power computing, quantum computing, and robotics. It is unclear how to represent side-effects in this setting, because conventional methods need not respect reversibility. We model reversible effects by adapting Hughes’ arrows to dagger arrows and inverse arrows. This captures several fundamental reversible effects, including serialization and mutable store computations. Whereas arrows are monoids in the category of profunctors, dagger arrows are involutive monoids in the category of profunctors, and inverse arrows satisfy certain additional properties. These semantics inform the design of functional reversible programs supporting side-effects.
Keywords: Reversible Effect; Arrow; Inverse Category; Involutive Monoid
1 Introduction
Reversible computing studies settings in which all processes can be reversed: programs can be run backwards as well as forwards. Its history goes back at least as far as 1961, when Landauer formulated his physical principle that logically irreversible manipulation of information costs work. This sparked the interest in developing
reversible models of computation as a means to making them more energy efficient. Reversible computing has since also found applications in high-performance computing [29], process calculi [8], probabilistic computing [32], quantum computing [31], and robotics [30].
There are various theoretical models of reversible computations. The most well-known ones are perhaps Bennett’s reversible Turing machines [4] and Toffoli’s reversible circuit model [33]. There are also various other models of reversible automata [26,24] and combinator calculi [1,19].
We are interested in models of reversibility suited to functional programming languages. Functional languages are interesting in a reversible setting for two reasons. First, they are easier to reason and prove properties about, which is a boon if we want to understand the logic behind reversible programming. Second, they are not stateful by definition, which eases reversing programs. It is fair to say that existing reversible functional programming languages [20,34] still lack various desirable constructs familiar from the irreversible setting.
Irreversible functional programming languages like Haskell naturally take semantics in categories. The objects interpret types, and the morphisms interpret functions. Functional languages are by definition not stateful, and their categorical semantics only models pure functions. However, sometimes it is useful to have non-functional side-effects, such as exceptions, input/output, or indeed even state. Irreversible functional languages can handle this elegantly using monads [25] or more generally arrows [17].
A word on terminology. We call a computation \( a : X \to Y \) reversible when it comes with a specified partner computation \( a^\dagger : Y \to X \) in the opposite direction. This implies nothing about possible side-effects. Saying that a computation is partially invertible is stronger, and requires \( a \circ a^\dagger \circ a = a \). Saying that it is invertible is even stronger, and requires \( a \circ a^\dagger \) and \( a^\dagger \circ a \) to be identities. We call this partner of a reversible computation its dagger. In other words, reversible computing for us concerns dagger arrows on dagger categories, and is modeled using involutions [15]. In an unfortunate clash of terminology, categories of partially invertible maps are called inverse categories [6], and categories of invertible maps are called groupoids [10]. Thus, inverse arrows on inverse categories concern partially invertible maps.
We develop dagger arrows and inverse arrows, which are useful in two ways:
- We illustrate the reach of these notions by exhibiting many fundamental reversible computational side-effects that are captured (in Section 3), including: pure reversible functions, information effects, reversible state, serialization, vector transformations dagger Frobenius monads [14,15], recursion [21], and superoperators. Because there is not enough space for much detail, we treat each example informally from the perspective of programming languages, but formally from the perspective of category theory.
- We prove that these notions behave well mathematically (in Section 4): whereas arrows are monoids in a category of profunctors [18], dagger arrows and inverse arrows are involutive monoids.
This paper aims to inform design principles of sound reversible programming languages. The main contribution is to match desirable programming concepts to precise category theoretic constructions. As such, it is written from a theoretical perspective. To make examples more concrete for readers with a more practical background, we adopt the syntax of a typed first-order reversible functional programming language with type classes. We begin with preliminaries on reversible base categories (in Section 2).
2 Dagger categories and inverse categories
This section introduces the categories we work with to model pure computations: dagger categories and inverse categories. Each has a clear notion of reversing morphisms. Regard morphisms in these base categories as pure, ineffectful maps.
Definition 2.1 A dagger category is a category equipped with a dagger \( \dagger : C \to C \) satisfying \( f^{\dagger \dagger} = f \) for morphisms \( f \) and \( X^\dagger = X \) for objects \( X \). A morphism \( f \) in a dagger category is:
- positive if \( f = g \dagger \circ g \) for some morphism \( g \);
- a partial isometry if \( f = f \circ f^{\dagger} \circ f \);
- unitary if \( f \circ f^{\dagger} = \text{id} \) and \( f^{\dagger} \circ f = \text{id} \).
A dagger functor is a functor between dagger categories that preserves the dagger, i.e. a functor \( F \) with \( F(f^\dagger) = F(f)^\dagger \). A (symmetric) monoidal dagger category is a monoidal category equipped with a dagger making the coherence isomorphisms
\[
\alpha_{X,Y,Z} : X \otimes (Y \otimes Z) \to (X \otimes Y) \otimes Z \quad \rho_X : X \otimes I \to X
\]
\[
\lambda_X : I \otimes X \to X \quad (\text{and } \sigma_{X,Y} : X \otimes Y \to Y \otimes X \text{ in the symmetric case})
\]
unitary and satisfying \((f \otimes g)^\dagger = f^\dagger \otimes g^\dagger\) for morphisms \( f \) and \( g \). We will sometimes suppress coherence isomorphisms for readability.
Any groupoid is a dagger category under \( f^\dagger = f^{-1} \). Another example of a dagger category is \( \text{Rel} \), whose objects are sets, and whose morphisms \( X \to Y \) are relations \( R \subseteq X \times Y \), with composition \( S \circ R = \{ (x, z) \mid \exists y \in Y : (x, y) \in R, (y, z) \in S \} \). The dagger is \( R^\dagger = \{ (y, x) \mid (x, y) \in R \} \). It is a monoidal dagger category under either Cartesian product or disjoint union.
Definition 2.2 A (monoidal) inverse category is a (monoidal) dagger category of partial isometries where positive maps commute: \( f \circ f^{\dagger} \circ f = f \) and \( f^{\dagger} \circ f \circ g^{\dagger} \circ g = g^{\dagger} \circ g \circ f^{\dagger} \circ f \) for all maps \( f : X \to Y \) and \( g : X \to Z \).
Every groupoid is an inverse category. Another example of an inverse category is \( \text{PInj} \), whose objects are sets, and morphisms \( X \to Y \) are partial injections: \( R \subseteq X \times Y \) such that for each \( x \in X \) there exists at most one \( y \in Y \) with \( (x, y) \in R \), and for each \( y \in Y \) there exists at most one \( x \in X \) with \( (x, y) \in R \). It is a monoidal inverse category under either Cartesian product or disjoint union.
Definition 2.3 A dagger category is said to have inverse products [11] if it is a symmetric monoidal dagger category with a natural transformation \( \Delta_X : X \to X \otimes X \) making the following diagrams commute:
\[
\begin{align*}
X & \xrightarrow{\Delta_X} X \otimes X & X & \xrightarrow{\Delta_X} X \otimes X \\
\sigma_{X,X} & \downarrow & \Delta_X & \downarrow \Delta_X \otimes \text{id} \\
X \otimes X & \xrightarrow{id \otimes \Delta_X} X \otimes (X \otimes X) & (X \otimes X) \otimes X & \xrightarrow{\alpha} (X \otimes X) \otimes X
\end{align*}
\]
These diagrams express cocommutativity, coassociativity, speciality and the Frobenius law.
Another useful monoidal product, here on inverse categories, is a disjointness tensor, defined in the following way (see [11]):
Definition 2.4 An inverse category is said to have a disjointness tensor if it is equipped with a symmetric monoidal tensor product \(- \oplus -\) such that its unit \(0\) is a zero object, and the canonical quasi-injections
\[
\begin{align*}
\Pi_1 = X \xrightarrow{\rho^1_X} X \oplus 0 & \xrightarrow{\sigma_{0,Y}^1} X \oplus Y \\
\Pi_2 = Y \xrightarrow{\lambda^{-1}_Y} 0 \oplus Y & \xrightarrow{0_0,0 \oplus 0} X \oplus Y
\end{align*}
\]
are jointly epic.
For example, \(\text{PInj}\) has inverse products \(\Delta_X : X \to X \otimes X\) with \(x \mapsto (x, x)\), and a disjointness tensor where \(X \oplus Y\) is given by the tagged disjoint union of \(X\) and \(Y\) (the unit of which is \(\emptyset\)).
Inverse categories can also be seen as certain instances of restriction categories. Informally, a restriction category models partially defined morphisms, by assigning to each \(f : A \to B\) a morphism \(\bar{f} : A \to A\) that is the identity on the domain of definition of \(f\) and undefined otherwise. For more details, see [6].
Definition 2.5 A restriction category is a category equipped with an operation that assigns to each \(f : A \to B\) a morphism \(\bar{f} : A \to A\) such that:
- \(f \circ \bar{f} = f\) for every \(f\);
- \(\bar{f} \circ \bar{g} = \bar{g} \circ \bar{f}\) whenever \(\text{dom } f = \text{dom } g\);
- \(g \circ \bar{f} = \bar{g} \circ \bar{f}\) whenever \(\text{dom } f = \text{dom } g\);
\[ \bar{g} \circ f = f \circ g \circ \bar{f} \] whenever \( \text{dom } g = \text{cod } f \).
A \textit{restriction functor} is a functor \( F \) between restriction categories with \( F(\bar{f}) = \bar{F}(f) \). A \textit{monoidal restriction category} is a restriction category with a monoidal structure for which \( \otimes : C \times C \to C \) is a restriction functor.
A morphism \( f \) in a restriction category is a \textit{partial isomorphism} if there is a morphism \( g \) such that \( g \circ f = \bar{f} \) and \( f \circ g = \bar{g} \). Given a restriction category \( C \), define \( \text{Inv}(C) \) to be the wide subcategory of \( C \) having all partial isomorphisms of \( C \) as its morphisms.
An example of a monoidal restriction category is \( \text{PFN} \), whose objects are sets, and whose morphisms \( X \to Y \) are partial functions: \( R \subseteq X \times Y \) such that for each \( x \in X \) there is at most one \( y \in Y \) with \( (x, y) \in R \). The restriction \( \bar{R} \) is given by \( \{(x, x) | \exists y \in Y : (x, y) \in R \} \).
\textbf{Remark 2.6} Inverse categories could equivalently be defined as either categories in which every morphism \( f \) satisfies \( f = f \circ g \circ f \) and \( g = g \circ f \circ g \) for a unique morphism \( g \), or as restriction categories in which all morphisms are partial isomorphisms [6, Theorem 2.20]. It follows that functors between inverse categories automatically preserve daggers and that \( \text{Inv}(C) \) is an inverse category.
It follows, in turn, that an inverse category with inverse products is a monoidal inverse category: because \( X \otimes - \) and \( - \otimes Y \) are endofunctors on an inverse category, they preserve daggers, so that by bifunctoriality \( - \otimes - \) does as well:
\[
(f \otimes g)^\dagger = ((f \otimes \text{id}_Y) \circ (\text{id}_X \otimes g))^\dagger = (\text{id}_X \otimes g)^\dagger \circ (f \otimes \text{id}_Y)^\dagger = (\text{id}_X \otimes g^\dagger) \circ (f^\dagger \otimes \text{id}_Y) = f^\dagger \otimes g^\dagger.
\]
3 Arrows as an interface for reversible effects
Arrows are a standard way to encapsulate computational side-effects in a functional (irreversible) programming language [16,17]. This section extends the definition to reversible settings, namely to dagger arrows and inverse arrows. We argue that these notions are “right”, by exhibiting a large list of fundamental reversible side-effects that they model. We start by recalling irreversible arrows.
\textbf{Definition 3.1} An \textit{arrow} on a symmetric monoidal category \( C \) is a functor \( A : C^{\text{op}} \times C \to \text{Set} \) with operations
\[
\begin{align*}
\text{arr} : (X \to Y) &\to A \times Y \\
(\text{>>>}) : A \times Y &\to A \times Z \\
\text{first}_{X,Y,Z} : A \times Y &\to A \times (X \otimes Z) \ (Y \otimes Z)
\end{align*}
\]
that satisfy the following laws:
\[(a \ggg b) \ggg c = a \ggg (b \ggg c)\]
\[\text{arr}(g \circ f) = \text{arr } f \ggg \text{arr } g\]
\[\text{arr id} \ggg a = a \ggg \text{arr id}\]
\[\text{first}_{X,Y,I} a \ggg \text{arr } \rho_Y = \text{arr } \rho_X \ggg a\]
\[\text{first}_{X,Y,\otimes V} a \ggg \text{arr } \alpha_{Y,Z,V} = \text{arr } \alpha_{X,Z,V} \ggg \text{first}(\text{first } a)\]
\[\text{first}(\text{arr } f) = \text{arr } (f \otimes \text{id})\]
\[\text{first}(a \ggg b) = (\text{first } a) \ggg (\text{first } b)\]
where we use the functional programming convention to write \(A \times Y\) for \(A(X,Y)\) and \(X \to Y\) for \(\text{hom}(X,Y)\) The multiplicative fragment consists of above data except first, satisfying all laws except those mentioning first; we call this a weak arrow.
Define \(\text{second}(a)\) by \(\text{arr}(\sigma) \ggg \text{first }(a) \ggg \text{arr}(\sigma)\), using the symmetry, so analogs of \((4)-(8)\) are satisfied. Arrows makes sense for (nonsymmetric) monoidal categories if we add this operation and these laws.
**Definition 3.2** A dagger arrow is an arrow on a monoidal dagger category with an additional operation \(\text{inv}: A \times Y \to A Y X\) satisfying the following laws:
\[\text{inv}(\text{inv } a) = a\]
\[\text{inv } a \ggg \text{inv } b = \text{inv } (b \ggg a)\]
\[\text{arr } (f^\dagger) = \text{inv } (\text{arr } f)\]
\[\text{inv } (\text{first } a) = \text{first } (\text{inv } a)\]
A inverse arrow is a dagger arrow on a monoidal inverse category such that:
\[(a \ggg \text{inv } a) \ggg a = a\]
\[(a \ggg \text{inv } a) \ggg (b \ggg \text{inv } b) = (b \ggg \text{inv } b) \ggg (a \ggg \text{inv } a)\]
The multiplicative fragment consists of above data except first, satisfying all laws except those mentioning first.
**Remark 3.3** There is some redundancy in the definition of an inverse arrow: \((13)\) and \((14)\) imply \((11)\) and \((12)\); and \((11)\) implies \(\text{inv } (\text{arr id}) = \text{arr id}\).
Like the arrow laws \((1)-(8)\), in a programming language with inverse arrows, the burden is on the programmer to guarantee \((9)-(14)\) for their implementation. If that is done, the language guarantees arrow inversion.
**Remark 3.4** Now follows a long list of examples of inverse arrows, described in a typed first-order reversible functional pseudocode with type classes, inspired by Theseus [20,19], the revised version of Rfun (briefly described in [22]), and Haskell.
Type classes are a form of interface polymorphism: A type class is defined by a class specification containing the signatures of functions that a given type must implement in order to be a member of that type class (often, type class membership also informally requires the programmer to ensure that certain equations are required of their implementations). For example, the \textit{Functor} type class (in Haskell) is given by the class specification
\begin{verbatim}
class Functor f where
fmap : (a -> b) -> f a -> f b
\end{verbatim}
with the additional informal requirements that $fmap \ id = \ id$ and $fmap \ (g \circ f) = (fmap \ g) \circ (fmap \ f)$ must be satisfied for all instances. For example, lists in Haskell satisfy these equations when defining \textit{fmap} as the usual \textit{map} function, \textit{i.e.}:
\begin{verbatim}
instance Functor List where
fmap : (a -> b) -> List a -> List b
fmap f [] = []
fmap f (x::xs) = (f x)::(fmap f xs)
\end{verbatim}
While higher-order reversible functional programming is fraught, aspects of this can be mimicked by means of parametrized functions. A parametrized function is a function that takes parts of its input statically (\textit{i.e.}, no later than at compile time), in turn lifting the first-order requirement on these inputs. To separate static and dynamic inputs from one another, two distinct function types are used: $a \rightarrow b$ denotes that $a$ must be given statically, and $a \leftrightarrow b$ (where $a$ and $b$ are first-order types) denotes that $a$ is passed dynamically. As the notation suggests, functions of type $a \leftrightarrow b$ are reversible. For example, a parametrized variant of the reversible map function can be defined as a function \textit{map} : $(a \leftrightarrow b) \rightarrow ([a] \leftrightarrow [b])$. Thus, \textit{map} itself is not a reversible function, but given statically any reversible function $f : a \leftrightarrow b$, the parametrized \textit{map} $f : ([a] \leftrightarrow [b])$ is.
Given this distinction between static and dynamic inputs, the signature of arr becomes $(X \leftrightarrow Y) \rightarrow A X Y$. We will see later that Arrows on $C$ can be modelled categorically as monoids in the functor category $[C^{op} \times C, Set]$ [18]. Definition 3.1 uses the original signature, because this distinction is not present in the irreversible case. Fortunately, the semantics of arrows remain the same whether or not this distinction is made.
**Example 3.5 (Pure functions)** A trivial example of an arrow is the identity arrow $\hom(-, +)$ which adds no computational side-effects at all. This arrow is not as boring as it may look at first. If the identity arrow is an inverse arrow, then the programming language in question is both \textit{invertible} and \textit{closed under program inversion}: any program $p$ has a semantic inverse $\llbracket p \rrbracket^\dagger$ (satisfying certain equations), and the semantic inverse coincides with the semantics $\llbracket inv(p) \rrbracket$ of another program $inv(p)$. As such, $inv$ must be a sound and complete \textit{program inverter} (see also [23]) on pure functions; not a trivial matter at all.
Example 3.6 (Information effects) James and Sabry’s information effects [19] explicitly expose creation and erasure of information as effects. This type-and-effect system captures irreversible computation inside a pure reversible setting.
We describe the languages from [19] categorically, as there is no space for syntactic details. Start with the free dagger category \((C, \times, 1)\) with finite products (and hence coproducts), where products distribute over coproducts by a unitary map. Objects interpret types of the reversible language \(\Pi\) of bijections, and morphisms interpret terms. The category \(C\) is a monoidal inverse category.
The category \(C\) carries an arrow, where \(A(X, Y)\) is the disjoint union of \(\text{hom}(X \times H, Y \times G)\) where \(G\) and \(H\) range over all objects, and morphisms \(X \times H \to Y \times G\) and \(X \times H' \to Y \times G'\) are identified when they are equal up to coherence isomorphisms. This is an inverse arrow, where \(\text{inv}(a)\) is simply \(a^\dagger\). It supports the following additional operations:
\[
\text{erase} = \left[ \pi_H : X \times H \to H \right]_\simeq \in A(X, 1),
\]
\[
\text{create}_X = \left[ \pi_H^\dagger : H \to X \times H \right]_\simeq \in A(1, X).
\]
James and Sabry show how a simply-typed first order functional irreversible language translates into a reversible one by using this inverse arrow to build implicit communication with a global heap \(H\) and garbage dump \(G\).
Example 3.7 (Reversible state) Perhaps the prototypical example of an effect is computation with a mutable store of type \(S\). In the irreversible case, such computations are performed using the state monad \(\text{State } S X = S \triangleright \left( X \otimes S \right)\), where \(S \triangleright \left( X \otimes S \right)\) is the right adjoint to \(\left( X \otimes S \right)\), and can be thought of as a function type. Morphisms in the corresponding Kleisli category are morphisms of the form \(X \to S \triangleright \left( Y \otimes S \right)\) in the ambient monoidal closed category. In this formulation, the current state is fetched by \(\text{get} : \text{State } S\) defined as \(\text{get } s = (s, s)\), while the state is (destructively) updated by \(\text{put} : S \to \text{State } S\) defined as \(\text{put } x s = ((), x)\).
Such arrows can not be used as-is in inverse categories, however, as canonical examples (such as \(\text{PInj}\)) fail to be monoidal closed. To get around this, note that it follows from monoidal closure that \(\text{hom}(X, S \triangleright \left( Y \otimes S \right)) \simeq \text{hom}(X \otimes S, Y \otimes S)\), so that \(\text{hom}(\left( - \otimes S, - \otimes S \right))\) is an equivalent arrow that does not depend on closure. With this in mind, we define the reversible state arrow with a store of type \(S\):
\[
\text{type } RState\ S\ X\ Y = X \otimes S \leftrightarrow Y \otimes S
\]
\[
\text{instance } Arrow \ (RState\ S) \ where
\]
\[
\text{arr } f \ (x, s) = (f x, s)
\]
\[
(a \gg b) \ (x, s) = b \ (a \ (x, s))
\]
\[
\text{first } a \ ((x, z), s) = \text{let } (x', s') = a \ (x, s) \ \text{in } ((x', z), s')
\]
\[
\text{instance } InverseArrow \ (RState\ S) \ where
\]
\[
\text{inv } a \ (y, s) = a^\dagger \ (y, s)
\]
This satisfies the inverse arrow laws. To access the state, we use reversible duplication of values (categorically, this requires the monoidal product to have a natural
diagonal \( \Delta_X : X \to X \otimes X \), as inverse products do). Syntactically, this corresponds to the following arrow:
\[
\text{get} : RState S X (X \otimes S) \\xrightarrow{\quad} \quad (x, s) = ((x, s), s)
\]
The inverse to this arrow is \( \text{assert} : RState S (X \otimes S) X \), which asserts that the current state is precisely what is given in its second input component; if this fails, the result is undefined. For changing the state, while we cannot destructively update it reversibly, we can reversibly update it by a given reversible function with signature \( S \leftrightarrow S \). This gives:
\[
\text{update} : (S \leftrightarrow S) \to RState S X X \\
\text{update } f (x, s) = (x, f s)
\]
This is analogous to how variable assignment works in the reversible programming language Janus [35]: Since destructive updating is not permitted, state is updated by means of built-in reversible update operators, e.g., updating a variable by adding a constant or the contents of another variable to it, etc.
**Example 3.8 (Computation in context)** Related to computation with a mutable store is computation with an immutable one; that is, computation within a larger context that remains invariant across execution. In an irreversible setting, this job is typically handled by the reader monad (with context of type \( C \)), defined as \( \text{Reader } C X = C \Rightarrow X \). This approach is fundamentally irreversible, however, as the context is “forgotten” whenever a value is computed by supplying it with a context. Even further, it relies on the reversibly problematic notion of monoidal closure.
A reversible version of this idea is one that remembers the context, giving us the reversible Reader arrow:
\[
\text{type } \text{Reader } C X Y = X \otimes C \leftrightarrow Y \otimes C
\]
This is precisely the same as the state arrow – indeed, the instance declarations for \( \text{arr}, (\gg \gg \gg), \text{first}, \) and \( \text{inv} \) are the same – save for the fact that we additionally require all Reader arrows \( r \) to satisfy \( c = c' \) whenever \( r (x, c) = (y, c') \). We notice that \( \text{arr } f \) satisfies this property for all \( f \), whereas \( (\gg \gg \gg), \text{first}, \) and \( \text{inv} \) all preserve it. This resembles the “slice” construction on inverse categories with inverse products; see [11, Sec. 4.4].
As such, while we can provide access to the context via a function defined exactly as \( \text{get} \) for the reversible state arrow, we cannot provide an update function without (potentially) breaking this property – as intended. In practice, the property that the context is invariant across execution can be aided by appropriate interface hiding, i.e. exposing the Reader type and appropriate instance declarations and helpers (such as \( \text{get} \) and \( \text{assert} \)) but leaving the constructor for Reader arrows hidden.
Example 3.9 (Rewriter) A particularly useful special case of the reversible state arrow is when the store $S$ forms a group. While group multiplication if seen as a function $G \otimes G \leftrightarrow G$ is invertible only in degenerate cases, we can use parametrization to fix the first argument of the multiplication, giving it a much more reasonable signature of $G \rightarrow (G \leftrightarrow G)$. In this way, groups can be expressed as instances of the type class
```haskell
class Group G where
gunit : G
gmul : G \rightarrow (G \leftrightarrow G)
ginv : G \leftrightarrow G
```
subject to the usual group axioms. This gives us an arrow of the form
```haskell
type Rewriter G X Y = X \otimes G \leftrightarrow Y \otimes G
```
with instance declarations identical to that of $RState G$, save that we require $G$ to be an instance of the $Group$ type class. With this, adding or removing elements from state of type $G$ can then be performed by
```haskell
rewrite : G \rightarrow Rewriter G X X
rewrite a (x, b) = (x, gmul a b)
```
which “rewrites” the state by the value $a$ of type $G$. Note that while the name of this arrow was chosen to be evocative of the $Writer$ monad known from irreversible functional programming, as it may be used for similar practical purposes, its construction is substantially different (i.e., irreversible $Writer$ arrows are maps of the form $X \rightarrow Y \times M$ where $M$ is a monoid).
Example 3.10 (Vector transformation) Vector transformations, that is, functions on lists that preserve the length of the list, form another example of inverse arrows. The $Vector$ arrow is defined as follows:
```haskell
type Vector X Y = [X] \leftrightarrow [Y]
```
```haskell
instance Arrow (Vector) where
arr f xs = map f xs
(a >>> b) xs = b (a xs)
first a ps = let (xs, zs) = zip\uparrow ps in zip (a xs, zs)
```
```haskell
instance InverseArrow (Vector) where
inv a ys = a\downarrow ys
```
The definition of $first$ relies on the usual $map$ and $zip$ functions, which are defined as follows:
map : (a \leftrightarrow b) \rightarrow ([a] \leftrightarrow [b])
map f [] = []
map f (x::xs) = (f x)::(map f xs)
zip : ([a], [b]) \leftrightarrow [(a, b)]
zip ([], []) = []
zip (x::xs, y::ys) = (x, y)::(zip (xs, ys))
Notice that preservation of length is required for first to work: if the arrow \( a \) does not preserve the length of \( xs \), then \( zip (a \times s, zs) \) is undefined. However, since \( arr \) lifts a pure function \( f \) to a map (which preserves length), and \( (\ggg) \) and \( inv \) are given by the usual composition and inversion, the interface maintains this property.
Example 3.11 (Reversible error handling) An inverse weak arrow comes from reversible computation with a possibility for failure. The weak Error arrow is defined using disjointness tensors as follows:
\[
\text{type} \quad \text{Error} \quad E \quad X \quad Y = X \oplus E \leftrightarrow Y \oplus E
\]
\[
\text{instance} \quad \text{WeakArrow} (\text{Error} \quad E) \quad \text{where}
\quad \text{arr} \quad f \quad (\text{InL} \quad x) = \text{InL} \quad (f \quad x)
\quad \text{arr} \quad f \quad (\text{InR} \quad e) = \text{InR} \quad e
\quad (a \ggg b) \quad x = b \quad (a \quad x)
\]
\[
\text{instance} \quad \text{InverseWeakArrow} (\text{Error} \quad E) \quad \text{where}
\quad \text{inv} \quad a \quad y = a^\dagger \quad y
\]
In this definition, we think of the type \( E \) as the type of errors that could occur during computation. As such, a pure function \( f \) lifts to a weak arrow which always succeeds with value \( f(x) \) when given a nonerroneous input of \( x \), and always propagates errors that may have occurred previously.
Raising an error reversibly requires more work than in the irreversible case, as the effectful program that produces an error must be able to recover from it in the converse direction. In this way, a reversible \( raise \) requires two pieces of data: a function of type \( X \leftrightarrow E \) that transforms problematic inputs into appropriate errors; and a choice function of type \( E \leftrightarrow E \oplus E \) that decides if the error came from this site, injecting it to the left if it did, and to the right if it did not. The latter choice function is critical, as in the converse direction it decides whether the error should be handled immediately or later. Thus we define \( raise \) as follows:
\[
\text{raise} \quad : \quad (X \leftrightarrow E) \rightarrow (E \leftrightarrow E \oplus E) \rightarrow \text{Error} \quad E \quad X \quad Y
\quad \text{raise} \quad f \quad p \quad x = \text{InR} \quad (p^\dagger \quad (\text{arr} \quad f \quad x)))
\]
The converse of \( raise \) is \( handle \), an (unconditional) error handler that maps matching errors back to successful output values. Since unconditional error handling is seldom required, this can be combined with control flow (see Example 3.15) to perform conditional error handling, i.e. to only handle errors if they occur.
Example 3.12 (Serialization) When restricting our attention, as we do here, to only first-order reversible functional programming languages, another example of
inverse arrows arises in the form of serializers. A serializer is a function that transforms an internal data representation into one more suitable for storage, or for transmission to other running processes. To transform serialized data back into an internal representation, a suitable deserializer is used.
When restricting ourselves to the first-order case, it seems reasonable to assume that all types are serializable, as we thus avoid the problematic case of how to serialize data of function type. As such, assuming that all types $X$ admit a function $\text{serialize} : X \leftrightarrow \text{Serialized} X$ (where $\text{Serialized} X$ is the type of serializations of data of type $X$), we define the $\text{Serializer}$ arrow as follows:
\[
\text{type Serializer } X Y = X \leftrightarrow \text{Serialized } Y
\]
\[
\text{instance Arrow (Serializer) where}
\]
\[
\text{arr } f x = \text{serialize} (f x)
\]
\[
(a \gg> b) x = b (\text{serialize}^\dagger (a x))
\]
\[
\text{first } a (x, z) = \text{serialize} (\text{serialize}^\dagger (a x), z)
\]
\[
\text{instance InverseArrow (Serializer) where}
\]
\[
\text{inv } a y = \text{serialize} (a^\dagger (\text{serialize} y))
\]
Notice how $\text{serialize}^\dagger : \text{Serialized } X \leftrightarrow X$ takes the role of a (partial) deserializer, able to recover the internal representation from serialized data as produced by the serializer. A deserializer of the form $\text{serialize}^\dagger$ will often only be partially defined, since many serialization methods allow many different serialized representations of the same data (for example, many textual serialization formats are whitespace insensitive). In spite of this shortcoming, partial deserializers produced by inverting serializers are sufficient for the above definition to satisfy the inverse arrow laws.
### Example 3.13 (Dagger Frobenius monads)
Monads are also often used to capture computational side-effects. Arrows are more general. If $T$ is a strong monad, then $A = \text{hom}(-, T(+))$ is an arrow: $\text{arr}$ is given by the unit, $\gg>$ is given by Kleisli composition, and $\text{first}$ is given by the strength maps. What happens when the base category is a dagger or inverse category modelling reversible pure functions?
A monad $T$ on a dagger category is a dagger Frobenius monad when it satisfies $T(f^\dagger) = T(f)^\dagger$ and $T(\mu_X) \circ \mu^\dagger_{T(X)} = \mu_{T(X)} \circ T(\mu^\dagger_X)$. The Kleisli category of such a monad is again a dagger category [15, Lemma 6.1], giving rise to an operation $\text{inv}$ satisfying (9)–(10). A dagger Frobenius monad is strong when the strength maps are unitary. In this case (11)–(12) also follow. If the underlying category is an inverse category, then $\mu \circ \mu^\dagger \circ \mu = \mu$, whence $\mu \circ \mu^\dagger = \text{id}$, and (13)–(14) follow. Thus, if $T$ is a strong dagger Frobenius monad on a dagger/inverse category, then $A$ is a dagger/inverse arrow. The Frobenius monad $T(X) = X \otimes \mathbb{C}^2$ on the category of Hilbert spaces captures measurement in quantum computation [14], giving a good example of capturing an irreversible effect in a reversible setting. For more examples see [15].
### Example 3.14 (Restriction monads)
There is a notion in between the dagger and inverse arrows of the previous example. A (strong) restriction monad is a (strong)
monad on a (monoidal) restriction category whose underlying endofunctor is a restriction functor. The Kleisli-category of a restriction monad $T$ has a natural restriction structure: just define the restriction of $f : X \to T(Y)$ to be $\eta_X \circ \bar{f}$. The functors between the base category and the Kleisli category then become restriction functors. If $T$ is a strong restriction monad on a monoidal restriction category $C$, then $\text{Inv}(C)$ has an inverse arrow $(X,Y) \mapsto (\text{Inv}(K\ell(T)))(X,Y)$.
**Example 3.15** (*Control flow*) While only trivial inverse categories have coproducts [11], less structure suffices for reversible control structures. When the domain and codomain of an inverse arrow both have disjointness tensors (see Definition 2.4), it can often be used to implement $\text{ArrowChoice}$. For a simple example, the pure arrow on an inverse category with disjointness tensors implements $\text{left} : A X Y \to A (X \oplus Z) (Y \oplus Z)$ as
$$\text{left } f (x, z) = (f x, z)$$
The laws of $\text{ArrowChoice}$ [16] simply reduce to $- \oplus -$ being a bifunctor with natural quasi-injections. More generally, the laws amount to preservation of the disjointness tensor. For the reversible state arrow (Example 3.7), this hinges on $\otimes$ distributing over $\oplus$.
The splitting combinator $(\quad\quad)$ is unproblematic for reversibility, but the fan-in combinator $((||))$ cannot be defined reversibly, as it explicitly deletes information about which branch was chosen. Reversible conditionals thus require two predicates: one determining the branch to take, and one asserted to join the branches after execution. The branch-joining predicate must be chosen carefully to ensure that it is always true after the $\text{then}$-branch, and false after the $\text{else}$-branch. This is a standard way of handling branch joining reversibly [35,34,12].
**Example 3.16** (*Superoperators*) Quantum information theory has to deal with environments. The basic category $\text{FHilb}$ is that of finite-dimensional Hilbert spaces and linear maps. But because a system may be entangled with its environment, the only morphisms that preserve states are the so-called superoperators, or completely positive maps [31,7]: they are not just positive, but stay positive when tensored with an arbitrary ancillary object. In a sense, information about the system may be stored in the environment without breaking the (reversible) laws of nature. This leads to the so-called CPM construction. It is infamously known not to be a monad. But it is a dagger arrow on $\text{FHilb}$, where $A X Y$ is the set of completely positive maps $X^* \otimes X \to Y^* \otimes Y$, $\text{arr } f = f_* \otimes f$, $a \gggg b = b \circ a$, first$_{X,Y,Z} a = a \otimes \text{id}_Z^{* \otimes Z}$, and $\text{inv } a = a^\dagger$.
Aside from these, other examples do fit the interface of inverse arrows, though they are less syntactically interesting as they must essentially be “built in” to a particular programming language. These include reversible IO, which functions very similarly to irreversible IO, and reversible recursion, which could be used to give a type-level separation between terminating and potentially non-terminating functions, by only allowing fixed points of parametrized functions between arrows rather than between (pure) functions.
4 Inverse arrows, categorically
This section explicates the categorical structure of inverse arrows. Arrows on $C$ can be modelled categorically as monoids in the functor category $[C^{op} \times C, \text{Set}]$ [18]. They also correspond to certain identity-on-objects functors $J : C \rightarrow D$. The category $D$ for an arrow $A$ is built by $D(X, Y) = A X Y$, and $\text{arr}$ provides the functor $J$. We will only consider the multiplicative fragment. The operation first can be incorporated in a standard way using strength [18,3], and poses no added difficulty in the reversible setting.
Clearly, dagger arrows correspond to $D$ being a dagger category and $J$ a dagger functor, whereas inverse arrows correspond to both $C$ and $D$ being inverse categories and $J$ a (dagger) functor. This section takes the first point of view: which monoids correspond to dagger arrows and inverse arrows? In the dagger case, the answer is quite simple: the dagger makes $[C^{op} \times C, \text{Set}]$ into an involutive monoidal category, and then dagger arrows correspond to involutive monoids. Inverse arrows furthermore require certain diagrams to commute.
**Definition 4.1** An involutive monoidal category is a monoidal category $C$ equipped with an involution: a functor $(\overline{\_}) : C \rightarrow C$ satisfying $\overline{f} = f$ for all morphisms $f$, together with a natural isomorphism $\chi_{X,Y} : X \otimes Y \rightarrow Y \otimes X$ that makes the following diagrams commute$^4$:
$$
\begin{align*}
\chi_{X,Y} & : X \otimes Y \rightarrow Y \otimes X \\
\chi & : X \otimes Y \rightarrow Y \otimes X
\end{align*}
$$
Just like monoidal categories are the natural setting for monoids, involutive monoidal categories are the natural setting for involutive monoids. Any involutive monoidal category has a canonical isomorphism $\phi : I \rightarrow \overline{I}$ [9, Lemma 2.3]:
$$
\begin{align*}
I = \overline{I} & \xrightarrow{\rho_I^{-1}} \overline{I \otimes I} \\
\chi_{I,\overline{I}}^{-1} & \xrightarrow{I \otimes \overline{I}} \overline{I} \otimes \overline{I} = \overline{I \otimes I} \xrightarrow{\rho_I} \overline{I}
\end{align*}
$$
Moreover, any monoid $M$ with multiplication $m$ and unit $u$ induces a monoid on $\overline{M}$ with multiplication $\overline{m} \circ \chi_{M,M}$ and unit $\overline{u} \circ \phi$. This monoid structure on $\overline{M}$ allows us to define involutive monoids.
**Definition 4.2** An involutive monoid is a monoid $(M, m, u)$ together with a monoid homomorphism $i : \overline{M} \rightarrow M$ satisfying $i \circ \overline{i} = \text{id}$. A morphism of involutive monoids
$^4$ There is a more general definition allowing a natural isomorphism $\overline{X} \rightarrow X$ (see [9] for details), but we only need the strict case.
is a monoid homomorphism $f : M \to N$ making the following diagram commute:
$$
\begin{array}{ccc}
M & \xrightarrow{f} & N \\
i_M & & i_N \\
M & \xrightarrow{f} & N
\end{array}
$$
Our next result lifts the dagger on $C$ to an involution on the category $[C^{op} \times C, \text{Set}]$ of profunctors. First we recall the monoidal structure on that category. It categorifies the dagger monoidal category $\text{Rel}$ of relations of Section 2 [5].
**Definition 4.3** If $C$ is small, then $[C^{op} \times C, \text{Set}]$ has a monoidal structure
$$
F \otimes G(X, Z) = \int_Y F(X, Y) \times G(Y, Z);
$$
concretely, $F \otimes G(X, Z) = \bigsqcup_{Y \in C} F(X, Y) \times G(Y, Z)/\approx$, where $\approx$ is the equivalence relation generated by $(y, F(f, \text{id})(x)) \approx (G(\text{id}, f)(y), x)$, and the action on morphisms is given by $F \otimes G(f, g) := [y, x]_\approx \mapsto [F(f, \text{id})x, G(\text{id}, g)y]$. The unit of the tensor product is $\text{hom}_C$.
**Proposition 4.4** If $C$ is a dagger category, then $[C^{op} \times C, \text{Set}]$ is an involutive monoidal category when one defines the involution on objects $F$ by $\overline{F}(X, Y) = F(Y, X)$, $\overline{F}(f, g) = F(g^\dagger, f^\dagger)$ and on morphisms $\overline{\tau}: F \to G$ by $\overline{\tau}_{X,Y} = \tau_{Y,X}$.
**Proof.** First observe that $\overline{\text{()}}$ is well-defined: For any natural transformation of profunctors $\tau$, $\overline{\tau}$ is natural, and $\tau \mapsto \overline{\tau}$ is functorial. Define $\chi_{F,G}$ by the following composite of natural isomorphisms:
$$
\begin{align*}
\overline{F \otimes G}(X, Z) &\cong \int^Y \overline{F}(X, Y) \times \overline{G}(Y, Z) \text{ by definition of } \overline{\text{\otimes}} \\
&= \int^Y F(Y, X) \times G(Z, Y) \text{ by definition of } \overline{\text{\int}} \\
&\cong \int^Y G(Z, Y) \times F(Y, X) \text{ by symmetry of } \times \\
&\cong G \otimes F(Z, X) \text{ by definition of } \overline{\text{\otimes}} \\
&= \overline{G} \otimes \overline{F}(X, Z) \text{ by definition of } \overline{\text{\otimes}}
\end{align*}
$$
Checking that $\chi$ make the relevant diagrams commute is routine. \hfill $\Box$
**Theorem 4.5** If $C$ is a dagger category, the multiplicative fragments of dagger arrows on $C$ correspond exactly to involutive monoids in $[C^{op} \times C, \text{Set}]$.
**Proof.** It suffices to show that the dagger on an arrow corresponds to an involution on the corresponding monoid $F$. But this is easy: an involution on $F$ corresponds to giving, for each $X, Y$ a map $F(X, Y) \to F(Y, X)$ subject to some axioms. That this involution is a monoid homomorphism amounts to it being a contravariant identity-on-objects-functor, and the other axiom amounts to it being involutive. \hfill $\Box$
Remark 4.6 If the operation first is modeled categorically as (internal) strength, axiom (12) for dagger arrows can be phrased in \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\) as follows: for each object \(Z\) of \(\mathcal{C}\), and each dagger arrow \(M\), the profunctor \(M_Z = M((-) \otimes Z, (+) \otimes Z)\) is also a dagger arrow, and first\(_{-,+,Z}\) is a natural transformation \(M \Rightarrow M_Z\). The arrow laws (7) and (8) imply that it is a monoid homomorphism, and the new axiom just states that it is in fact a homomorphism of involutive monoids. For inverse arrows this law is not needed, as any functor between inverse categories is automatically a dagger functor and thus every monoid homomorphism between monoids corresponding to inverse arrows preserves the involution.
Next we set out to characterize which involutive monoids correspond to inverse arrows. Given an involutive monoid \(M\), the obvious approach would be to just state that the map \(\mathcal{C}^{\text{op}} \times \mathcal{C} \rightarrow \text{Set}\) defined by \(a \mapsto a \circ a^\dagger \circ a\) is the identity. However, there is a catch: for an arbitrary involutive monoid, the map \(a \mapsto a \circ a^\dagger \circ a\) is not natural transformation and therefore not a morphism in \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\). To circumvent this, we first require some conditions guaranteeing naturality. These conditions concern endomorphisms, and to discuss them we introduce an auxiliary operation on \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\).
Definition 4.7 Let \(\mathcal{C}\) be a dagger category. Given a profunctor \(M : \mathcal{C}^{\text{op}} \times \mathcal{C} \rightarrow \text{Set}\), define \(LM : \mathcal{C}^{\text{op}} \times \mathcal{C} \rightarrow \text{Set}\) by
\[
LM(X, Y) = M(X, X),
\]
\[
LM(f, g) = f^\dagger \circ (-) \circ f.
\]
If \(M\) is an involutive monoid in \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\), define a subprofunctor of \(LM\):
\[
L^+ M(X, Y) = \{a^\dagger \circ a \in M(X, X) \mid a \in M(X, Z) \text{ for some } Z\}.
\]
Remark 4.8 The construction \(L\) is a functor \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}] \rightarrow [\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\). There is an analogous construction \(RM(X, Y) = M(Y, Y)\) and \(R^+ M\), and furthermore \(RM = LM\). For any monoid \(M\) in \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\), \(LM\) is a right \(M\)-module (and \(RM\) a left \(M\)-module). Compare Example 3.16.
For the rest of this section, assume the base category \(\mathcal{C}\) to be an inverse category. This lets us multiply positive arrows by positive pure morphisms. If \(M\) is an involutive monoid in \([\mathcal{C}^{\text{op}} \times \mathcal{C}, \text{Set}]\), then the map \(LM \times L^+(\text{homC}) \rightarrow LM\) defined by \((a, g^\dagger \circ g) \mapsto a \circ g^\dagger \circ g\) is natural:
Similarly there is a map \( L^+(\text{hom}) \times LM \rightarrow LM \) defined by \((g^\dagger \circ g, a) \mapsto g^\dagger \circ g \circ a\). Now the category corresponding to \( M \) satisfies \( a^\dagger \circ a \circ g^\dagger = g^\dagger \circ g \circ a^\dagger \circ a \) for all \( a \) and pure \( g \) if and only if the following diagram commutes:
\[
\begin{array}{ccc}
L^+(\text{hom}) \times L^+(\text{hom}) & \longrightarrow & LM \times L^+(\text{hom}) \\
\sigma \downarrow & & \downarrow \\
L^+(\text{hom}) \times L^+M & \longrightarrow & L^+(\text{hom}) \times LM & \longrightarrow & LM
\end{array}
\] (15)
If this is satisfied for an involutive monoid \( M \) in \([C^{\text{op}} \times C, \text{Set}]\), then positive arrows multiply. In other words, the map \( L^+M \times L^+M \rightarrow LM \) defined by \((a^\dagger \circ a, b^\dagger \circ b) \mapsto a^\dagger \circ a \circ b^\dagger \circ b \) is natural:
\[
D_M(f,g)(a, a^\dagger, a) \\
= (g \circ a \circ f, f^\dagger \circ a^\dagger \circ g^\dagger, g \circ a \circ f) \\
\mapsto g \circ a \circ f \circ f^\dagger \circ a^\dagger \circ g^\dagger \circ g \circ a \circ f \\
= g \circ a \circ a^\dagger \circ g^\dagger \circ g \circ a \circ f \circ f^\dagger \circ f \\
= g \circ a \circ a^\dagger \circ a \circ a \circ f \\
= g \circ g^\dagger \circ g \circ a \circ a^\dagger \circ a \circ f \\
= g \circ a \circ a^\dagger \circ a \circ f \\
= M(f,g)(a \circ a^\dagger \circ a)
\]
This multiplication is commutative iff the following diagram commutes:
\[
\begin{array}{ccc}
L^+M \times L^+M & \longrightarrow & L^+M \times L^+M \\
\sigma \downarrow & & \downarrow \\
& & LM
\end{array}
\] (16)
Finally, let \( D_M \hookrightarrow M \times M \times M \) be the diagonal \( D_M(X,Y) = \{(a,a^\dagger,a) \mid a \in M(X,Y)\} \).
If \( M \) satisfies (15), then the map \( D_M \rightarrow M \) defined by \((a, a^\dagger, a) \mapsto a \circ a^\dagger \circ a \) is natural:
Thus \( M \) satisfies \( a \circ a^\dagger \circ a = a \) if and only if the following diagram commutes:
\[
\begin{array}{ccc}
M & \rightarrow & D_M \\
\downarrow \text{id} & & \downarrow \\
M & \rightarrow & M
\end{array}
\]
Hence we have established the following theorem.
**Theorem 4.9** Let \( C \) be an inverse category. Then the multiplicative fragments of inverse arrows on \( C \) correspond exactly to involutive monoids in \( [C^{\text{op}} \times C, \text{Set}] \) making the diagrams (15)–(17) commute.
\[\square\]
5 Applications and related work
As we have seen, inverse arrows capture a variety of fundamental reversible effects. An immediate application of our results would be to retrofit existing typed reversible functional programming languages (e.g., Theseus [20]) with inverse arrows to accommodate reversible effects while maintaining a type-level separation between pure and effectful programs. Another approach could be to design entirely new such programming languages, taking inverse arrows as the fundamental representation of reversible effects. While the Haskell approach to arrows uses typeclasses [16], these are not a priori necessary to reap the benefits of inverse arrows. For example, special syntax for defining inverse arrows could also be used, either explicitly, or implicitly by means of an effect system that uses inverse arrows “under the hood”.
To aid programming with ordinary arrows, a handy notation due to Paterson [27,28] may be used. The simplest form of this notation is based on process combinators, the central one being
\[
p \rightarrow e_1 \triangleleft e_2 = \begin{cases}
\text{arr}(\lambda p.e_2) \gg e_1 & \text{if } p \text{ is fresh for } e_1, \\
\text{arr}(\lambda p.(e_1,e_2)) \gg \text{app} & \text{otherwise.}
\end{cases}
\]
Note that if the second branch is used, the arrow must additionally be an instance of \texttt{ArrowApply} (so that it is, in fact, a monad). Though we only know of degenerate examples where inverse arrows are instances of \texttt{ArrowApply}, this definition is conceptually unproblematic (from the point of view of guaranteeing reversibility) so long as the pure function $\lambda p.e_2$ is first-order and reversible. A more advanced style of this notation is the \texttt{do}-notation for arrows, which additionally relies on the arrow combinator
$$\begin{align*}
\text{bind} &: A \times Y \rightarrow A (X \otimes Y) \times A \times Z \\
\text{f 'bind' g} &= (\text{arr}(id) \&& \text{f}) \gg\gg g.
\end{align*}$$
If the underlying monoidal dagger category has natural coassociative diagonals, for example when it has inverse products, this combinator does exist: the arrow combinator ($\&&\&&$) can be defined as
$$\begin{align*}
(\&&\&&): A \times Y \rightarrow A \times Z \rightarrow A (Y \otimes Z) \\
\text{f} \&&\&& \text{g} &= \text{arr}(\text{copy}) \gg\gg \text{first}(f) \gg\gg \text{second}(g)
\end{align*}$$
where \texttt{copy} : $X \rightarrow X \otimes X$ is the natural diagonal (given in pseudocode by \texttt{copy x} = \texttt{(x, x)}), and the combinator \texttt{second} is derived from \texttt{first} in the usual way, \texttt{i.e.}, as
$$\begin{align*}
\text{second} &: A \times Y \rightarrow A (Z \otimes X) (Z \otimes Y) \\
\text{second f} &= \text{arr}(\text{swap}) \gg\gg \text{first}(f) \gg\gg \text{arr}(\text{swap})
\end{align*}$$
with \texttt{swap} : $X \otimes Y \leftrightarrow Y \otimes X$ given by \texttt{swap} $(x, y)$ = $(y, x)$. This allows \texttt{do}-notation of the form
$$\begin{align*}
\text{do} \{ p \leftarrow c; A \} &\equiv c \text{'bind'} (\kappa p. \text{do} \{ A \}),
\end{align*}$$
so soon as the $\kappa$-calculus [13] expression $\kappa p. \text{do} \{ A \}$ is reversible. Note, however, that \texttt{do}-expressions of the form $\text{do} \{ c; A \}$ (\texttt{i.e.}, where the output of $c$ is discarded entirely) will fail to be reversible in all but the most trivial cases. Since $\text{do} \{ p \leftarrow c; A \}$ produces a value of an inverse arrow type, closure under program inversion provides a program we might call
$$\begin{align*}
\text{undo} \{ p \leftarrow c; A \} &\equiv \text{inv}(\text{do} \{ p \leftarrow c; A \}) .
\end{align*}$$
Inverse arrow law (13) then guarantees that \texttt{doing}, then \texttt{undoing}, and then \texttt{doing} the same operation is the same as \texttt{doing} it once.
A pleasant consequence of the semantics of inverse arrows is that inverse arrows are safe: as long as the inverse arrow laws are satisfied, fundamental properties guaranteed by reversible functional programming languages (such as invertibility and closure under program inversion) are preserved. In this way, inverse arrows provide reversible effects as a conservative extension to pure reversible functional programming.
A similar approach to invertibility using arrows is given by bidirectional arrows [2]. However, while the goal of inverse arrows is to add effects to already invertible languages, bidirectional arrows arise as a means to add invertibility to an otherwise uninvertible language. As such, bidirectional arrows have different concerns than inverse arrows, and notably do not guarantee invertibility in the general case.
Acknowledgements
This work was supported by COST Action IC1405, the Oskar Huttunen Foundation, and EPSRC Fellowship EP/L002388/1. We thank Robert Furber and Robert Glück for discussions.
References
|
{"Source-Url": "https://static-curis.ku.dk/portal/files/211215602/ArticleKaarsgaard.pdf", "len_cl100k_base": 14939, "olmocr-version": "0.1.53", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 78519, "total-output-tokens": 18751, "length": "2e13", "weborganizer": {"__label__adult": 0.0005316734313964844, "__label__art_design": 0.0005335807800292969, "__label__crime_law": 0.0004439353942871094, "__label__education_jobs": 0.0014362335205078125, "__label__entertainment": 0.00012373924255371094, "__label__fashion_beauty": 0.00024127960205078125, "__label__finance_business": 0.0003888607025146485, "__label__food_dining": 0.0006265640258789062, "__label__games": 0.0009002685546875, "__label__hardware": 0.001445770263671875, "__label__health": 0.0011606216430664062, "__label__history": 0.00047087669372558594, "__label__home_hobbies": 0.00017261505126953125, "__label__industrial": 0.0008020401000976562, "__label__literature": 0.0008244514465332031, "__label__politics": 0.0004322528839111328, "__label__religion": 0.0009212493896484376, "__label__science_tech": 0.133544921875, "__label__social_life": 0.0001360177993774414, "__label__software": 0.00582122802734375, "__label__software_dev": 0.84716796875, "__label__sports_fitness": 0.0003597736358642578, "__label__transportation": 0.0010976791381835938, "__label__travel": 0.0002532005310058594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59474, 0.01446]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59474, 0.70859]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59474, 0.77376]], "google_gemma-3-12b-it_contains_pii": [[0, 513, false], [513, 1960, null], [1960, 5280, null], [5280, 8509, null], [8509, 10735, null], [10735, 13627, null], [13627, 16131, null], [16131, 19331, null], [19331, 22790, null], [22790, 25716, null], [25716, 27774, null], [27774, 30904, null], [30904, 34309, null], [34309, 37694, null], [37694, 40493, null], [40493, 43286, null], [43286, 46282, null], [46282, 48237, null], [48237, 50037, null], [50037, 53041, null], [53041, 56325, null], [56325, 59474, null]], "google_gemma-3-12b-it_is_public_document": [[0, 513, true], [513, 1960, null], [1960, 5280, null], [5280, 8509, null], [8509, 10735, null], [10735, 13627, null], [13627, 16131, null], [16131, 19331, null], [19331, 22790, null], [22790, 25716, null], [25716, 27774, null], [27774, 30904, null], [30904, 34309, null], [34309, 37694, null], [37694, 40493, null], [40493, 43286, null], [43286, 46282, null], [46282, 48237, null], [48237, 50037, null], [50037, 53041, null], [53041, 56325, null], [56325, 59474, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59474, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59474, null]], "pdf_page_numbers": [[0, 513, 1], [513, 1960, 2], [1960, 5280, 3], [5280, 8509, 4], [8509, 10735, 5], [10735, 13627, 6], [13627, 16131, 7], [16131, 19331, 8], [19331, 22790, 9], [22790, 25716, 10], [25716, 27774, 11], [27774, 30904, 12], [30904, 34309, 13], [34309, 37694, 14], [37694, 40493, 15], [40493, 43286, 16], [43286, 46282, 17], [46282, 48237, 18], [48237, 50037, 19], [50037, 53041, 20], [53041, 56325, 21], [56325, 59474, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59474, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
89165231df64a1c7a8fea369420bb9ed31e9af39
|
<table>
<thead>
<tr>
<th>Title</th>
<th>Metis: A Term Rewriting System Generator: An Inference Engine for Equations and Inequations</th>
</tr>
</thead>
<tbody>
<tr>
<td>Author(s)</td>
<td>Ohsuga, Akihiko; Sakai, Ko</td>
</tr>
<tr>
<td>Citation</td>
<td>数理解析研究所講究録 (1987), 618: 170-187</td>
</tr>
<tr>
<td>Issue Date</td>
<td>1987-04</td>
</tr>
<tr>
<td>URL</td>
<td><a href="http://hdl.handle.net/2433/99856">http://hdl.handle.net/2433/99856</a></td>
</tr>
<tr>
<td>Type</td>
<td>Departmental Bulletin Paper</td>
</tr>
<tr>
<td>Textversion</td>
<td>publisher</td>
</tr>
</tbody>
</table>
Kyoto University
Metis: A Term Rewriting System Generator
— An Inference Engine for Equations and Inequations —
Akihiko Ohsuga and Kō Sakai
ICOT Research Center
1-4-28, Mita, Minato-ku, Tokyo 108, JAPAN
September 10, 1986
RIMS Symposium on Software Science and Engineering
ABSTRACT
The TRS (term rewriting system) Working Group of ICOT has been studying applications of TRSs to the intelligent programming system. As a result, we have implemented a TRS generator called Metis, an experimental tool with the many functions required for such a system. This paper describes the features of Metis and several experiments with it.
1. Introduction
A set of rewrite rules is called a term rewriting system or TRS. The theory of TRSs has a wide variety of both theoretical and practical applications. It provides models for abstract data types, operational semantics for functional programming languages, and inference engines for automated theorem proving with equality.
The intelligent programming system is an important research topic of Japan’s Fifth Generation Computer System (FGCS) Project. A lot of evidence suggests that the study of TRSs will yield key technologies for the intelligent programming system, in particular for specification, verification, and synthesis of programs. The Institute for New Generation Computer Technology (ICOT) organized the TRS Working Group in 1985 to study TRSs theoretically, and for application to the intelligent programming system.
Metis is the first result of the activity of the working group. It generates a complete TRS from a set of equations automatically, semi-automatically, or interactively. It is also an experimental tool with the various functions needed for the study of TRSs.
The kernel function of Metis is the so-called Knuth-Bendix completion procedure. Significantly improved with better capabilities and operability by the incorporation of many new facilities. For example, Metis can provide us with several kinds of ordering methods of terms, but the user can orient an equation with little knowledge of the ordering methods and obtain an appropriate rewrite rule that does not violate termination of the TRS. If the equation cannot be oriented to either direction, Metis offers the user several kinds of recipe. It manipulates inequations as well as equations and provides special handling of associative-commutative operators in the completion procedure.
Section 2 describes the basic concept of the TRS. Section 3 introduces the features of Metis in the general framework, and in Section 4, several concrete examples illustrate how Metis actually works.
2. Preliminaries
In this section, we will introduce the terminology and notation in this paper and survey well-known properties of TRSs.
We will deal with finite sequences of the following two kinds of symbols (and parentheses and commas for ease of reading):
1. A finite set $F$ of function symbols, and
2. A denumerable set $V$ of variables.
We assume the reader is familiar with the concepts of terms, ground terms, occurrences, subterms, substitutions, unifiers, and most general unifiers. In what follows, we will denote the set of all terms constructed from $F$ and $V$ by $\mathcal{T}(F,V)$, and the set of all the ground terms constructed from $F$ by $\mathcal{T}(F)$. The notation $t[s]$ represents a term with $s$ as its subterm. In this context, $[s]$ represents a certain occurrence of $s$ in $t[s]$. Thus, $t[s']$ denotes the term obtained by replacing the occurrence of $s$ in $t[s]$ with $s'$. Similarly, we will use the notation $t[s_1, \ldots, s_n]$ to represent a term with $s_1, \ldots, s_n$ subterms, and $t[s'_1, \ldots, s'_n]$ for the term obtained by replacing each $s_i$ in $t[s_1, \ldots, s_n]$ with $s'_i$. Substitutions are denoted by the greek letter $\theta$, possibly with subscripts and primes.
Definition 2.1
A term rewriting system (TRS) is a finite set of pairs $l \rightarrow r$ of terms. An element $l \rightarrow r$ of a TRS is called a rewrite rule.
Definition 2.2
Let $R$ be a TRS. A term $t$ is said to be reduced to another term $u$ with respect to $R$, if there exist a rewrite rule $l \rightarrow r$ and a substitution $\theta$ such that $c[\theta(l)] = t$ and $c[\theta(r)] = u$, denoted by $t \Rightarrow u$. We denote the reflexive transitive closure of $\Rightarrow$ by $\Rightarrow^*$.
Definition 2.3
Let $R$ be a TRS. Two terms $u$ and $v$ are said to be convergent (with respect to $R$) if there exists a term $t$ such that $u \Rightarrow^* t$ and $v \Rightarrow^* t$. A TRS is said to be confluent if $t_1$ and $t_2$ are convergent for any $t$ and for any two reductions $t \Rightarrow t_1$ and $t \Rightarrow t_2$.
Definition 2.4
A TRS is said to terminate if there exists no infinite reduction $t_1 \Rightarrow t_2 \Rightarrow \cdots \Rightarrow t_n \Rightarrow \cdots$.
Definition 2.5
A term $t$ is said to be irreducible if there exists no term $u$ such that $t \Rightarrow u$. An irreducible term $s$ such that $t \Rightarrow s$ is called an irreducible form of $t$ (with respect to $R$) and denoted by $t\downarrow$.
If $R$ is a terminating TRS, then every term $t$ has an irreducible form $t\downarrow$. Moreover, $R$ is confluent if and only if the irreducible form $t\downarrow$ is unique. In this case, the TRS $R$ is said to be complete and the irreducible form $t\downarrow$ is called the normal form of $t$.
Intuitively, a reduction step represents a computation step. Therefore, termination of a TRS means that every computation process finally stops and a certain result (i.e. an irreducible form) is obtained, while confluence of a TRS means that the result is unique. For this reason, completeness plays an important role in the study of TRSs (viewed as computation mechanisms) and the normal form of a term is sometimes called the value of the term.
Historically, however, the concept of TRS appeared as a decision procedure of word problems of universal algebra, where the completeness is very significant as well, because the decidability of the word problems depend on completeness of the TRS obtained by converting equational axioms to rewrite rules.
Definition 2.6
An equational theory is a set of pairs $t_1 \simeq t_2$ of terms satisfying the following conditions. (We use the symbol $\simeq$ for this purpose, and the symbol $=$ is taken to mean syntactical identity in this paper.)
1. $t \simeq t$ for all terms $t$.
2. If $t_1 \simeq t_2$, then $t_2 \simeq t_1$.
3. If $t_1 \simeq t_2$, $t_2 \simeq t_3$, then $t_1 \simeq t_3$.
4. If $t_1 \simeq t_2$, then $\theta(t_1) \simeq \theta(t_2)$ for any substitution $\theta$.
5. If $t_1 \simeq t_2$, then $s[t_1] \simeq s[t_2]$.
Any set $E$ of pairs $l \simeq r$ of terms can be extended to an equational theory by considering the closure $T(E)$ of $E$ with respect to the above conditions (1)-(5). In other words, the equational theory $T(E)$ is the least congruence including $E$. The set $E$ is called an (equational) axiom system of the equational theory $T(E)$ and an element of $E$ is called an axiom.
The word problem in an equational theory $T$ involves the determination of whether $t_1 \simeq t_2$ for two arbitrary terms $t_1$ and $t_2$. Given an equational theory $T$, suppose that there exists a complete TRS such that $t_1 \simeq t_2$ if and only if $t_1 \downarrow = t_2 \downarrow$ for any two terms $t_1$ and $t_2$. Obviously, such a TRS can be viewed as an algorithm to solve the word problem of $T$. Knuth and Bendix devised a mechanical procedure to convert an axiom system $E$ to a complete TRS which solves the word problems of $T(E)$ [Knuth 70, Huet 81].
Before introducing the procedure, let us define critical pairs.
Definition 2.7
Let \( l_{1} \rightarrow r_{1} \) and \( l_{2} \rightarrow r_{2} \) be rewriting rules and \( s \) be a non-variable subterm of \( l_{2} \) such that \( l_{1} \) and \( s \) have a most general unifier \( \theta \). Let \( l_{2} = c[s] \). The term \( \theta(l_{2}) \) is called the superposition of \( l_{1} \) on \( s \) in \( l_{2} \). The pair \( \theta(c[r_{1}]) \simeq \theta(r_{2}) \) is called a critical pair between \( l_{1} \rightarrow r_{1} \) and \( l_{2} \rightarrow r_{2} \).
We are now ready to introduce the Knuth-Bendix completion procedure.
Procedure 2.8 Knuth and Bendix’s completion
Step 0: Set \( E \) to be the initially given axiom system. Set \( R \) to be empty. Go to Step 1.
Step 1: If \( E \) is empty, the current value of \( R \) is the desired TRS. Otherwise, go to Step 2.
Step 2: Remove a pair \( t \simeq u \) from \( E \). If the rule \( t \rightarrow u \) or \( u \rightarrow t \) can be added to \( R \) without violating termination, acquire it as a new rule and go to Step 3. Otherwise, stop; the procedure is unsuccessful.
Step 3: Remove all the rewrite rules \( l \rightarrow r \) from \( R \) such that either \( l \) or \( r \) is reducible by the acquired new rule and append \( l \simeq r \) to \( E \) instead. Go to Step 4.
Step 4: Append the acquired rule to \( R \). Construct all the critical pairs between the acquired rule and all the rules in \( R \) (including the acquired rule itself) and append them to \( E \). For each equation \( t \simeq u \) in \( E \), find irreducible forms \( t \downarrow \) and \( u \downarrow \) with respect to \( R \), and set \( \{ t \downarrow \simeq u \downarrow \mid t \downarrow \neq u \downarrow, t \simeq u \in E \} \) to be the new \( E \). Go to Step 1.
If the procedure terminates successfully, the resulting \( R \) is a complete TRS to solve the word problem of \( T(E) \) for the initially given \( E \).
3. Term rewriting system generator Metis
Metis is a TRS generator based on the completion procedure described in the previous section. It has a lot of functions required before, during, and after generation of TRSs for a very user-friendly system. In this section, we will describe several characteristic features of Metis.
3.1 Well-founded ordering of terms
As can be seen from the above description, a key point of the completion procedure is ensuring termination of a TRS. The standard way to assure termination of a system is to introduce a well-founded order on the objects of the system and show that the operations in the system always reduce the objects with respect to the order.
Well-founded orders \( \prec \) on \( \mathcal{T}(F,V) \) with the following properties are usually used on TRSs.
(1) If \( t_{1} \prec t_{2} \), then \( \theta(t_{1}) \prec \theta(t_{2}) \) for any substitution \( \theta \).
(2) If $t_1 \prec t_2$, then $s[t_1] \prec s[t_2]$.
Property (1) is called stability and (2) monotonicity. If there is a monotonic and stable well-founded order on $T(F, V)$ such that $l \succ r$ for every rule $l \rightarrow r$, it is obvious that the TRS terminates. There is a lot of research for such ordering methods, such as well-known Dershowitz's recursive path ordering [Dershowitz 82]. The original version of the recursive path ordering is defined on the set $T(F)$ of ground terms. Here, however, we extend the definition on the set $T(F, V)$ of all the terms.
Definition 3.1 Recursive path ordering
Let $<$ be a partial order on the set of function symbols $F$. The recursive path ordering $\prec$ of $T(F, V)$ is then defined recursively as follows:
(1) For a variable $v$, there are no terms $t$ such that $t \prec v$.
(2) For a non-variable term $t = g(t_1, \ldots, t_n)$ and a term $s$, $s \prec t$ if and only if
(2-1) there exists $j$ such that $s \preceq t_j$ or
(2-2) $s = f(s_1, \ldots, s_m)$ and $s_i \prec t$ for all $i$ and
(2-2-1) $f \prec g$ or
(2-2-2) $f = g$ and $(s_1, \ldots, s_m) \preceq (t_1, \ldots, t_n)$, where $\preceq$ is the multi-set ordering [Dershowitz 79] induced by $\prec$.
In (2-2-2) of the above definition, adoption of the multi-set ordering is not always necessary. If the function symbols $f$ is varyadic (i.e. takes an arbitrary number of arguments) and the order of the arguments does not affect the value of the function (for example, $\sum$ and $\prod$ representing finite sum and product), the multi-set ordering is probably the most reasonable. However, if the function symbol $f$ has a fixed arity, the lexicographic ordering is more suitable in many cases. There may be cases where the kachinuki ordering [Sakai 85] is the most appropriate.
Metis can handle any of these three versions of the recursive path ordering, namely multi-set, lexicographic, and kachinuki. The user can employ arbitrary combinations of them, function by function. As long as the lexicographic order is applied only to function symbols of fixed arity, any combination defines a monotone and stable well-founded order on $T(F, V)$. Moreover, if the underlying order $<$ on $F$ is total and the lexicographic or the kachinuki ordering are employed for any function symbol, then it is a total ordering on the limited domain $T(F)$ of the ground terms, a very important property as we shall see later.
Metis converts axioms to rewrite rules $l \rightarrow r$ such that $l \succ r$. Metis allows the user to define the underlying partial order $<$ on $F$ incrementally during the completion procedure. If the user knows little about the above ordering method, Metis can suggest what ordering is needed on $F$ in order to orient an equation to a certain direction. Thus, when both are possible, the user just has to decide which direction an equation should be oriented to.
3.2 Associative and commutative operators
The weakest point of the Knuth-Bendix completion procedure is revealed by equations that cannot be converted to rules without violating the termination of the TRS. The most typical example of such axioms is the commutative laws, such as $A + B \simeq B + A$. Encounter with such an equation causes unsuccessful stop in Step 2 of the procedure. Metis has several countermeasures to deal with this situation. The general measures will be described later.
It is clearly the commutativity of operators that is the main source of the above failure. In many cases, commutative operators are also associative. Metis has a specific countermeasure effective only against the commutative laws combined with the associative laws of the same operators. A function symbol is called an AC-operator if it satisfies the associative and the commutative law. Metis is equipped with an algorithm of special unification for AC-operators (called AC-unification) devised by Fages [Fages 84] and can execute the AC-completion procedure based on Peterson and Stickel's principle [Peterson 81].
For example, if Metis is told that $+$ is an AC-operator, then the axioms $A + B \simeq B + A$ and $(A + B) + C \simeq A + (B + C)$ are acquired implicitly and AC-unification and AC-reduction are activated for $+$. Thus, Metis can generate $0 + Y + (-(X + Y)) \simeq (-X) + 0$ as a critical pair between the same two rules $(-X) + X \rightarrow 0$ by AC-unification, since
$$0 + Y + (-(X + Y)) \Leftarrow (-X) + X + Y + (-(X + Y)) \Rightarrow (-X) + 0.$$
If it has the rule $0 + A \rightarrow A$, the above critical pair is reduced to $Y + (-(X + Y)) \simeq -X$ by AC-reduction.
As shown in the above example, an AC-operator is supposed to be a binary function symbol and Metis allows us to use infix notation for binary function symbols. Inside Metis an AC-operator is treated as if it were varyadic. For example, the term $t_1 + \cdots + t_n$ is converted to $+(t_1, \ldots, t_n)$ with a varyadic function symbol $+$, in whatever order the operator $+$ is applied to the arguments. The multi-set ordering is assumed to be the ordering method for AC-operators unless otherwise specified, since the above treatment makes it the most reasonable ordering as mentioned in the previous section.
3.3 Orientation-free rules and S-strategy
There exist many equations other than commutative laws which cannot be converted to terminating rules. The approach of incorporating special unification algorithms for such equations has been studied systematically by Jouannaud and Kirchner [Jouannaud 84].
A simple trick to handle non-orientable equations is introducing a new function symbol. For example, if the equation $A^2 \simeq A \times A$ cannot be oriented to either direction, a new function symbol $\text{square}$ is introduced and the problematic equation is divided to the two equations $A^2 \simeq \text{square}(A)$ and $A \times A \simeq \text{square}(A)$. Thus, Metis can continue the completion procedure,
since both equations can be oriented left to right. This technique seems to be too simple, but the effect is worth implementation [Knuth 70, Sakai 84].
A more radical remedy for such equations is adoption of orientation-free rules. This remedy is called the unfailing completion procedure [Hsiang 85, Bachmair 86]. Metis is equipped with an extended version of the unfailing completion procedure called S-strategy devised by Hsiang and Rusinowitch [Hsiang 85]. The S-strategy has enabled Metis to manipulate not only non-orientable equations, but also inequational axioms as well as equational axioms.
The S-strategy can be viewed as a kind of refutational theorem proving technique for systems of equations and inequations. Before introducing the S-strategy, we will extend the concepts of reduction and critical pairs and introduce the concept of extended narrowing and subsumption. Let us fix a monotonic and stable well-founded order \( \prec \) on \( T(F, V) \).
**Definition 3.2**
A term \( t \) is said to be *reduced* to another term \( u \) by an equation \( l \simeq r \) (or \( r \simeq l \)), if \( t \succ u \) and there exists a substitution \( \theta \) such that \( c[\theta(l)] = t \) and \( c[\theta(r)] = u \). This reduction is called an *extended reduction (by an equation)* and denoted also by \( t \Rightarrow u \).
**Definition 3.3**
Let \( l_1 \simeq r_1 \) (or \( r_1 \simeq l_1 \)) and \( l_2 \simeq r_2 \) (or \( r_2 \simeq l_2 \)) be equations. Let \( s \) be a non-variable subterm of \( l_2 \) such that \( l_1 \) and \( s \) have a most general unifier \( \theta \). Let \( l_2 = c[s] \). If \( \theta(l_1) \not\simeq \theta(r_1) \) and \( \theta(l_2) \not\simeq \theta(r_2) \), then the pair \( \theta(c[r_1]) \simeq \theta(r_2) \) is called an *extended critical pair* between \( l_1 \simeq r_1 \) (or \( r_1 \simeq l_1 \)) and \( l_2 \simeq r_2 \) (or \( r_2 \simeq l_2 \)).
If every rule \( l \rightarrow r \) has the property that \( l \succ r \), the above definitions are natural extensions of the ordinary reduction by a rule and the ordinary critical pairs between rules. For example, if \( l \succ r \), the condition that \( t \succ u \) in reducing \( t \) to \( u \) weakens the rewrite power of the equation \( l \simeq r \) exactly to the same level as that of the rule \( l \rightarrow r \), since \( \prec \) is stable and monotonic. Similarly, if \( l_1 \succ r_1 \) and \( l_2 \succ r_2 \), the set of all extended critical pairs between equations \( l_1 \simeq r_1 \) and \( l_2 \simeq r_2 \) is equal to the set of all critical pairs between rules \( l_1 \rightarrow r_1 \) and \( l_2 \rightarrow r_2 \).
**Definition 3.4**
Let \( l_1 \simeq r_1 \) (or \( r_1 \simeq l_1 \)) be an equation and \( l_2 \not\simeq r_2 \) (or \( r_2 \not\simeq l_2 \)) be an inequation. Let \( s \) be a non-variable subterm of \( l_2 \) such that \( l_1 \) and \( s \) have a most general unifier \( \theta \). Let \( l_2 = c[s] \). If \( \theta(l_1) \not\simeq \theta(r_1) \), then the inequation \( \theta(c[r_1]) \not\simeq \theta(r_2) \) is said to be narrowed from \( l_2 \not\simeq r_2 \) (or \( r_2 \not\simeq l_2 \)) using \( l_1 \simeq r_1 \) (or \( r_1 \simeq l_1 \)).
**Definition 3.5**
An equation \( t \simeq u \) is said to be *subsumed* by other equations \( l_1 \simeq r_1 \) (or \( r_1 \simeq l_1 \)), \( \ldots \), \( l_n \simeq r_n \) (or \( r_n \simeq l_n \)), if there exists a substitution \( \theta \) such that \( c[\theta(l_1)], \ldots, \theta(l_n)] = t \) and \( c[\theta(r_1)], \ldots, \theta(r_n)] =
u. An inequation \( t \not\equiv u \) is said to be subsumed by another inequation \( l \not\equiv r \) (or \( r \not\equiv l \)), if there exists a substitution \( \theta \) such that \( \theta(l) = t \) and \( \theta(r) = u \).
Unfailing completion is a modified version of ordinary completion employing extended critical pairs and extended reduction instead of the ordinary ones; and the S-strategy can be viewed as the unfailing completion with refutation by extended narrowing.
**Procedure 3.6 S-strategy**
Suppose that a system of equational and inequational axioms is given together with an equation or inequation to be solved (called the target formula).
**Step 0:** Set \( E \) to be the given axiom system plus the negation of the target formula (Skolemized if necessary). Set \( R \) to be empty. Go to Step 1.
**Step 1:** If \( E \) is empty, the current value of \( R \) is a complete set of equations and inequations deduced from the axioms and the negation of the target formula, in the sense that neither new equations nor new inequations can be derived. Since \( R \) is also consistent, the target formula cannot be deduced from the axioms. If \( E \) is not empty, go to Step 2.
**Step 2:** Remove an equation \( t \equiv u \) or inequation \( t \not\equiv u \) (called the ruling formula) from \( E \). Go to Step 3.
**Step 3:** If the ruling formula is an equation, move all the equations \( l \equiv r \) and all the inequations \( l \not\equiv r \) from \( R \) to \( E \) such that either \( l \) or \( r \) is reducible by the ruling formula and remove all the equations subsumed by the ruling formula from \( R \). If the ruling formula is an inequation, remove all the inequations subsumed by the ruling formula from \( R \). Go to Step 4.
**Step 4:** Append the ruling formula to \( R \). Construct all the extended critical pairs and all the narrowed inequations between the ruling formula and all the equations and inequations in \( R \). Append them to \( E \). For each equation \( t \equiv u \) or inequation \( t \not\equiv u \) in \( E \), find irreducible forms \( t \downarrow \) and \( u \downarrow \) with respect to equations in \( R \). If there is an inequation \( t \not\equiv u \) such that \( t \downarrow \) and \( u \downarrow \) are unifiable, then stop. A contradiction is detected and, therefore, the target formula is deduced from the originally given axiom system. Otherwise, let the new \( E \) be the set of equations \( t \downarrow \equiv u \downarrow \) such that \( t \downarrow \not\equiv u \downarrow \) not subsumed by any equation in \( R \) and inequations \( t \downarrow \not\equiv u \downarrow \) not subsumed by any inequation in \( R \). Go to Step 1.
The unfailing completion differs from the S-strategy only in that it does not treat non-ground inequations. If the ordering \( < \) is total on the set \( T(F) \) of all the ground terms, the S-strategy is logically complete and, therefore, so is the unfailing completion.
4. Experiments
Let us begin with purely algebraic examples. The first example is the word problem of ring theory.
Example 4.1
Metis was given an AC-operator + and a binary operator $\ast$, (not AC in general) with the following axioms:
(1) $0 + A = A$
(2) $(-A) + A = 0$
(3) $(A \ast B) \ast C = A \ast (B \ast C)$
(4) $(A + B) \ast C = A \ast C + B \ast C$
(5) $A \ast (B + C) = A \ast B + A \ast C$
We had Metis run the completion procedure in automatic mode. Metis obtained $(A \ast B) \ast C = A \ast (B \ast C)$ and $0 + A = A$ as the first and the second ruling formula and converted them to the rules $(A \ast B) \ast C \rightarrow A \ast (B \ast C)$ and $0 + A \rightarrow A$, respectively. The third ruling formula $(-A) + A = 0$ could be oriented left to right by the recursive path ordering, if $0 < +$ or $0 < –$. So Metis asked the user which should be introduced.
[[METIS]] $\rightarrow$ k
<< Knuth – Bendix (automatic execution) >>
New Rule is r1: $(A \ast B) \ast C \rightarrow A \ast (B \ast C)$
New Rule is r2: $0 + A \rightarrow A$
You can orient $-A + A \rightarrow 0$ by the following.
[1] $0 << +$
[2] $0 << -$
else exit
After selecting $0 < +$, we had Metis continue the procedure.
select no? 1
[ 0 << + is asserted. ]
New Rule is r3: $-A + A \rightarrow 0$
New Rule is r4: $-(-A) \rightarrow A$
New Rule is r5: $-(0) \rightarrow 0$
Which do you want to orient?
[1] $A \ast (B + C) \rightarrow A \ast B + A \ast C$
[2] $A \ast B + A \ast C \rightarrow A \ast (B + C)$
else exit
The sixth ruling formula was the left distributive law and it could be oriented to either direction depending on the orderings on function symbols. Since we instructed Metis to convert it to the rule $A *(B + C) \rightarrow A * B + A * C$, the system automatically introduced $+$ $-$ as the ordering on function symbols.
select no ? 1
[ + << * is asserted. ]
New Rule is r6: $A*(B+C)$ $\rightarrow$ $A*B+A*C$
New Rule is r7: $(A+B)*C$ $\rightarrow$ $A*C+B*C$
New Rule is r8: $A+ -(B+A)$ $\rightarrow$ $-B$
[ + << - is asserted. ]
New Rule is r9: $-(A+(-B))$ $\rightarrow$ $B+(-A)$
The ninth ruling formula can be converted to the rule $-(A + (-B)) \rightarrow B + (-A)$ if and only if $+ < -$. So Metis introduced the ordering without interaction.
New Rule is r10: $-(A+B)$ $\rightarrow$ $-A+(-B)$
DELETE r8
DELETE r8*
DELETE r9
New Rule is r11: $A*0+A*B$ $\rightarrow$ $A*B$
New Rule is r12: $A*0$ $\rightarrow$ $0$
DELETE r11
DELETE r11*
New Rule is r13: $0*A+B*A$ $\rightarrow$ $B*A$
New Rule is r14: $0*A$ $\rightarrow$ $0$
DELETE r13
DELETE r13*
New Rule is r15: $(-A)*B+A*B$ $\rightarrow$ $0$
Which do you want to orient ?
[1] $(-A)*B$ $\rightarrow$ $-A*B$
else exit
select no ? 1
[ - << * is asserted. ]
New Rule is r16: $(-A)*B$ $\rightarrow$ $-A*B$
DELETE r15
DELETE r15*
New Rule is r17: $A*(-B)+A*B$ $\rightarrow$ $0$
New Rule is r18: $A*(-B)$ $\rightarrow$ $-A*B$
Knuth - Bendix terminated.
Your system is [ COMPLETE ].
The procedure terminated successfully. Here is the resulting complete TRS for the word problem of rings.
\[ [\text{METIS}] \rightarrow \text{list} \]
\[ \ll \text{state listing} \gg \]
"ring"
operators:
\[ + / AC \ (\text{multiset ordering}) \]
\[ 0 / 0 \]
\[ - / 1 \]
\[ * / 2 \ (\text{left to right lexicographic ordering}) \]
orderings:
\[ 0 < "+" < *, - \]
\[ "O" < +, *, - \]
\[ +, 0 < "-" < * \]
\[ +, -, 0 < "*" \]
equations:
No equations.
rules:
r1: \( (A*B)*C \rightarrow A*(B+C) \)
r2: \( 0+A \rightarrow A \)
r2*: \( A+0+B \rightarrow A+B \)
r3: \( -A+A \rightarrow 0 \)
r3*: \( A+(-B)+B \rightarrow A+0 \)
r4: \( -(-A) \rightarrow A \)
r5: \( -(0) \rightarrow 0 \)
r6: \( A*(B+C) \rightarrow A*B+A*C \)
r7: \( (A+B)*C \rightarrow A*C+B*C \)
r10: \( -(A+B) \rightarrow -A+(-B) \)
r12: \( A+0 \rightarrow 0 \)
r14: \( 0*A \rightarrow 0 \)
r16: \( (-A)*B \rightarrow -A*B \)
Huet and Hullot developed a method to prove inductive theorems without explicit induction \cite{Huet82} using a modified version of the Knuth-Bendix completion procedure. Their method is called inductionless induction and is effective for many theorems which usually require explicit induction.
In order to use the method, ground terms have to be classified into two categories, namely, \textit{constructor terms} which are always irreducible and constructed only of special function symbols called constructors, and \textit{non-constructor terms} which are always reducible and include a function symbol other than constructors. To prove an inductive theorem, we add the statement as an axiom and execute the completion procedure. The statement is an inductive theorem if the process succeeds to completion without yielding any rules to rewrite constructor terms.
Metis was given an ordinary definition of the append operation for two lists and two different definitions of the reverse operation of a list.
```
\textbf{[METIS]} \rightarrow \text{list rule}
\langle \text{state listing} \rangle
"-- append & reverse --"
\textbf{rules:}
\begin{align*}
r1: \quad \text{append}([],A) & \rightarrow A \quad [e3] \\
r2: \quad \text{rev}([],A) & \rightarrow A \quad [e5] \\
r3: \quad \text{reverse}([]) & \rightarrow [] \quad [e1] \\
r4: \quad \text{append}([A|B],C) & \rightarrow [A|\text{append}(B,C)] \quad [e4] \\
r5: \quad \text{rev}([A|B],C) & \rightarrow \text{rev}(B,[A|C]) \quad [e6] \\
r6: \quad \text{reverse}([A|B]) & \rightarrow \text{append}(\text{reverse}(B),[A]) \quad [e2]
\end{align*}
```
If we define \([\_\_\_]\) \textit{(cons)} and \([\_\_]\) \textit{(nil)} as the constructors, then the above conditions are satisfied. We added an equation \(\text{rev}(A,[]) = \text{reverse}(A)\) and had Metis execute the completion procedure.
```
\textbf{[METIS]} \rightarrow \text{kB INTERACTIVE}
\langle \text{Knuth - Bendix (interactive execution)} \rangle
\text{Current ruling formula [ CAN ] be oriented.}
\langle\langle\langle \langle\langle \text{e7: reverse(A) =(<>)= rev(A,[]) } \rangle \rangle \rangle \rangle
Which do you want to orient ?
[1] \quad \text{reverse(A) } \rightarrow \quad \text{rev(A,[])}
[2] \quad \text{reverse(A) } \leftarrow \quad \text{rev(A,[])}
\text{else exit}
Which ? 1
```
---
181
[ rev << reverse is asserted. ]
Current ruling formula is [ ORIENTED ].
New Rule is \( r7: \) reverse\((A) \rightarrow \text{rev}(A,[[]]) \)
DELETE\( r3 \)
DELETE\( r6 \)
Current ruling formula [ CAN ] be oriented.
\(<<<< e8: \text{rev}(A,[B]) =(<>)= \text{append}(\text{rev}(A,[]),[B]) \) \( >>>> \)
Which do you want to orient?
[1] \( \text{rev}(A,[B]) \rightarrow \text{append}(\text{rev}(A,[]),[B]) \)
[2] \( \text{rev}(A,[B]) \leftarrow \text{append}(\text{rev}(A,[]),[B]) \)
else exit
Which? 2
[ rev << append is asserted. ]
Current ruling formula is [ ORIENTED ].
New Rule is \( r8: \) \( \text{append}(\text{rev}(A,[]),[B]) \rightarrow \text{rev}(A,[B]) \)
Current ruling formula is [ ORIENTED ].
New Rule is \( r9: \) \( \text{append}(\text{rev}(A,[B]),[C]) \rightarrow \text{rev}(A,[B,C]) \)
Current ruling formula is [ ORIENTED ].
\(<<<< e10: \text{append}(\text{rev}(A,[B,C]),[D]) \approx>\text{rev}(A,[B,C,D]) \) \( >>>> \)
Since the current and the former ruling formulas suggested that a new lemma
\[ \text{append}(\text{rev}(A,B),C) = \text{rev}(A,\text{append}(B,C)) \]
would be useful, we added it.
\[ \text{METIS/KB} \rightarrow \text{new LEMMA} \]
\[ << \text{introduce a new lemma} >> \]
Lemma > \( \text{append}(\text{rev}(A,B),C) = \text{rev}(A,\text{append}(B,C)) \).
Current ruling formula is [ ORIENTED ].
New Rule is \( r10: \) \( \text{append}(\text{rev}(A,B),C) \rightarrow \text{rev}(A,\text{append}(B,C)) \)
DELETE\( r8 \)
DELETE\( r9 \)
Knuth - Bendix is terminated.
Your system is [ COMPLETE ].
The completion terminated and, therefore, both the target statement and the lemma inserted on the way were proved to be inductive theorems.
Several examples were taken from the theory of $\lambda$-calculus and combinators [Hindley 86, Barendregt 84]. In the theory of combinators, the combinator $K = \lambda X. Y$. $X$ and $S = \lambda X. Y. Z. X * Z * (Y * Z)$ (as usual we assume that symbols * standing for application of functions are left associative) are called basic combinators because all the $\lambda$-terms without free variables can be constructed from $S$ and $K$ only.
Example 4.2
It is well-known that the identity $I = \lambda X. X$ is represented by $S * K * K$. Metis was given the two axioms $K * X * Y = X$ and $S * X * Y * Z = X * Z * (Y * Z)$ for $K$ and $S$ to derive the identity. The problem can be expressed as $\exists I. \forall X. I * X = X$. Metis converted its negation to Skolemized form $A * \$1(A) \neq \$1(A)$ ($\$1$ is the so-called Skolem function).
```
[METIS] -> prove sSTRATEGY TERMINAL
<< prove formulas by S-strategy >>
Formula > some(I,all(X, I*X = X)).
Try to prove formula : A* \$1(A) =/= \$1(A)
Enter S-strategy...
Current ruling formula is [ INEQUATION ].
New Rule is r1: A* \$1(A) <-> $1(A)
Current ruling formula is [ ORIENTED ].
New Rule is r2: k*A*B -> A
Current ruling formula is [ INEQUATION ].
New Rule is r3: A <-> \$1(k*A)
Current ruling formula is [ NOT ] orientable.
New Rule is r4: s*A*B*C <-> A*C*(B*C)
Current ruling formula is [ ORIENTED ].
New Rule is r5: s*k*A*B -> B
$1(s*k*A) =/= \$1(s*k*A) [r5/r1] is a contradiction.
Then [ PROVED ].
```
—14—
The first ruling formula was the target formula $A \ast \mathcal{I}(A) \neq \mathcal{I}(A)$ and the second was the axiom for $K$, which was oriented left to right. The third formula was an extended narrowing from the first using the second, since $A = K \ast A \ast \mathcal{I}(K \ast A) \neq \mathcal{I}(K \ast A)$. The fourth was the axiom for $S$ which could not be oriented. The fifth was an extended critical pair between the fourth and the second, since $S \ast K \ast A \ast B = K \ast B \ast (A \ast B) = B$. Using this, a contradictory narrowing was obtained from the first ruling formula. By examining this process, we easily find all terms of the form $S \ast K \ast A$ are equal to the identity function, and $S \ast K \ast K$ is merely an instance of such terms.
Example 4.3
Next, we had Metis try to prove the fixed-point theorem, i.e. that there exists a fixed-point for any combinator, with the existence of the combinators $B = \lambda XYZ. X \ast (Y \ast Z)$ of composition of functions and $M = \lambda X. X \ast X$ of self-application, which are defined by $B = S \ast (K \ast S) \ast K$ and $M = S \ast I \ast I$. Metis was given the axioms $B \ast X \ast Y \ast Z = X \ast (Y \ast Z)$ and $M \ast X = X \ast X$. The theorem can be expressed as $\forall F.F \ast P \ast P = P$.
```
[METIS] -> list all
<< state listing >>
operators:
* / 2 ( lexicographic ordering left to right )
b / 0
m / 0
orderings:
No orderings
equations:
e1: m\ast A = A\ast A [axiom]
e2: b\ast A\ast B\ast C = A\ast (B\ast C) [axiom]
rules:
No rules.
```
```
[METIS] -> prove sstrategy terminal
<< prove equations by S-strategy >>
Equation > all(F,some(F,P, F\ast P = P )).
Try to prove equation : $1\ast A =/= A$
Enter S-strategy...
Current ruling formula is [ INEQUALITY ] .
New Rule is r1: $1\ast A <\text{-}/\text{-} A$
```
-15-
Current ruling formula is [ NOT ] orientable.
<<< e1: m*A = A*A >>>>
Since the above ruling formula could not be oriented, we let Metis introduce a new function symbol s and rewrite both A*A and M*A to s(A). Acquisition of the new function symbol and orientation of new equations was done interactively as follows:
[ METIS/PROVE/S-STRAt ] -> new function
<< introduce a new function >>
Operator?s
[ e3: m*A = s(A) (axiom) is asserted. ]
[ e4: A*A = s(A) (axiom) is asserted. ]
Current ruling formula [ CAN ] be oriented.
<<< e4: A*A =-(<>)= s(A) >>>>
[ METIS/PROVE/S-STRAt ] -> suggestion current
<< suggestion for ordering >>
Which do you want to orient?
[1] A*A -> s(A)
else exit
Which ? 1
[ s << * is asserted. ]
Current ruling formula is [ ORIENTED ].
New Rule is r2: A*A -> s(A)
Current ruling formula is [ ORIENTED ].
New Rule is r3: m*A -> s(A)
Current ruling formula is [ INEQUATION ].
New Rule is r4: s($1) <-> $1
Current ruling formula is [ ORIENTED ].
New Rule is r5: b*A*B*C -> A*(B*C)
Current ruling formula is [ ORIENTED ].
New Rule is r6: s(b)*A*B -> b*(A*B)
Current ruling formula is [ ORIENTED ].
New Rule is r7: s(b*A)*B -> A*(b*A*B)
-16-
Current ruling formula is [ ORIENTED ].
New Rule is \[ r8: \quad A \ast (B \ast (b \ast A \ast B)) \rightarrow s(b \ast A \ast B) \]
Current ruling formula is [ ORIENTED ].
New Rule is \[ r9: \quad s(s(b)) \ast A \rightarrow b \ast (s(b) \ast A) \]
Current ruling formula is [ INEQUATION ].
New Rule is \[ r10: \quad s(b \ast$1\ast A) \leftarrow \rightarrow A \ast (b \ast$1\ast A) \]
\[ e32: \quad s(b \ast$1\ast m) =/\iff s(b \ast$1\ast m) \quad [r3/r10] \text{ is a contradiction.} \]
Then [ PROVED ].
Metis finally found a contradictory inequation. The inequation was obtained by substituting $M$ to $A$ in r10 and rewriting the right hand side by r3. The inequation r10 was from r1 and r8, since
\[ s(B \ast$1\ast A) = $1 \ast (A \ast (B \ast$1\ast A)) \neq A \ast (B \ast$1\ast A). \]
and the rule r8 was from r2 and r5, since
\[ A \ast (B \ast (B \ast A \ast B)) = B \ast A \ast B \ast (B \ast A \ast B) = s(B \ast A \ast B). \]
Examining this process of refutation showed us that $m \ast (B \ast$1\ast m)$ is the value substituted to the original variable $A$ in the inequality obtained by the negation of the target formula. In fact, it is a fixed point of $1$, since
\[ M \ast (B \ast$1\ast M) = B \ast$1\ast M \ast (B \ast$1\ast M) = $1 \ast (M \ast (B \ast$1\ast M)) \]
REFERENCES
[Jouannaud 84] Jouannaud, J-P. and Kirchner, H.: Completion of a set of rules modulo a set of equations, 11th ACM POPL, 1984
|
{"Source-Url": "https://repository.kulib.kyoto-u.ac.jp/dspace/bitstream/2433/99856/1/0618-10.pdf", "len_cl100k_base": 11281, "olmocr-version": "0.1.53", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 82257, "total-output-tokens": 13210, "length": "2e13", "weborganizer": {"__label__adult": 0.00034165382385253906, "__label__art_design": 0.0006928443908691406, "__label__crime_law": 0.0004439353942871094, "__label__education_jobs": 0.003833770751953125, "__label__entertainment": 0.00016260147094726562, "__label__fashion_beauty": 0.00021588802337646484, "__label__finance_business": 0.0006127357482910156, "__label__food_dining": 0.000507354736328125, "__label__games": 0.0008287429809570312, "__label__hardware": 0.0011053085327148438, "__label__health": 0.0007348060607910156, "__label__history": 0.0005478858947753906, "__label__home_hobbies": 0.00022399425506591797, "__label__industrial": 0.0010328292846679688, "__label__literature": 0.0008511543273925781, "__label__politics": 0.0004489421844482422, "__label__religion": 0.0006809234619140625, "__label__science_tech": 0.46337890625, "__label__social_life": 0.000225067138671875, "__label__software": 0.01486968994140625, "__label__software_dev": 0.5068359375, "__label__sports_fitness": 0.0002818107604980469, "__label__transportation": 0.0007596015930175781, "__label__travel": 0.00021409988403320312}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39315, 0.04188]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39315, 0.80785]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39315, 0.849]], "google_gemma-3-12b-it_contains_pii": [[0, 448, false], [448, 2854, null], [2854, 5291, null], [5291, 8078, null], [8078, 10993, null], [10993, 13906, null], [13906, 16935, null], [16935, 20508, null], [20508, 23510, null], [23510, 25016, null], [25016, 26479, null], [26479, 27426, null], [27426, 29755, null], [29755, 31292, null], [31292, 32917, null], [32917, 34776, null], [34776, 35960, null], [35960, 37942, null], [37942, 39315, null]], "google_gemma-3-12b-it_is_public_document": [[0, 448, true], [448, 2854, null], [2854, 5291, null], [5291, 8078, null], [8078, 10993, null], [10993, 13906, null], [13906, 16935, null], [16935, 20508, null], [20508, 23510, null], [23510, 25016, null], [25016, 26479, null], [26479, 27426, null], [27426, 29755, null], [29755, 31292, null], [31292, 32917, null], [32917, 34776, null], [34776, 35960, null], [35960, 37942, null], [37942, 39315, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39315, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39315, null]], "pdf_page_numbers": [[0, 448, 1], [448, 2854, 2], [2854, 5291, 3], [5291, 8078, 4], [8078, 10993, 5], [10993, 13906, 6], [13906, 16935, 7], [16935, 20508, 8], [20508, 23510, 9], [23510, 25016, 10], [25016, 26479, 11], [26479, 27426, 12], [27426, 29755, 13], [29755, 31292, 14], [31292, 32917, 15], [32917, 34776, 16], [34776, 35960, 17], [35960, 37942, 18], [37942, 39315, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39315, 0.021]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
424018f3639ce3254de952e8cf7d3711d24acfd3
|
An Assertional Characterization of Serializability
E. Robert McCurley and Fred B. Schneider
Serializability is usually defined operationally in terms of sequences of operations. This paper gives another definition of serializability—in terms of sequences of states. It also shows how this definition can be used to prove correctness of solutions to the concurrency control problem.
An Assertional Characterization of Serializability*
E. Robert McCurley
School of Information and Computer Science
Georgia Institute of Technology
Atlanta, Georgia 30332
Fred B. Schneider
Department of Computer Science
Cornell University
Ithaca, New York 14853
September 28, 1989
Abstract
Serializability is usually defined operationally in terms of sequences of operations. This paper gives another definition of serializability—in terms of sequences of states. It also shows how this definition can be used to prove correctness of solutions to the concurrency control problem.
1 Introduction
A database system is a computer system that stores information. Consistency constraints restrict system states to those that are meaningful; transactions are designed so that each individually transforms the database from
*This material is based on work supported in part by the Office of Naval Research under contract N00014-86-K-0092, the National Science Foundation under Grant No. CCR-8701103, and Digital Equipment Corporation. Any opinions, findings, and conclusions or recommendations expressed in this publication are those of the authors and do not reflect the views of these agencies.
one consistent state to another. For example, in a database for a banking application, a consistency constraint might relate cash-on-hand to the sum of the account balances; a transaction for a deposit would adjust both an account balance and cash-on-hand, preserving the consistency constraint.
During concurrent execution of transactions, operations can interleave in ways that leave the database in an inconsistent state. Avoiding such states is called the concurrency control problem. The traditional solution to this problem is based on serializability [EGLT76], which asserts that transactions executing concurrently "behave like" they are run serially, one after another. If, when run in isolation, each transaction transforms the database from one consistent state to another and if transactions are serializable, then concurrent execution of those transactions will also transform the database from one consistent state to another. Thus, implementing serializability solves the concurrency control problem.
Serializability is usually defined (operationally) in terms of sequences, called schedules, that list operations in the order they run. This would seem to preclude use of programming methodologies based on assertions about states—so called assertional reasoning. It is tempting to regard this as a fundamental limitation of such methodologies. In this paper, we show this view to be erroneous. We give an assertional characterization of serializability and show how this definition can be used to prove correctness of solutions to the concurrency control problem.
We proceed as follows. In Section 2, we present a database system model and give a formal definition of serializability. Two ways to specify serializability using formulas of a Hoare-style programming logic are given in Section 3. In Section 4, we discuss possible extensions to our database system model and their implications. We conclude, in Section 5, with a comparison of our definition and previous ones.
2 Serializability
2.1 System Model
A database system $\Sigma$ can be represented by a triple $(V, C, T)$, where $V$ is a set of variables, $C$ is a predicate on $V$, and
$$T: [\tau_0 \parallel \ldots \parallel \tau_{N-1}]$$
is a concurrent program in which each transaction $\tau_i$ is a program that references only variables of $V$.
Variables in $V$ represent the state of the database, including but not limited to the part that actually contains application data.\(^1\) $C$ is the consistency constraint of the database. A state is consistent iff $C$ is true in that state. Each transaction $r_i$ is assumed to terminate in a consistent state when run alone starting in one.
An example of a database system is given in Figure 1. $\Sigma_0$ models a database that maintains an unordered collection of records, represented by variable $s$ of type set. Variables $i_{n_0}, \ldots, i_{N-1}$ are sequences, containing records that have or will be inserted into $s$, and consistency constraint $C_0$ requires $s$ to contain a subset of these. Each transaction $Add_i$ adds the records of $i_n$ to $s$. Variable $t_i$ of $Add_i$ is local to the transaction, hence excluded from $V_0$. In the guard of the loop, $|i_n|$ denotes the length of the sequence $i_n$. Angle brackets "(" and ")" surround operations that execute atomically.
$$\Sigma_0 = \langle V_0: s, i_{n_0}, \ldots, i_{N-1}, C_0: s \subseteq (i_{n_0} \cup \ldots \cup i_{N-1}), T_0: \{Add_0 || \ldots || Add_{N-1}\} \rangle$$
$$Add_i: \langle t_i := 0; \rangle$$
$$\text{do } t_i \neq |i_n| \rightarrow$$
$$\langle s := s \cup i_n(t_i); \rangle$$
$$\langle t_i := t_i + 1 \rangle$$
$$\text{od}$$
Figure 1: Database System $\Sigma_0$.
2.2 Serializability
Serializability of $\Sigma = \langle V, C, T \rangle$ can be understood in terms of an abstract database system $\Sigma' = \langle V', C', T' \rangle$ where $V'$ and $C'$ are the same as $V$ and $C$ of $\Sigma$, and
$$T': \tau_0' || \ldots || \tau'_{N-1},$$
is the concurrent program in which each $\tau'_i$ is $\langle \tau_i \rangle$, a transaction that executes the same operations as $\tau_i$ but as a single atomic operation. Executions
\(^1\)A commit flag is an example of an element of $V$ that does not contain application data.
of $T'$ are serial, meaning that transactions are executed one after another without interleaving.
Recall that serializability asserts that every (potentially interleaved) execution of $T$ "behaves like" some (serial) execution of $T'$. Since if one system $T$ implements another one $T'$, then every behavior of $T$ can be viewed as a behavior of $T'$, serializability of $T$ is equivalent to $T$ implementing $T'$ [Lam88].
2.3 Defining "Implements"
In [Pri87, GP85], a formal definition in terms of predicate transformers is given for when one program implements another. This definition is a generalization of that presented in [Hoa72] and can be summarized as follows. Let $S'$ be a program operating on variables $X$, and let $P$ be a predicate on $X$ such that $S'$ is guaranteed to terminate when run in an initial state satisfying $P$. Let $S$ be a program on variables $Y$ (disjoint from $X$), which is intended to implement $S'$.
Programs $S'$ and $S$ are called the abstract and concrete programs, respectively. The correspondence between the states of these programs is represented by a predicate $I$ on $X$ and $Y$, called a coupling invariant. It often takes the form $X = F(Y)$, where $F$ is a function that maps any state of $S$ to the state of $S'$ that it implements.
The property that $S$ implements $S'$ is formalized as
$$(P \land I) \Rightarrow wp(S, wp^*(S', I)).$$
Here, $wp(S, R)$ denotes the weakest precondition of $S$ with respect to $R$ [Dij76], the set of states in which any execution of $S$ is guaranteed to terminate in a state satisfying $R$, and $wp^*(S', R)$ denotes the angelic weakest precondition of $S'$ with respect to $R$, the set of states in which some execution of $S'$ will terminate in a state satisfying $R$.$^{2}$ Thus, (2) specifies a correspondence between the effect of concrete program $S$ and that of the abstract program $S'$, when both programs are viewed as predicate transformers. In particular, (2) asserts that concrete program $S$ changes its variables in a way that is consistent—as defined by $I$—with some execution of the abstract program it implements.
$^{2}$The relationship between $wp$ and $wp^*$ is as follows:
$$wp(S, \text{true}) \Rightarrow (wp^*(S, R) \iff \neg wp(S, \neg R)).$$
For deterministic $S$, $wp(S, R) \Rightarrow wp^*(S, R)$.
4
2.4 Serializability as "Implements"
Serializability of $\Sigma = (V, C, T)$ can be formalized in terms of $\Sigma' = (V', C', T')$ using (2) by taking $T'$ of (1) to be the abstract program and $T$ to be the concrete program. To do so, however, variables $V'$ in $C'$ and $T'$ must be replaced by fresh variables $v'_0, \ldots, v'_{M-1}$ disjoint from $V$. Henceforth, we assume that $V$ and $V'$ are disjoint.
For $P$ in (2) we take $C'$ and for $I$ we take $\bigwedge_{v \in V} v = v'$ giving the following characterization of serializability.
Definition: $\Sigma$ is serializable if and only if
\[ (C' \land \bigwedge_{v \in V} v = v') \Rightarrow wp(T, wp^*(T', \bigwedge_{v \in V} v = v')). \]
(3)
Some simplification of (3) is possible. Since $T_0, \ldots, T_{N-1}$ run serially in $T'$, any execution of $T'$ will be equivalent to some execution of a sequential program $\rho$ in the set
$S(T')$: \{ $\phi_0; \ldots; \phi_{N-1}$ | $\phi_i$ is a transaction of $T'$, $0 \leq i < N$ $\}$.
Thus, for any predicate $R$,
$$wp^*(T', R) \iff \bigvee_{\rho \in S(T')} wp^*(\rho, R).$$
(4)
Substituting the right-hand side of (4) into (3) gives the equivalent formula
\[ (C' \land \bigwedge_{v \in V} v = v') \Rightarrow wp(T, \bigvee_{\rho \in S(T')} wp^*(\rho, \bigwedge_{v \in V} v = v')). \]
(5)
When transactions of $T'$ are deterministic, (3) can be further simplified. Each $\rho \in S(T')$ is now deterministic. Since $wp$ and $wp^*$ are equivalent for deterministic programs, (5) is equivalent to
\[ (C' \land \bigwedge_{v \in V} v = v') \Rightarrow wp(T, \bigvee_{\rho \in S(T')} wp(\rho, \bigwedge_{v \in V} v = v')). \]
(6)
3 Proof Techniques for Serializability
3.1 Hoare's Logic
Verifying that a database system $\Sigma$ satisfies any of (3), (5) or (6) presents a difficult problem: the weakest precondition of a concurrent program such
as \( T \) is a complicated predicate that is difficult to evaluate. Hoare's logic [Hoa69] provides an alternative and often more tractable formalism for reasoning about concurrent programs. A \textit{triple} is a formula
\[
\{P\}S\{Q\}
\]
(7)
where \( S \) is a program and \( P \) and \( Q \) are predicates on variables of \( S \). Predicates \( P \) and \( Q \) are called \textit{assertions} with \( P \) designated the \textit{precondition} and \( Q \) the \textit{postcondition} of \( S \).
The triple (7) has the following interpretation:
If execution of \( S \) begins in a state satisfying \( P \) and \( S \) terminates, then the state reached will satisfy \( Q \).
Since this interpretation implies nothing about the termination of \( S \), a triple specifies \textit{partial correctness}. Axioms and inference rules of Hoare's logic for a simple sequential programming language can be found in [Hoa69]. Additional axioms and rules for concurrent programs are given in [OG76].
### 3.2 Effective Criteria Serializability
The relationship between a triple and \( wp \) is
\[ Q \Rightarrow wp(S, R) \text{ iff } \{Q\}S\{R\} \text{ and } \text{term}(S, Q) \]
(8)
for any predicates \( Q \) and \( R \) and any program \( S \), where \( \text{term}(S, Q) \) specifies that \( S \) is guaranteed to terminate when started in a state satisfying \( Q \). Thus, our definition of serializability in Section 2.4 and formulas (3), (5) and (6) imply the following theorem and corollary.
**Theorem 1** Let \( \Sigma = (V, C, T) \) be a database system and \( \Sigma' \) a corresponding abstract system. \( \Sigma \) is serializable if and only if
\begin{align*}
T1.1: & \quad \{C' \land \bigwedge_{v_i \in V} v_i = v_i'\}T \{ \bigvee_{\rho \in S(T')} wp^*(\rho, \bigwedge_{v_i \in V} v_i = v_i')\}, \\
T1.2: & \quad \text{term}(T, C' \land \bigwedge_{v_i \in V} v_i = v_i').
\end{align*}
**Corollary 2** If the transactions of \( T' \) are deterministic, then \( \Sigma \) is serializable if and only if
\[ wp(S, R) \Rightarrow \{Q\}S\{R\} \text{ and } \text{term}(S, Q) \]
The conditions of Theorem 1 and Corollary 2 provide effective criteria for verifying—using assertional reasoning—serializability of database systems. Validity of T1.1 and C2.1 can be established using the logic of [OG76]; validity of T1.2 and C2.2 can be established using temporal logic [Pnu81, MP81].
3.3 An Example
Returning to the example of Figure 1, note that transactions of $\Sigma_0'$ are deterministic since those of $\Sigma_0$ are. Thus, Corollary 2 can be used to verify serializability of $\Sigma_0$ as follows. We first prove condition C2.1,
$$\{ C'_0 \land \bigwedge_{i=1}^N \psi_i = \psi'_i \} \land \bigvee_{\rho \in \mathcal{S}(T'_0)} wp(\rho, \bigwedge_{i=1}^N \psi_i = \psi'_i).$$
We abbreviate the formal proof of (9) with the following proof outline [OG76]:
$$\{ C'_0 \land s = s' \land (\forall i: 0 \leq i < N: \Delta_i = 0) \}
\{ I0 \land (\forall i: 0 \leq i < N: \Delta_i = 0) \}
\{ [PO(Add_0)] || ... || [PO(Add_N)] \}
\{ I0 \land (\forall i: 0 \leq i < N: \Delta_i = 0) \}
\{ \bigvee_{\rho \in \mathcal{S}(T'_0)} wp(\rho, \bigwedge_{i=1}^N \psi_i = \psi'_i) \}
Here, each $PO(Add_i)$ is the proof outline shown in Figure 2 below, and
$$I0: (\forall i: 0 \leq i < N: \Delta_i = 0) \land (\forall i: 0 \leq i < N: \Delta_i = 0) \land (\forall i: 0 \leq i < N: \Delta_i = 0)$$
is an assertion that remains true throughout execution of $T_0$. Variables $\Delta_0, ..., \Delta_{N-1}$ are auxiliary variables [OG76, McC89]. They have type set and represent the difference between $s$ and $s'$. Since they are used for purposes of proof only, they need not be implemented.
In verifying serializability of $\Sigma_0$, we next prove condition C2.2 of Corollary 2—that $T_0$ terminates when started in a state satisfying $C'_0 \land \bigwedge_{i=1}^N \psi_i = \psi'_i$.
\{I0 \land \Delta_i = \emptyset\}
\langle t_i := 0\rangle;
\{I0 \land 0 \leq t_i \leq |in_i| \land \Delta_i = in_i(0..t_i-1)\}
do \ t_i \neq |in_i| \rightarrow
\{I0 \land 0 \leq t_i < |in_i| \land \Delta_i = in_i(0..t_i-1)\}
\langle s, \Delta_i := s \cup in_i(t_i), \Delta_i \cup in_i(t_i)\rangle;
\{I0 \land 0 \leq t_i < |in_i| \land \Delta_i = in_i(0..t_i)\}
\langle t_i := t_i + 1\rangle
\{I0 \land 0 \leq t_i \leq |in_i| \land \Delta_i = in_i(0..t_i-1)\}
od
\{I0 \land \Delta_i = in_i\}
Figure 2: \textit{PO(Add_i)}
\nu'. Since the loop in each \textit{Add_i} executes exactly \(|in_i|\) iterations, \textit{Add_i} executes a bounded number of operations, each of which is an assignment that is guaranteed to terminate. Consequently, each \textit{Add_i} terminates, and it follows that \textit{T_0} terminates.
By Corollary 2, therefore, \Sigma_0 is a serializable database system. Notice that an explicit concurrency control mechanism was not needed to achieve this serializability, even though transactions shared access to variable \(s\). This, then, illustrates how our work can be used to prove correctness of solutions to the concurrency control problem when the semantics of individual transactions contribute to the solution.
The preceding example is misleading. Although effective, the criteria given by Theorem 1 and its corollary are not practical for verifying serializability of a database system. For all but the simplest database systems, the assertions used will be too large for a proof of TI.1 or C2.1 to be tractable, due to the number and complexity of serial executions \(\rho \in S(T')\). For example, consider the database system \Sigma_1 of Figure 3. \Sigma_1 is obtained from \Sigma_0 by adding variables \text{out}_0, \ldots, \text{out}_{N-1} and transactions \text{List}_0, \ldots, \text{List}_{N-1} that write the contents of \(s\) to these variables. The consistency constraint has been strengthened to require that contents written by a \text{List} transaction contain all or none of the elements being added by an \text{Add} transaction. This has made it necessary to synchronize transactions in order to prevent listing \(s\) when only part of some \(in_i\) has been added. Synchronization is accomplished using locking [KS79, Kor83]. Transactions synchronize by acquiring
and releasing a lock, which can have either shared or exclusive mode, denoted by S and X, respectively. An X-lock is incompatible with other locks, so a transaction attempting to acquire either an S-lock or an X-lock will block until no other transaction holds an X-lock. To ensure that transactions terminate when run in isolation, the consistency constraint requires that transactions hold no locks initially. We denote the fact that a transaction \( \tau_i \) holds an \( M \)-lock by the predicate \( locked(\tau_i, M) \).
Corollary 1 requires
\[
\{ C'_1 \land \bigwedge_{v_i \in V_i} v_i = v'_i \} \ T_1 \{ \bigvee_{\rho \in \mathcal{S}(T'_1)} \ wp(\rho, \bigwedge_{v_i \in V_i} v_i = v'_i) \}
\]
to be valid. In the postcondition of the analogous triple (9) for \( T_0 \), all disjuncts \( wp(\rho, \bigwedge_{v_i \in V_0} v_i = v'_i) \) were equivalent. For \( \Sigma_1 \) of Figure 3, the number of different disjuncts will be exponential in \( N \), making it painful to verify.
### 3.4 Simpler Criteria for Serializability
When transactions are deterministic (as they are in \( \Sigma_0 \) and \( \Sigma_1 \)), simpler criteria for serializability can be formulated by promoting abstract transactions from their passive role in the postcondition of C2.1 to a more active
---
3 The semantics of operations on \( s \) have allowed shared-mode locks to be used in transactions \( Add_i \), even though they modify \( s \).
one. Let \( \tau \) be a transaction of \( \Sigma \) and let \( \tau' \) be the corresponding transaction of an abstract system for \( \Sigma \). An augmentation of \( \tau \) is a program \( \tau^* \) obtained by substituting \( (\alpha; \tau') \) for some atomic operation \( \alpha \) that runs exactly once in any terminating execution of \( \tau \). An augmentation of \( T \) is a program
\[
T^* : [\tau_0^* \parallel \cdots \parallel \tau_{N-1}^*]
\]
in which each \( \tau_i^* \) is an augmentation of \( \tau_i \). The following theorem shows that serializability can be characterized using triples for augmentations.
**Theorem 3** Let \( \Sigma = (V, C, T) \) be a database system with deterministic transactions and let \( \Sigma' = (V', C', T') \) be an abstract system for \( \Sigma \). Let \( T^* \) be an augmentation of \( T \) using transactions of \( T' \). \( \Sigma \) is serializable if
\[
T3.1: \{ C' \land \bigwedge_{v_i \in V} v_i = v'_i \} \; T^* \{ \bigwedge_{v_i \in V} v_i = v'_i \},
\]
\[
T3.2: \text{term}(T, C' \land \bigwedge_{v_i \in V} v_i = v'_i).
\]
**Proof** Due to Corollary 2, it suffices to show that conditions T3.1 and T3.2 imply C2.1 and C2.2. Since T3.2 and C2.2 are identical, it suffices to show T3.1 and T3.2 imply C2.1.
Assume T3.1 holds and consider a terminating execution of \( T \) that starts in a state satisfying the precondition of C2.1. Any such execution can be formally represented by a history of the form
\[
\sigma: \; s_0 \overset{\alpha_1}{\rightarrow} s_1 \overset{\alpha_2}{\rightarrow} s_2 \cdots s_{M-1} \overset{\alpha_M}{\rightarrow} s_M,
\]
where \( s_0 \) is the initial state, and \( s_{i-1} \overset{\alpha_i}{\rightarrow} s_i \) denotes that atomic action \( \alpha_i \) transforms state \( s_{i-1} \) to state \( s_i \). To show that C2.1 is valid, it suffices to show that \( s_M \) satisfies the postcondition of C2.1.
For any execution \( \sigma \) of \( T \), the construction of \( T^* \) implies that there is a corresponding history
\[
\sigma^*: \; s_0^* \overset{\alpha_1^*}{\rightarrow} s_1^* \overset{\alpha_2^*}{\rightarrow} s_2^* \cdots s_{M-1}^* \overset{\alpha_M^*}{\rightarrow} s_M^*
\]
of \( T^* \) in which \( s_0^* = s_0 \) and \( \alpha_i^* \) is either \( \alpha_i \) or \( (\alpha_i; \tau') \), where \( \tau' \) is the abstract transaction used to form the \( \tau^* \) that contains \( \alpha_i^* \). Validity of T3.1 implies that \( s_M^* \) satisfies \( \bigwedge_{v_i \in V} v_i = v'_i \).
Since \( V \) and \( V' \) are disjoint, the abstract transactions in \( \sigma^* \) can be pulled from their atomic operations and permuted with operations \( \alpha_i \), to obtain a history
\( \sigma': s'_0 \xrightarrow{a_1} s'_1 \xrightarrow{a_2} s'_2 \ldots s'_{M-1} \xrightarrow{\alpha} s'_M \xrightarrow{\tau'_0} s'_{M+1} \ldots s'_{M+N-1} \xrightarrow{\tau'_{N-1}} s'_{M+N} \)
of \( T \) followed by \( T' \) in which \( s'_0 = s_0 \), \( s'_{M+N} = s'_M \) and \( \tau'_0, \ldots, \tau'_{N-1} \) are the abstract transactions of \( T' \) in the order they appear in \( \sigma' \).
Transactions are assumed to be deterministic, and the subsequence of \( \sigma' \) from \( s'_0 \) to \( s'_M \) has the same initial state and operations as the original execution sequence \( \sigma \). Consequently, \( s'_M = s_M \). The subsequence of \( \sigma' \) from \( s'_M \) to \( s'_{M+N} \) is one of the \( \rho \in S(T') \). Since \( s'_{M+N} = s'_M \) satisfies \( \bigwedge_{v_i \in V} v_i = v'_i \), \( s'_M \) satisfies \( wp(\rho, \bigwedge_{v_i \in V} v_i = v'_i) \), from which it follows that \( s_M \) satisfies the postcondition of \( C_2.1 \).
The conditions given by Theorem 3 are simpler to verify than those of Theorem 2 or Corollary 2, due to shorter assertions in the proof of \( T3.1 \). However, this simplicity has been acquired at the expense of completeness. The conditions of Theorem 1 and its corollary are equivalent to serializability, while those of Theorem 3 only imply it. An example of a serializable database system for which \( T3.1 \) cannot be proven is given in [McC88].
### 3.5 Example Revisited
Theorem 3 can be used to prove \( \Sigma_1 \) of Figure 3 serializable, as follows. The following augmentations of each \( Add_i \) and \( List_i \) are used:
- **Add\(_i^*\):**
\[
\begin{align*}
\langle \text{lock}(S) \rangle; \\
\langle t_i := 0 \rangle; \\
\text{do } t_i \neq \lvert \text{in}_i \rvert \rightarrow \langle s := s \cup \text{in}_i(t_i) \rangle; \\
\langle t_i := t_i + 1 \rangle \\
\text{od}; \\
\langle \text{unlock}(S); \text{Add}_i' \rangle
\end{align*}
\]
- **List\(_i^*\):**
\[
\begin{align*}
\langle \text{lock}(X) \rangle; \\
\langle \text{out}_i := s; \text{List}_i' \rangle; \\
\langle \\text{unlock}(X) \rangle
\end{align*}
\]
We first prove \( T3.1 \),
\[
\{ C'_1 \land \bigwedge_{v_i \in V} v_i = v'_i \} T_1^* \{ \bigwedge_{v_i \in V} v_i = v'_i \},
\]
using the proof outline
\{ C'_1 \land \land_{v_i \in V_i} v_i = v'_i \} \\
(\Delta_0, \ldots, \Delta_{N-1} := 0, \ldots, 0) \\
\{ I_1 \land (\forall i: 0 \leq i < N: \Delta_i = 0) \} \\
[PO(Add'_0) || \ldots || PO(Add'_{N-1})] \\
[PO(List'_0) || \ldots || PO(List'_{N-1})] \\
\{ I_1 \land (\forall v_i: 0 \leq i < N: \Delta_i = 0) \} \\
\{ \land_{v_i \in V_i} v_i = v'_i \} \\
In (11), PO(Add'_*), and PO(List'_*) are the proof outlines shown in Figures 4 and 5, and I1 is
\begin{align*}
&I0 \\
&\land (\forall i: 0 \leq i < N: out_i = out'_i) \\
&\land (\forall i: 0 \leq i < N: \Delta_i \neq 0 \Rightarrow locked(Add_i, S)) \\
&\land (\forall i, j: 0 \leq i, j < N: -(locked(Add_i, S) \land locked(List_j, X))) \\
&\land (\forall i, j: 0 \leq i \neq j < N: -(locked(List_i, X) \land locked(List_j, X)))
\end{align*}
Auxiliary variables \( \Delta_0, \ldots, \Delta_{N-1} \) play the same role here as in the previous example. The proof of (11) is straightforward and is omitted here.
Condition T3.2 requires T1 to terminate when started in a state satisfying \( C'_1 \land \land_{v_i \in V_i} v_i = v'_i \). The argument for this is analogous to that used to prove termination of \( \Sigma_0 \) except for the possibility of deadlock introduced by the addition of locking. Deadlock is impossible, however, since locking is two-phase [EGLT76].
### 4 Extensions
#### 4.1 Modes of Termination
The database system model presented in Section 2.1 ignores certain aspects of actual database systems. One of these is the potential for transactions to abort. An aborting transaction typically executes a recovery protocol in which operations are run that undo the effects of its changes to the database, thereby giving the effect that it never ran.
We can incorporate this mode of transaction termination into our system model by including in each transaction \( \tau_i \) an operation modeling its recovery protocol and including in \( V \) a Boolean variable commit, initially false, that \( \tau_i \) sets to true if and only if it terminates without executing its recovery protocol. This change in the system model necessitates a change in the
\{ I_i \land \Delta_i = \emptyset \land \neg locked(Add_i,S) \} \\
(\text{lock}(S)); \\
\{ I_i \land \Delta_i = \emptyset \land locked(Add_i,S) \} \\
( t_i := 0); \\
\{ I_i \land 0 \leq t_i \leq |in_i| \land \Delta_i = in_i(0...t_i-1) \land locked(Add_i,S) \} \\
\text{do} t_i \neq |in_i| \rightarrow \\
\{ I_i \land 0 \leq t_i < |in_i| \land \Delta_i = in_i(0...t_i-1) \land locked(Add_i,S) \} \\
( s, \Delta_i := s \cup in_i(t_i), \Delta_i \cup in_i(t_i)); \\
\{ I_i \land 0 \leq t_i < |in_i| \land \Delta_i = in_i(0...t_i) \land locked(Add_i,S) \} \\
( t_i := t_i + 1) \\
\{ I_i \land 0 \leq t_i \leq |in_i| \land \Delta_i = in_i(0...t_i-1) \land locked(Add_i,S) \} \\
\text{od}; \\
\{ I_i \land \Delta_i = in_i \land locked(Add_i,S) \} \\
(\text{unlock}(S); \Delta_i := \emptyset; Add'_i) \\
\{ I_i \land \Delta_i = \emptyset \land \neg locked(Add_i,S) \} \\
Figure 4: \text{PO}(Add'_i)
definition of serializability as well. Our definition specifies in (3) that every execution of \( T \) corresponds to some execution of \( T' \). However, there can be executions of \( T \) in which transactions abort for reasons that are not encountered in a serial execution (e.g., deadlock), and no execution of \( T' \) will correspond to these.
This problem is circumvented by choosing
\( T'': [\tau'_0 || ... || \tau'_{N-1}] \)
as the abstract concurrent program for \( \Sigma' \) (instead of \( T' \)), where each transaction
\( \tau''_i: \text{\texttt{\{if true \rightarrow \tau'_i||true \rightarrow \text{skip}\}}})
executes one of \( \tau'_i \) or \text{skip} when run, the choice being made nondeterministically. If \text{skip} is selected, all variables, including \text{commit}'_i, will be left unchanged, giving the same effect as if \( \tau'_i \) ran but aborted. Every execution in \( S(T'') \) will now be equivalent to some serial execution \( p \) in the set
\( SS(T'):: \{ \phi_0;...;\phi_{k-1} | 0 \leq k \leq N, \phi_i \text{ is a transaction of } T', 0 \leq i < k \} \).
There are several consequences of replacing $T'$ by $T''$. One is that $S(T')$ must be replaced by $SS(T')$ in (5) and formulas derived from it. Consequently, an implementation of $\Sigma$ that aborts every transaction will be serializable under our definition, violating constraints on transaction progress that are often assumed of databases. This can be avoided by specifying these constraints in addition to serializability.
Another consequence of using abstract transactions of $T''$ is that even when transactions of $T$ are deterministic, those of $T''$ are not, and consequently cannot be used in augmentations to prove serializability as described in Section 3.4. Transactions of $T'$ can still be used in augmentations, however, as long as each $r'_i$ is restricted to positions where it runs if and only if $\tau_i$ commits. The proof of Theorem 3 is virtually unchanged by this restriction, guaranteeing that serializability is still ensured by conditions T3.1 and T3.2.
4.2 Views
In our definition of serializability, the choice of the coupling invariant reflects an implicit assumption that transaction behavior is characterized by the entire system state. This may be too strong. Parts of the state of a real database system will be invisible to users of the system and need not be included when considering behavior. For example, the set $s$ of database $\Sigma_1$ might be implemented using an array $a$ that stores elements in contiguous locations. The order of elements in this array should not be considered when determining whether or not execution is serializable.
The visible aspects of the database system state are an abstraction of the system state. This can be modeled by using a function on system states that
maps indistinguishable states to a common abstract representation. We call such a function a \textit{view function}. We can incorporate a view function $f$ into our definition of serializability by replacing the original coupling invariant $\bigwedge \forall i \in V \; v_i = v_i'$ by $\bigwedge \forall i \in V \; f(v_i) = f(v_i')$ in (3), together with formulas derived from it.
5 Discussion
We have defined serializability in terms of concurrent execution of transactions implementing serial execution. By choosing an assertional characterization of "implements", serializability was expressed using Hoare's logic. This makes it possible to verify concurrency control mechanisms using that logic.
There are many other definitions of serializability \cite{Pap86}. What most of these definitions have in common is that serializability is defined as a property of system \textit{schedules}, sequences of operations resulting from particular system executions. Schedule-based definitions of serializability fall into two broad categories based on how schedule behavior is characterized: \textit{state based} and \textit{conflict based}.
In state-based definitions, system behavior is described in terms of how schedules transform one state to another. Definitions differ with respect to the parts of the state considered significant. A schedule is \textit{final-state serializable} if it and some serial schedule transform identical initial states to final states that agree on the value of all shared variables. A schedule is \textit{view serializable} if the final states agree on the values obtained by read operations as well. Both final-state and view serializable schedules can be expressed by our definition of serializability by suitable choice of system variables.
Conflict-based definitions of serializability describe behavior somewhat indirectly, using \textit{conflict relations} (also known as \textit{dependency relations}) on operations of the schedule. An operation $\alpha_1$ \textit{conflicts} with another operation $\alpha_2$ in the same schedule (written $\alpha_1 < \alpha_2$) if (i) the operations are from different transactions, (ii) $\alpha_1$ precedes $\alpha_2$, and (iii) $\alpha_1$ and $\alpha_2$ do not commute with each other (i.e., the same initial state can produce different final states when the operations are run in different orders). The conflict relation on operations is extended to one on transactions. This, then, is used to determine the set of serial schedules exhibiting the same behavior: a schedule is \textit{conflict serializable} if it and some serial schedule have the same conflict relation on transactions.
Because schedule-based definitions of serializability consider operation sequences and system states independently, some database systems considered serializable under our definition are not considered serializable by the schedule-based definitions above. The (somewhat contrived) database system $E_2$ of Figure 6 is an example. There, variables $x$, $y$, and $out$ hold integer values, while $b$ holds a binary value. Transaction $UpdateXY$ subtracts 17 from $y$ and adds it to $x$, using the value of $b$ to control the order in which this occurs. ($\overline{b}$ denotes the complement of $b$.) Using the techniques of Section 3, it is not difficult to prove $E_2$ serializable according to our definition.
Consider the schedule
$$\alpha_0;\beta_0;\alpha_1.$$ (12)
Note that the value read by $ListX$ depends on the state in which execution begins: $out$ gets the same value as it does from the serial schedule $\alpha_0;\alpha_1;\beta_0$ if $b = 1$ initially, while $out$ gets the same value as from $\beta_0;\alpha_0;\alpha_1$ if $b = 0$. Thus, schedule (12) is neither final-state nor view serializable since these require (12) to "behave like" one of the serial schedules for all initial states. Nor is (12) conflict serializable, since the conflict relation on $UpdateXY$ and $ListX$ has a cycle. Thus, although $E_2$ is serializable according to our definition, it is not serializable by the schedule-based definitions of serializability.
In [Cas81], a definition of serializability similar to ours is given. This definition uses operators of Concurrent Dynamic Logic (CDL) instead of weakest preconditions to express the "implements" relationship between $T$ and its serial model $T'$. Our definition is more general than the CDL definition, however, because the coupling invariant can be written in terms of a view function. Our definition also provides more useful criteria for verifying serializability, since Hoare's logic offers a variety of formal techniques for deriving and verifying triples that CDL currently lacks.
Acknowledgment
David Gries and Phil Hutto read and provided helpful comments on an earlier version of this paper.
References
|
{"Source-Url": "http://www.dtic.mil/dtic/tr/fulltext/u2/a213323.pdf", "len_cl100k_base": 9536, "olmocr-version": "0.1.53", "pdf-total-pages": 19, "total-fallback-pages": 0, "total-input-tokens": 50855, "total-output-tokens": 11494, "length": "2e13", "weborganizer": {"__label__adult": 0.00042724609375, "__label__art_design": 0.0003185272216796875, "__label__crime_law": 0.0005936622619628906, "__label__education_jobs": 0.0013818740844726562, "__label__entertainment": 7.456541061401367e-05, "__label__fashion_beauty": 0.00019788742065429688, "__label__finance_business": 0.0003814697265625, "__label__food_dining": 0.00045418739318847656, "__label__games": 0.0007681846618652344, "__label__hardware": 0.0011920928955078125, "__label__health": 0.0011234283447265625, "__label__history": 0.0003421306610107422, "__label__home_hobbies": 0.0001398324966430664, "__label__industrial": 0.0006566047668457031, "__label__literature": 0.0004477500915527344, "__label__politics": 0.0003757476806640625, "__label__religion": 0.0006346702575683594, "__label__science_tech": 0.089111328125, "__label__social_life": 0.00010865926742553712, "__label__software": 0.007114410400390625, "__label__software_dev": 0.892578125, "__label__sports_fitness": 0.0003542900085449219, "__label__transportation": 0.0009160041809082032, "__label__travel": 0.00022280216217041016}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35483, 0.03754]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35483, 0.655]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35483, 0.83451]], "google_gemma-3-12b-it_contains_pii": [[0, 384, false], [384, 1580, null], [1580, 3916, null], [3916, 5841, null], [5841, 8167, null], [8167, 10036, null], [10036, 12124, null], [12124, 13923, null], [13923, 16236, null], [16236, 17673, null], [17673, 20369, null], [20369, 22670, null], [22670, 24794, null], [24794, 26787, null], [26787, 28529, null], [28529, 31195, null], [31195, 33236, null], [33236, 34724, null], [34724, 35483, null]], "google_gemma-3-12b-it_is_public_document": [[0, 384, true], [384, 1580, null], [1580, 3916, null], [3916, 5841, null], [5841, 8167, null], [8167, 10036, null], [10036, 12124, null], [12124, 13923, null], [13923, 16236, null], [16236, 17673, null], [17673, 20369, null], [20369, 22670, null], [22670, 24794, null], [24794, 26787, null], [26787, 28529, null], [28529, 31195, null], [31195, 33236, null], [33236, 34724, null], [34724, 35483, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35483, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35483, null]], "pdf_page_numbers": [[0, 384, 1], [384, 1580, 2], [1580, 3916, 3], [3916, 5841, 4], [5841, 8167, 5], [8167, 10036, 6], [10036, 12124, 7], [12124, 13923, 8], [13923, 16236, 9], [16236, 17673, 10], [17673, 20369, 11], [20369, 22670, 12], [22670, 24794, 13], [24794, 26787, 14], [26787, 28529, 15], [28529, 31195, 16], [31195, 33236, 17], [33236, 34724, 18], [34724, 35483, 19]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35483, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
6429ac6a59ebfc7c1029d1f3c7c9b045245c626f
|
An Abstract Representation of Variational Graphs†
Martin Erwig
School of EECS
Oregon State University
erwig@eecs.oregonstate.edu
Eric Walkingshaw
Department of Computer Science
University of Marburg
walkiner@informatik.uni-marburg.de
Sheng Chen
School of EECS
Oregon State University
chensh@eecs.oregonstate.edu
Abstract
In the context of software product lines, there is often a need to represent graphs containing variability. For example, extending traditional modeling techniques or program analyses to variational software requires a corresponding notion of variational graphs. In this paper, we introduce a general model of variational graphs and a theoretical framework for discussing variational graph algorithms. Specifically, we present an abstract syntax based on tagging for succinctly representing variational graphs and other data types relevant to variational graph algorithms, such as variational sets and paths. We demonstrate how (non-variational) graph algorithms can be generalized to operate on variational graphs, to accept variational inputs, and produce variational outputs. Finally, we discuss a filtering operation on variational graphs and how this interacts with variational graph algorithms.
Categories and Subject Descriptors D.2.9 [Software Engineering]: Management—Software configuration management; E.1 [Data Structures]: Graphs and networks
Keywords Choice calculus, variational data structures, variational algorithms
1. Introduction
Graphs are a fundamental data structure in computer science and are useful for representing and solving a huge range of problems. In the context of feature-oriented software development [1] and software product lines [28], graphs are used for a wide variety of purposes. For example, graphs are used to describe the structure and relationships of the components or features that make up a system [15, 31] and to support separation of concerns [29]. Graphs in the form of UML models [25] are used to support a broad range of tasks related to the construction of component-based software product lines [2, 16].
A major goal of all of these fields is to support the creation and maintenance of variational software—that is, software that represents not just a single program, but can be used to generate many different program variants that provide different features and run in different environments. Therefore, it is not surprising that there is often a need to represent variation in these supporting graph representations. For example, many different extensions to UML have been proposed for incorporating variability [8, 22, 24, 33].
The need for variation in graphs is perhaps most strongly observed in the implementation of variability-aware analyses [21], which are the extension of traditional single-program static analyses to variational software. For example, extending traditional data-flow or control-flow analyses to variational software leads to correspondingly variational data-flow and control-flow graphs [4, 5].
Analogous to variational software, a variational graph represents not one, but many different plain graphs. Although many variational graph representations have been devised already, these have all been adaptations of existing representations—situated solutions that address a specific problem, with no shared underlying theory.
This paper attempts to fill this gap by presenting an abstract representation of variational graphs and a theoretical framework for discussing variational graph algorithms. Such an underlying theory is useful since it supports the reuse of operations and theoretical results between tools, problems, and fields.
In the following we establish a set of principles on which to base an abstract representation of variational graphs and also outline the rest of the paper.
(1) The model should provide a way to structure the variation space to support the scalability of variation. This is typically done through a feature model that can specify relationships between different decisions, such as dependency or mutual exclusiveness. It should be possible in our model to express and precisely characterize such relationships. This principle is the focus of Section 2.
(2) It should provide a general model of variation that applies not only to graphs, but to the values accepted and returned by graph algorithms. This is necessary to support variational graph queries. For example, variational path analysis relies not only on variational graphs, but also on variational paths (passed as inputs to the path-finding algorithm), and variational paths (as output). Section 3 provides this model.
(3) It should suggest representations for variational data structures that take advantage of inherent sharing between alternatives. For example, the paths computed by a variational path analysis may have many nodes and edges in common. As the variability in a structure increases, it becomes increasingly important to share these common sub-parts due to a multiplicative explosion in the total number of variants. Sharing is also important for making sense of variational output; for example, the differences between alternative paths are easier to see when they are overlaid on a single graph than when examined separately. Tagged sets are introduced in Section 4 as a specific data structure for efficiently representing variation in sets, and this representation is extended to tagged graphs in Section 5. These representations realize the general variation model from Section 3 for sets and graphs, respectively.
(4) It should provide a way to lift algorithms to the variational setting to support the reuse of algorithms. In the case of graphs, variational graph algorithms should accept variational input, operate on variational graphs, and produce variational output. For exam-
ple, we should be able to take a simple path-finding algorithm and mechanically lift it to a variational algorithm that supports finding variational paths. We show how to do this in general, in Section 6, and also show how lifted graph algorithms can take advantage of sharing in tagged graphs.
(5) Finally, it should provide a way to filter variational results. For example, we wanted to be able to discard alternative paths during the exploration process. We did this by making selections on the input, restricting the variation in the output. This feature is also important since a few independent sources of variation can lead to a potentially huge number of variants. Filters provide a way to project on variational output, in order to focus on and understand a related subset of the variants at a time. In Section 7 we describe variational filters, which provide a general way to project on variational values.
2. Dimensions and Decisions
In this section we describe how the variation space of a variational type can be organized in terms of its dimensions of variation, and how to identify particular points in this space by decisions. This way of structuring variability is motivated in part by our previous work on the choice calculus [10] (see Section 8).
A decision describes one way in which something varies. A dimension definition assigns a dimension name to a non-empty set of tags, which correspond to the alternatives in that dimension. A dimension definition is written as $D = \{t_1, \ldots, t_n\}$, where $D$ is the dimension’s name and $t_1, \ldots, t_n$ are its tags. A qualified tag is a tag prefixed by the name of the dimension it is in, written $D \cdot t_i$. Qualified tags are used to distinguish between tags of the same name from different dimensions. Given a qualified tag $q = D \cdot t$, we can extract the dimension name with the function $\text{dim}(q) = D$.
A decision space of degree $n$ is given by a set of $n$ dimension definitions $D' = \{D_1 = T_1, \ldots, D_n = T_n\}$ where $T_i$ is the set of tags in dimension $D_i$. We define the function $\text{dims}(D') = \{D_1, \ldots, D_n\}$ to return the set of all dimension names in a decision space. The tag universe of decision space $D'$, written $Q_{Un}$, is the set of all qualified tags in $D'$, defined as $Q_{Un} = \{D \cdot t \mid D \in \text{dims}(D') \land t \in T\}$. A decision in a decision space $D'$ is a set of qualified tags $\delta \in Q_{Un}$ that contains at most one tag for each dimension, that is, $q, q' \in \delta \implies q = q' \lor \text{dim}(q) = \text{dim}(q')$. We overload the function $\text{dims}$ to also denote the dimension names of a decision, that is, $\text{dims}(\delta) = \bigcup_{\text{q} \in \delta} \text{dim}(\text{q})$. A decision $\delta \subseteq Q_{Un}$ is complete if it contains a qualified tag from every dimension in $D'$, that is, if $\text{dims}(\delta) = \text{dims}(D')$, otherwise it is partial.
However, not all dimensions are independent of one another. A decision structure $\mathcal{D} = (D', R)$ is given by a decision space $D'$ and a (potentially empty) set of dependency relationships $R \subseteq 2^{Q_{Un}} \times D'$, where $2^{Q_{Un}}$ is the power set of the tag universe for $D'$. Given a dependency relationship $\{(D_1, t_1, \ldots, D_k, t_k), D'\} \in R$, which we write also as $D_1 \cdot t_1, \ldots, D_k \cdot t_k \rightarrow D'$, we say that $D'$ is a dependent dimension and that $D'$ is dependent on the qualified tags $D_1 \cdot t_1, \ldots, D_k \cdot t_k$. The tag universe of $\mathcal{D}$ is given by that of $D'$, that is, $Q_{Un} = Q_{D'}$.
A decision structure refines the concept of decision completeness given above, and it also gives rise to the idea of “overdetermination” of a decision. The formal definitions are based on the notions of decision covering and dimension triggering. First, we say that a decision $\delta$ covers another decision $\delta' \iff \delta' \subseteq \delta$. Second, we say that a decision $\delta$ triggers the dimension $D$ if it covers a decision $\delta'$ for a dependency $\delta' \rightarrow D \in R$.
With these two concepts we can define the completeness of decisions with respect to a decision structure as follows. A decision $\delta$ is complete if it contains a tag for each non-dependent dimension and a tag for each dependent dimension that it triggers. Formally, $\delta \subseteq Q_{\delta'}$ is complete with respect to $\mathcal{D}$ if the following is true.
$$\forall D \in \text{dims}(D') - \text{dims}(\delta). \forall \delta' \rightarrow D, \delta' \not\subseteq \delta$$
A decision structure can thus reduce the number of dimensions required in a decision to be complete. The flip side of this aspect is that dimensions in a decision can also become superfluous. We say that a decision $\delta$ is overdetermined if $\delta$ contains a dependent dimension $D$ without containing the tags that $D$ is dependent on. Formally, $\delta$ is overdetermined with respect to a decision structure $\mathcal{D} = (D', R)$ if the following is true.
$$\exists D \in \delta, \delta' \rightarrow D \land \delta' \not\subseteq \delta$$
Note that the concepts of completeness and overdetermination are independent of one another, that is, a partial as well as a complete decision can be overdetermined. Since the semantics of variational values will be defined to map to values only those decisions that contain exactly the tags needed for selecting a value and not more, we also identify the set of exact decisions, which are decisions that are complete, but not overdetermined. To summarize, a decision is:
- partial if it lacks tags to select a plain value;
- complete if it is not partial, that is, it has enough tags to select a plain value;
- overdetermined if it contains tags that are not required to select a plain value; and
- exact if it is complete but not overdetermined, that is, it contains exactly the tags needed to select a plain value.
We write $\Delta_\mathcal{D}$ for the set of all exact decisions with respect to the decision structure $\mathcal{D}$.
3. Variational Values
A variational value represents several different plain values that can be obtained by making different decisions. Given a set of plain values $A$, a variational $A$ value over a decision structure $\mathcal{D} = (D', R)$ is a partial function of type $V_\mathcal{D}(A) = \Delta_\mathcal{D} \rightarrow A$ that maps exact decisions to plain values in $A$. Given a variational value $\bar{V}$, the function $\text{dom}$ returns the decisions that can be made for $\bar{V}$ and $\text{rng}$ returns the variants contained in $\bar{V}$. A variational value may not be defined for all decisions, and the set $\Delta_\mathcal{D} - \text{dom}(\bar{V})$ contains all the uncovered decisions of $\bar{V}$.
The process of obtaining a plain value from a variational value $\bar{V}$ is called selection. A plain value is selected by applying $\bar{V}$ to an exact decision.
In addition to selecting plain values, we can also refine variational values by applying them to partial decisions. The result of refining a variational value is a new variational value that contains fewer variants. The refinement of a variational value $\bar{V}$ with respect to a partial decision $\delta$ is defined as a selection on the domain of $\bar{V}$.
$$\bar{V} \delta = \{((\delta \cdot \delta'), \nu) \mid (\delta', \nu) \in \bar{V} \land \delta \subseteq \delta'\}$$
Note that refinement with a complete decision $\delta$ will produce a trivial function $\{((\emptyset, \nu)) \mid \nu = \bar{V} \emptyset(\delta)\}$, and refinement with an overdetermined decision will produce the empty set.
Note also that the refinement operation changes the type of the variational value. Dimensions contained in $\delta$ are removed from the decision space, as well as dependent dimensions that cannot be triggered anymore. Moreover, triggered dependencies will be removed, as well as dependencies whose antecedent tags contain dimensions that are also contained in $\delta$.
In cases of successive refinements, the order of refining does not matter. This property is captured in the following lemma.
LEMMA 1. $\bar{V} \delta \delta' = \bar{V} \delta' \delta$
1 We use arrows over variables that range over variational values to indicate that these are functions.
4. Tagged and Variational Sets
The definition of variational values is completely generic in the type of values that are being varied. While this is a useful feature that provides a common semantic basis, it does not automatically lead to succinct representations of non-atomic, structured values. Specifically, variation in structured values can be local, and the duplication of all non-varying parts in the semantic representation of a variational value is not space efficient. It is also probably hard to understand and work with in many cases.
Let us consider variational sets as a simple example of a structured value that illustrates the problem well. A solution to the representation of variational sets also forms the basis for the representation of more complicated variational structures, such as graphs.
Given a set $A = \{a, b, c, d\}$, we consider the representation of two variant $A$-sets $S_1 = \{a, b, c\} \times 2^A$ and $S_2 = \{a, b, d\} \times 2^A$ as a variational $A$-set over the decision structure $\mathcal{D} = \{\{t, u\}\} \times \emptyset$.
The variational semantics described in Section 3 yields the following variational set.
$$\tilde{S} = \{(\{D.t\}, \{a, b, c\}), (\{D.u\}, \{a, b, d\})\}$$
We can observe the repeated representation of $\{a, b\}$ in both variants. In this small example, this is not a problem, but if the set of shared values gets large, say $n$, and if the number of variant sets also grows, say to $k$, then this representation produces $n(k-1)$ unnecessary copies of the shared data.
A more economic representation that shares common parts would be something like this.
$$\bar{S} = \{a, b, c, D_1, d_0, u\}$$
This representation assumes that unlabeled values appear in all variants of the set, whereas a value that is labeled by a tagged tag appears only in those variants that are mapped to by decisions containing that tag.
Labeling values with single tags is a bit limited and does not exploit the full potential of this approach to sharing. For example, we might want to express that a value is included only if two or more tags (from different dimensions) are selected. This could be expressed by a conjunction of tags, which allows the inclusion of a value to be restricted to more specific cases. Similarly, we can imagine cases where the same value is included only if one of some number of different tags is selected. In this case, instead of repeating the value for each tag, we could attach a corresponding disjunction of tags and represent it only once.
These ideas are combined by the concept of tag expression over a tag universe $Q_\varphi$. Tag expressions are defined by the following grammar (where $q$ ranges over qualified tags drawn from $Q_\varphi$).\(^2\)
\[e ::= q | e_1 \land e_2 | e_1 \lor e_2\]
Additionally, we introduce a separate annotation $*$ to label elements that are included in all variants. We can define a tagged $A$ set over a decision structure $\varphi$ as a mapping of type $A \to e_*$ where $e_*$ represents the set of tagged expressions that can be generated by the above grammar based on $\varphi$’s tag universe $Q_\varphi$, extended by the element $*$. We write $\tilde{S}$ for a variable representing a tagged set and $\tau_\varphi(A)$ for the type of tagged $A$ sets over $\varphi$. Moreover, as indicated above, we write elements $(v, e) \in \tilde{S}$ of the tagged set $\tilde{S}$ using exponent notation, that is, as $v_\varphi$, and we typically omit the $*$ exponent and simply write $v$ for $v_\varphi$.
The purpose of tagged $A$ sets is to provide an economical syntax for variational $A$ sets. In the following we therefore define the semantics of this notation and explain what variational set is denoted by a tagged set. First, using a simple qualified tag $v^\varphi$ means to include $v$ in the set only if the tag $q$ is selected. Conversely, an element $v^*$ is included for any selection. Second, the meaning of a conjunction of tags $v^\varphi \land v^\varphi$ is that $v$ is included for a selection that would cause $v^\varphi$ and $v^\varphi$ to be included. Dually, a disjunction of tags $v^\varphi \lor v^\varphi$ causes $v$ to be included for selections that would cause $v^\varphi$ or $v^\varphi$ to be included.
We can define the semantics of tagged sets in two steps by first mapping single tag elements into variational sets and then combining those sets. Since variational sets are represented by functions, the combination of those functions requires a careful distinction of what to do for overlapping and non-overlapping decisions in the sets to be combined. Specifically, we can consider the two cases of computing the union and intersection of functions. The *variational union* of two variational sets $\tilde{S}$ and $\tilde{S'}$ takes the union of the non-overlapping parts of $\tilde{S}$ and $\tilde{S'}$ and computes the union of the sets mapped to by the overlapping parts. Conversely, the *variational intersection* of $\tilde{S}$ and $\tilde{S'}$ takes only the intersection of the sets mapped to by the overlapping parts of $\tilde{S}$ and $\tilde{S'}$ and drops the non-overlapping parts.
To define these operations formally we introduce an auxiliary function $\lambda_\varphi$ that decomposes two functions into their overlapping and non-overlapping parts. The result of $\lambda_\varphi \tilde{S}$ is a triple of sets, where the first and third sets capture the non-overlapping parts of $\tilde{S}$ and $\tilde{S'}$, respectively, and the second captures the overlapping parts.
\[\lambda_\varphi \tilde{S} = ((\{\delta, S_1(\delta)\} | \delta \in dom(\tilde{S}) - dom(\tilde{S}') \}, (\{\delta, S_2(\delta)\} | \delta \in dom(\tilde{S}) \cap dom(\tilde{S}')), (\{\delta, S_3(\delta)\} | \delta \in dom(\tilde{S}' - dom(\tilde{S}))))\]
With this auxiliary function we define variational union as follows.
\[\tilde{S} \cup \tilde{S'} = L \cup \{\tilde{S}_1 \cup \tilde{S}_{1'} \cap \tilde{S}_2 \cap \tilde{S}_{2'} \cap \tilde{S}_3 \cap \tilde{S}_{3'} \mid \tilde{S}_1, \tilde{S}_2, \tilde{S}_3 \in \{\tilde{S}, \tilde{S}'\}, \tilde{S}_1 \cap \tilde{S}_2 \neq \emptyset \} \cup R\]
In our example we can use $\tilde{S}_1 = ((\{D.t\}, \{a, b, c\}) \cap \{\tilde{S}, \tilde{S}'\})$, and we find that $\tilde{S}_1 \cup \tilde{S}_2$ yields $\tilde{S}$ since $\tilde{S}_1 \cup \tilde{S}_2$ yields $L \cup \tilde{S}_1 \cup \tilde{S}_2$ and $M = \emptyset$.
In a similar way we can define variational intersection using the auxiliary decomposition function.
\[\tilde{S} \cap \tilde{S'} = (\{\tilde{S}_1 \cap \tilde{S}_{1'} \cap \tilde{S}_2 \cap \tilde{S}_{2'} \cap \tilde{S}_3 \cap \tilde{S}_{3'} \mid \tilde{S}_1, \tilde{S}_2, \tilde{S}_3 \in \{\tilde{S}, \tilde{S}'\}, \tilde{S}_1 \cap \tilde{S}_2 \neq \emptyset \} \cap \{\tilde{S}, \tilde{S}'\} \}
In our example, $\tilde{S}_1 \cap \tilde{S}_2$ yields $\emptyset$.
Now we can define the semantics of tagged values. First, we define the semantics of $\ast$ tagged values and singly tagged values. Then we use the union and intersection operations to define the semantics of values that are tagged by disjunctions and conjunctions of tags, respectively.
\[v^*_{\varphi} = \{(\delta, \{v\}) | \delta \in \Delta_{\varphi}\}\]
\[v^\varphi_{\varphi} = \{(\delta, \{v\}) | \delta \in \Delta_{\varphi} \land q \in \delta\}\]
\[v^{\land q}_{\varphi} = \{v^\varphi_{\varphi} \cap \{q\} | (v, q) \in \tilde{S}\}\]
\[v^{\lor q}_{\varphi} = \{v^\varphi_{\varphi} \cup \{q\} | (v, q) \in \tilde{S}\}\]
Finally, we can again use the variational union operation to define the semantics of tagged sets below. The type of the semantic function is \([\_ : \tau_\varphi(A) \to V_\varphi(2^A)].\]
\[\tilde{S}_{\varphi} = \bigcup_{v^\varphi_{\varphi} \in \{\tilde{S}, \tilde{S}'\}} v^\varphi_{\varphi}\]
Note that the decision structure determines the domain of the semantics. Thus, one tagged value or set will generally have different semantics under different decision structures. Specifically, an element in a tagged set will materialize as a plain element in the range of the semantics only if its tag expression respects the dependencies.
\(^2\) It is possible to extend tag expressions also by "negated tags", that is, tags whose selection will exclude elements, but we omit these here for brevity.
in the decision structure. An example of this effect can be seen in
the graph example shown in Figure 1(a) (explained in more depth in
the next section). The edge $(3,1)$ that is tagged $A.t \land B.r$ would not
appear in any plain graph if the dependency was instead $\{A.u\} \rightarrow B.$
We observe that the semantics for tagged values and sets are
well defined in the sense that the definition always produces vari-
ational values whose domain respects the decision structure. Con-
sider as an example the tagged set $(\{D.t,D.u\})$. We expect the cor-
responding variational set to be empty since $v$ cannot appear in a
decision that contains both $D.t$ and $D.u$ since the two tags belong
to the same dimension. We can verify our expectation by comput-
ing the semantics, which, as expected, produces the empty set.
$$\left[\left[\{D.t,D.u\}\right]\right]_\varnothing = \left[\left[\{D.t\}\right]\right]_\varnothing \cap \left[\left[\{D.u\}\right]\right]_\varnothing = \emptyset$$
Finally note that the function representation requires that in a
tagged set each element can occur at most once. Thus in order to
represent an element in different alternatives one must combine the
corresponding tags with a disjunction.
Tagged and variational sets provide the basis for the succinct
representation of a wide range of variational data structures, and
thus support the two principles of generality and sharing.
5. Tagged and Variational Graphs
A representation for variational graphs that is flexible, allows the
exploitation of sharing, and lends itself to succinct visualizations,
is obtained by drawing a “supergraph” of all graph variants and
labeling nodes, edges, and labels with tags to express the variational
parts. This supergraph representation strategy is in principle an
instance of the approach that we have already employed in the
representation of variational sets using tagged sets.
Before we can define tagged graphs, however, we have to decide
on a definition of (plain) directed, labeled graphs to work with.
We can obtain a succinct representation when we combine the set
of vertices and edges with their respective labeling functions. We
therefore represent a directed, node- and edge-labeled graph by
a pair of mappings $(N,E)$ where $N : V \rightarrow L$ and $E : V \times V \rightarrow L$
represent the sets of labeled vertices and edges, respectively, and
where $V$ and $L$ are sets that provide universes of node and label
values, respectively. Such a graph is said to be well defined if edges
connect only existing nodes, that is, $(v,w) \in dom(E) \implies (v,w) \subseteq dom(N)$.
Following the definition in Section 4 we now define a tagged
directed graph over a decision structure $\mathcal{D}$ as a pair of mappings $(\bar{N},\bar{E})$
where the supergraph $(N,E)$, obtained by $N = rng(\bar{N})$ and $E =
rng(\bar{E})$, is a directed graph. An example is shown in Figure 1(a).
To simplify the following discussion we use, without loss of gen-
erality, an unlabeled graph.
The definition of the semantics of a tagged graph can be based
on the semantics of tagged sets. Since labeled nodes and edges
are functions (and thus sets), their variational versions represented
as tagged functions/sets is directly amenable to the semantics of
tagged sets as defined in Section 4. However, this is not all there
is to do. The two resulting variational sets must still be combined
into a variational graph; that is, we have to transform an element of
type $(V_\varnothing (\bar{N})^v, V_\varnothing (\bar{N})^e)$ into one of type $V_\varnothing (2^\bar{N})$. This requires
some care since the tag structures of nodes and edges are prin-
cipally independent of one another; that is, the variational nodes
$(V_\varnothing (2^\bar{N}))$ and variational edges $(V_\varnothing (2^\bar{E}))$ that result form the
semantics are not guaranteed to be synchronized. For example, there
may be variants corresponding to specific decisions in one that are
missing in the other.
This problem can be avoided by taking decisions only from the
intersection of the domains of both variational sets, an idea
captured in the following definition of the semantics.
$$\left[\left[(\bar{N},\bar{E})\right]\right]_\varnothing = \left[\left[\delta, (\bar{N}(\delta), \bar{E}(\delta))\right]\right]_{\varnothing \subset dom(\bar{N}) \cap dom(\bar{E})}$$
where $\bar{N} = [N]_\varnothing$ and $\bar{E} = [E]_\varnothing$
As an example, consider the tagged graph $\bar{G}$ shown in Figure 1(a).
Its semantics $[G]_\varnothing$ is shown in Figures 1(b) - (d).
Even though the semantics definition ensures that each decision
leads to two sets of labeled nodes and edges, it is not guaranteed
that any such graph is itself well defined. Consider, for example,
the following tagged graph $\bar{G} = (\bar{N},\bar{E})$ with $\bar{N} = \{(v,l),(w,k)\}$
and $\bar{E} = \{(v,w),(w,m)\}$. We assume the simple decision structure
$(D = \{t,u\})$, and since we have only one dimension, we use
unqualified tags for brevity. The semantics of the tagged node
and edge label functions are as follows.
$$\bar{N} = \{(t),\{(v,l)\},\{(u),(w,k)\}\}$$
$$\bar{E} = \{(t),\{(v,w),(w,m)\},\{(u),(w,m)\}\}$$
The semantics of $\bar{G}$ is thus the following function (note that
dom($\bar{N}$) = dom($\bar{E}$) = $\{t\}$).
$$\bar{G} = [G]_\varnothing = \left[\left[(t),\{(v,l)\},\{(u),(w,m)\}\right]\right],$$
$$\left[\left[u\right]\right]_\varnothing = \left[\left[\{(w),(w,m)\}\right]\right]_\varnothing$$
Now we can see that neither $\bar{G}(\{t\})$ nor $\bar{G}(\{u\})$ is well
defined. For example, in the graph $(N,E) = \bar{G}(\{t\})$, we observe that
$(\{v,l\},m) \in E$ and while $(v,w) \in dom(E)$, it is not the case that
$(v,w) \subseteq dom(N) = \{v\}$. (The situation is similar for $\bar{G}(\{u\})$ which
contains the same edge but only the node $w$.)
Similarly, consider what happens when we change the tag ex-
pression of node 1 in Figure 1(a) from $A.u \lor B.r$ to just $B.r$. Then
the graph generated by the decision $\{A.u\}$ is not well-defined since
it includes the edge $(1,2)$ but not the node 1.
To ensure that the graph variants denoted by tagged graphs
are well defined, we will add a condition that the tags of nodes
must include the decisions of their incident edges. To this end,
in Figure 5, we define a “subsumes” relationship $e \leq e'$ on
tag expressions that holds if $e$ is more inclusive with respect to the
decisions it denotes than $e'$. A crucial property of $\leq$ is expressed in
the following lemma that holds for arbitrary values $v_1$ and $v_2$.
Lemma 2. \( e_2 \subseteq e_1 \implies \forall v_1, v_2. \text{dom}(v_1) \subseteq \text{dom}(v_2) \)
This property allows us to formulate the following theorem that places a generality condition on node tags, ensuring that nodes will be included in all decisions that produce incident edges.
Theorem 1. If \( \forall ((v, w), e) \in E : N(v) \subseteq e \land N(w) \subseteq e, \text{ then } \forall G \in \text{rng}(((N, E))_T) : G \text{ is well defined.} \)
We can apply this theorem to the graph \( G \) shown in Figure 1(a).
Only node 1 is not tagged \( ^* \) and needs to be considered. Due to the reflexivity of \( e \), we have \( N(1) \in E(1, 2) \), and \( N(1) \in E(3, 1) \) holds since \( B \land B \implies (A \lor A) \lor B \). We can then observe that indeed all graph variants in Figure 1(b) - (d) are well defined.
Note, however, that the condition in the theorem is an approximation, that is, there are tagged graphs that do not satisfy the condition but are still well formed.
Tagged graphs directly support the third design principle that we identified in Section 1 since they offer a succinct representation for variational graphs that exploits sharing.
6. Variational Graph Algorithms
Since the \( V \) type constructor (see Section 3) is a functor [27], it can automatically lift any function \( f \) of type \( A \rightarrow B \) to a variational function \( \bar{f} \) of type \( V(A) \rightarrow V(B) \). We can provide the definition of \( \bar{f} \) using a plain set comprehension that iterates over all decisions in the variational domain of the function.
\[ \bar{f} = \{ (\delta, \bar{f}(a)) | (\delta, a) \in V(A) \} \]
However, this is generally not a very efficient method for computing \( \bar{f} \) since it does not exploit any potential sharing among the different alternatives of values in \( V(A) \).
What we would like to do instead is lift \( f \) based on a more economical representation, such as the one provided by tagging, which can exploit the sharing in the representation. In other words, we would like to find a definition for \( \bar{f} \) that is correct with respect to \( f \). We will illustrate this process with a simple example.
Consider the following function \( \text{path} \) for finding all directed paths between two nodes (in some given graph \( G \)). Here \( [] \) denotes an empty path, and \( :: p \) puts the node \( v \) at the beginning of the path \( p \), but only if \( p \) doesn’t already contain \( v \), to avoid cycles.
\[ \text{path}(v, v) = [v] \]
\[ \text{path}(v, w) = \{ v : p \mid p \in \text{path}(u, w) \land (v, u, l) \in E \} \]
To generalize this function to work on tagged graphs, we simply copy tag expressions from traversed edges to the nodes that are reached via those edges in the constructed paths. In the constructed paths, we use the conjunction of the edge tag and the tag of the target node to find only paths that satisfy both tag constraints.
\[ \text{path}(v, v) = [v] \]
\[ \text{path}(v, w) = \{ v : p \mid p \in \text{path}\(u, w\) \land (v, u, l) \in E \} \]
For the tagged graph \( G \) in Figure 1, \( \text{path} \) computes one tagged path between nodes 1 and 2, namely \( [1, 2] \land (A, u) \), and the following two paths between nodes 3 and 2:
\[ \text{path}(3, 2) = \{ 3, 1, 2] \land (A, u) \land (A, u) \land (A, u) \land (A, u) \}
To judge the correctness of the algorithm, we need a semantics for tagged paths, which is given by variational paths, that is, by functions from decisions to plain paths. For the semantics of a tagged path \( p \) computed in a tagged graph \( G \) the following consistency criterion must hold.
\[ \forall (\delta, p) \in [\bar{p}]_T : p \text{ is a path in } [G]_T(\delta) \]
To ensure this property we gather the tags of all nodes in \( \bar{p} \) and form a conjunction of all of them, effectively computing the most restrictive tag from all tags, written as \( N((\bar{v}(w))_T) \). We attach this tag to the plain path \( p \), which is obtained from \( \bar{p} \) by removing the tags from all nodes, and then apply the standard semantics for tagged values.
\[ [\bar{p}]_T = [p]^N((\bar{v}(w))_T) \]
With this definition we can now define the semantics of the tagged path algorithm as follows.
\[ [\text{path}(v, w)]_T = \bigcup_\gamma \text{path}(v, w) \]
As an example, consider the computation of \( [\text{path}(3, 2)]_T \). Given \( \bar{p} = [3, 1, 2] \land (A, u) \land (A, u) \land (A, u) \land (A, u) \), we obtain \( p = [3, 1, 2] \) as the plain path and \( ([A, T \land B, R] \land (A, u) \lor B, R) \lor (A, u) \lor B, R) \) for its aggregated tag, which can be simplified to \( e = (A, T \land B, R) \land (A, u) \lor B, R) \). Now we can compute \( [p]_T \) as follows.
\[ [\bar{p}]_T = [p]_T \]
\[ = [p]^N((\bar{v}(w))_T) \]
\[ = [p]^N((\bar{v}(w))_T) \]
\[ = (\text{definition of } \bar{p}) \]
\[ = (\text{definition of } \bar{p}) \]
This complicated computation can be simplified significantly if we first simplify the tag expression \( e \) as follows.
\[ e = (A, T \land B, R) \land (A, u) \lor B, R) \]
\[ = A, T \land B, R \land A, u \lor A, T \land B, R \land B, R \]
\[ = A, T \land A, u \land B, R \land B, R \land A, T \land A, u \land B, R \land B, R \]
\[ = A, T \land B, R \land A, u \land B, R \land B, R \land A, T \land A, u \land B, R \land B, R \]
\[ = A, T \land B, R \land A, u \land B, R \land B, R \land A, T \land A, u \land B, R \land B, R \]
Note that the tag expression \( A, T \land B, R \land A, u \land B, R \land B, R \land A, T \land A, u \land B, R \land B, R \) is unsatisfiable because it needs both tags \( A, T \) and \( A, u \) whereas we can choose at most one tag from each dimension. Thus, this expression can be viewed as the zero identity to the connective \( \lor \).
With the simplified tag expression, the semantics of \( [p]^N((\bar{v}(w))_T) \) can be easily computed. Similarly, given \( \bar{p} = [3, 2] \land (A, u) \land (A, u) \) and thus \( p = [3, 2] \) we obtain \( [p]_T = (((A, T, B, R), (A, u), (A, T, B, R), (A, u))) \).
We can put these two results together and obtain the following.
\[ [\text{path}(3, 2)]_T = (((A, T, B, R), [3, 1, 2], [3, 2])) \]
\[ = (((A, T, B, R), [3, 1, 2], [3, 2])) \]
Note, however, that we can always compute \( f \) lazily, that is, only when \( f \) is applied to some decision \( \delta \) will we actually compute \( f \) for the value \( A(\delta) \). We can then also memoize the result.
The semantics tell us that when the tags $A.t$ and $B.r$ are chosen, the resulting graph will have two different paths from node 3 to node 1, namely the paths $\{3,1,2\}$ and $\{3,2\}$. The correctness can be easily verified against Figure 1(c). Similarly, when $A.t$ and $B.s$ are chosen, the resulting graph has one path $\{3,2\}$, which can again be verified against Figure 1(c).
The correctness of the algorithm $\text{path}$ is expressed in the following lemma where $\text{path}$ gives the “semantic standard” by lifting the path function to the variational case.
**Lemma 3.** $[\text{path}(v,w)]_{\text{path}} = \text{path}(v,w)$
Just like $\text{path}$, the algorithm $\text{path}$ traverses the graph only once and is thus in general more efficient than the variational version $\text{path}$. The expansion of tagged paths into a set of paths does cause some additional effort, but the efficiency gains are obvious in cases where one sub($\text{path}$) occurs in $n$ variants. The brute-force algorithm $\text{path}$ will compute that path $n$ times, whereas $\text{path}$ does this only once. However, the efficiency gain of $\text{path}$ over $\text{path}$ depends on the graph structure. For a given tagged graph $G$, the efficiency gain is significant if there is a lot of sharing among different variants.
Lemma 3, together with all of its efficiency benefits, extends naturally to many other graph algorithms. This result is important since it supports our fourth principle from Section 1 by providing a general roadmap to extend algorithms employed in graph applications to the variational case, along with their graph representations.
### 7. Variational Filters
Variational graphs, and variational values in general, are binary relations between decisions and plain values. Filters on variational graphs can therefore be conveniently expressed by pairs of predicates on the domain and range of these relations. We have already encountered refinement in Section 3 as an example of one such query operation. Refinement was basically a selection on a relation’s domain. Similarly, we can envision selection on the range.
In general, given a variational value $v$ of type $V_{\varphi}(A)$, a $V_{\varphi}(A)$-filter on $v$ is given by a pair of predicates $\varphi = (\alpha, \beta)$ where $\alpha : \Delta_{\varphi} \rightarrow B$ and $\beta : A \rightarrow B$ represent the domain and range predicates, respectively. We call $\alpha$ the decision predicate and $\beta$ the value predicate. The semantics of a filter is the transformation of a variational value obtained by applying the decision and value predicates to the two respective parts of the relation representing the variational value. Since the filtering step might leave redundant fragments in the decisions—that is, qualified tags that occur in every entry—those parts are removed from the decisions of the resulting relation.
$$[[\alpha, \beta]]_{\varphi}(v) = \{(\delta - K, v) | (\delta, v) \in R\}$$
where $R = \{((\delta, v) \in \varphi | \alpha(\delta) \land \beta(v))\}$
$$K = \bigcap_{\delta \in \text{dom}(R)} \delta$$
With the “accept everything” predicate $t = \lambda x.\text{true}$ that always returns true, we can identify some special cases of filters. For example, refinement with a decision $\delta$ (defined earlier in Section 3) is given by the filter $(\lambda x. x = \delta, t)$. Refinement corresponds to partial decision making. The dual operation, which restricts a variational value by a predicate $\beta$ on values is given by $(t, \beta)$.
From the semantics definition of filters it follows directly that the composition of filters can be performed component-wise, that is, by forming conjunctions of the decision and value predicates. (In the following definition, we lift conjunction from values to predicates, that is, we write more shortly $\alpha \land \alpha'$ for the expression $\lambda x. \alpha(x) \land \beta(x)$.)
**Lemma 4.** $(\alpha, \beta) \circ (\alpha', \beta') = (\alpha \land \alpha', \beta \land \beta')$
Since lifted variation computations do not change the domain of variational values, that is, $\text{dom}(\tilde{f}(v)) = \text{dom}(v)$, they are unaffected by changes to the decisions in variational values and thus commute with decision refinements, a result summarized in Lemma 5.
**Lemma 5.** $(\alpha, t) \circ \tilde{f} = \tilde{f} \circ (\alpha, t)$
The importance of this lemma lies in the fact that, when applied from left to right, it can save potentially costly computations of $\tilde{f}$ for all those decisions that are eliminated by $\alpha$.
Routing a filter with a non-trivial value predicate and a transformation is generally much more difficult, and for lack of space we will not explore this aspect here in detail. Instead we provide some preliminary results.
If we apply a filter after a transformation, as in $(\alpha, \beta) \circ \tilde{f}$, the predicate $\beta : B \rightarrow B$ will generally reduce the set of values produced by the transformation $\tilde{f} : A \rightarrow B$. Therefore, in order to apply $\beta$ before $\tilde{f}$, we have to apply a modified version of it that excludes only those A values whose image under $\tilde{f}$ would be excluded by $\beta$, that is, we need a predicate $\tilde{\beta}_f : A \rightarrow B$ that has the following property.
$$(\tilde{\beta}_f (a) \iff \neg \beta(\tilde{f}(a)))$$
We call such a predicate the $f$-prefilter for $\beta$. Having such a predicate available, we can move the filter as follows. Since the value predicate is not needed anymore, we can remove the whole filter following $\tilde{f}$.
**Lemma 6.** $(t, \beta) \circ \tilde{f} = \tilde{f} \circ (t, \tilde{\beta}_f)$
This lemma is probably not very useful in practice since it is generally difficult to construct a prefilter. A more promising approach for exploiting knowledge about the presence of post-algorithmic filters is to integrate the filter into the algorithm itself. Unfortunately, this is not a general solution and requires much effort. In many cases, a better approach is to apply an algorithm that modifies the plain values directly instead of applying a filter. For example, if $\tilde{f}$ is a shortest path algorithm and $\beta$ requires that certain nodes not be in the resulting paths, it is generally not possible to achieve this by removing some graphs from $\tilde{f}$ altogether. However, removing the nodes from the graph would cause the shortest path algorithm to produce the desired results.
As a corollary of Lemmas 5 and 6 we obtain the following result.
**Theorem 2.** $(\alpha, \beta) \circ \tilde{f} = \tilde{f} \circ (\alpha, \tilde{\beta}_f)$
As already mentioned, the construction of prefilters is a difficult problem. Therefore, Lemma 5 will probably be applicable more often and thus be more relevant.
On the other hand, we observe that we can always at least partially commute a filter with an algorithm by employing Lemma 4, a result captured in the following theorem.
**Theorem 3.** $(\alpha, \beta) \circ \tilde{f} = (t, \beta) \circ \tilde{f} \circ (\alpha, t)$
This result reveals a general strategy for evaluating queries in a variational setting, namely to first apply refinements, then run the algorithm, and finally apply value filters. The fact that variational filters are open to optimization, as illustrated by the lemmas and theorem, support the fifth principle we identified in Section 1.
### 8. Related Work
The feature-oriented software development (FOSD) [1] and software product line (SPL) [28] communities are intimately concerned with creating and managing variational software. Since the construction of plain software is often supported by various graph representations, there is a need to represent variation in these supporting graph representations as well. There are many examples of such
adaptations already, which will be described in this section. Com-
pared to the model presented in this paper, these variational graph
representations are in some sense domain-specific, adapting spec-
fic object languages in order to solve a particular problem.
An important distinction to make, however, is between graph
representations that contain variability and graph representations
that describe variability. In FOSD terms, the first is related to the
problem of feature implementation while the second is related to the
problem of feature modeling [20].
Feature diagrams [18] are a common notation for feature mod-
eling. Although feature diagrams are typically described as trees,
they are actually directed graphs when cross-tree constraints are
taken into account [30]. However, a feature diagram does not it-
self contain variation—instead it describes the high-level structure
of the variation in some other artifact, typically a software system.
In this way, feature diagrams are more similar to our dimensions
of variation and decisions structures (Section 2) than to variational
graphs. In terms of expressiveness, many feature diagram notations
are functionally complete, making them more expressive than our
decision structure representation. Our decisions structures provide
only implications and disjunctions of implications, which are not
by themselves functionally complete [32]. Our representation of
decisions structures would be complete if extended by a negation
operation. Feature diagrams are equivalent to many other represen-
tations of feature models, such as propositional formulas [3].
On the other hand, the tagged graph representation (Section 5)
contains variation—by making selections we can generate many
different plain graph variants. Similarly, to support efficient model
checking of SPLs, Classen et al. [6, 7] extend the directed graph
notation of transition systems with a way to tag edges that cor-
respond only to certain features in a SPL, which may be optional.
They call this representation featured transition systems (FTS). The
FTS notation resembles our tagged graphs, although there are sev-
eral important differences. First, the role of decision structures in
tagged graphs is played in FTS by an associated feature diagram.
Each node in the feature diagram corresponds to a potential tag in
FTS. Second, tagged graphs support a more flexible and precise
form of variation than FTS. In FTS, each edge can be associated
with only a single tag, and nodes are not variational at all. Tagged
graphs associate tag expressions (Section 4) with both nodes and
edges. Finally, to overcome the limitations of tagging in FTS, a no-
tion of edge priority is introduced, where some edges, if present,
supersede and remove other edges. Although this solution sup-
ported their variational model-checking algorithm, it is rather ad
hoc and demonstrates the need for a consistent, general model for
variational graphs. A similar but less expressive representation was
introduced by Lauenroth et al. [19], also in the context of model
checking product lines. Compared to FTS, this representation al-
ows only simple tags on edges rather than boolean expressions.
Checking product lines. Compared to FTS, this representation al-
Dented by Lauenroth et al. [19], also in the context of model
algebraic laws to support the flexible transformations of variation repre-
entations. Additionally, we have introduced the idea of variational
data structures, and described how to extend algebraic data types
with choice calculus-based variation [11]. One difference between
the choice calculus and this work is that dimensions of variation
can be locally scoped in the choice calculus, while they are glob-
ally defined in the decision structure corresponding to a variational
constructs. An interesting aspect of their approach is that it allows
the elimination of variability through the execution of petri nets.
Multiple researchers have extended UML class diagrams and
sequence diagrams to incorporate variability [22, 24, 33]. These
extensions again resemble our tagged graph representation, except
that only nodes are tagged. Also, the set of available tags is fixed
and not determined by an associated decision structure (or feature
diagram, as in Classen et al.). For example, optional class nodes
can be tagged directly as optional. A class tagged with the variation
tag denotes a variation point, whose alternatives are denoted with
variant tags. Constraints between different variation points and
optional classes, such as mutual requirement and exclusion, can be
expressed using the Object Constraint Language of UML [25].
The Common Variability Language (CVL) by the Object Man-
agement Group (OMG) is an ongoing effort to standardize the rep-
resentation of variation in model-based engineering [26]. The over-
arching goal of CVL is to achieve orthogonality [28] with respect
to the domain and language of the underlying model. To this end,
CVL adds variability modeling constructs to any modeling lan-
guage based on OMG standards. CVL consists of several different
kinds of models. A variability model is linked to nodes and edges
in the underlying base model. The links denote potential actions to
modify the base model. The modifications are controlled by a vari-
ability specification tree, which is similar to a feature model. An
individual configuration is given by a so-called resolution model,
which describes the modifications to be applied to the base model,
resulting in a resolved model. Compared to CVL, the representa-
tions proposed in this paper are simpler and more abstract. While
variational graphs and tagged graphs offer a straightforward and
systematic approach to formulate variational graph algorithms, it is
not clear how to achieve this with CVL.
Czarnecki and Antkiewicz present another approach to add vari-
ability to modeling languages in an orthogonal way [8]. Their ap-
proach associates presence conditions with model elements, simi-
lar to tagged graphs. When generating graph variants, the elements
whose presence conditions evaluate to false are removed. Unlike
tagged graphs, presence conditions are externally associated with
nodes (addressing them via XPath), so the variation structure is not
apparent when looking at the graph itself.
Brabrand et al. [5] describe several different ways of adapt-
ing existing static data-flow and control-flow analyses to varia-
tional software. This is supported by extending the representation
of data/control-flow graphs with an inclusion condition associated
with each node, describing under which configurations the node is
present in the graph. This is similar to our own tagged graph rep-
resentation except that only nodes are variational, not edges. Addi-
tionally, it is assumed that if nodes A and C are connected through
node B, A and C will still be connected even if B is excluded. An
alternative approach to lifting flow-based analyses to SPLs is de-
scribed by Bodden et al. [4]. In this approach, the data/control-flow
graphs are computed in the usual way, then supplemented by condi-
tional edges. While this representation has some benefits over the
representation used by Brabrand et al., the result does not re-
ally represent a variational data/control-flow graph in the sense de-
scribed in this paper since it is not possible to generate variant flow
graphs corresponding to each product of the SPL.
In our own previous work on the choice calculus [10], we have
developed a formal variation representation that offers many alge-
braic laws to support the flexible transformations of variation repre-
sentations. Additionally, we have introduced the idea of variational
data structures, and described how to extend algebraic data types
with choice calculus-based variation [11]. One difference between
the choice calculus and this work is that dimensions of variation
can be locally scoped in the choice calculus, while they are glob-
ally defined in the decision structure corresponding to a variational
graph. Even more importantly, the choice calculus operates on tree-structured data (such as a program’s abstract syntax tree), and is therefore not directly applicable to graphs. However, it could be applied to an inductive representation of graphs by an algebraic data type [9].
9. Conclusions and Future Work
We have introduced a model of variational graphs that can serve as a formal foundation for extending graph-based applications with variation. The ability to consider different versions of graph data side by side, to structure these versions systematically, and observe the corresponding variation in the results opens many exciting opportunities in these areas. The variational graph model can serve as a framework for systematically introducing variation into graph-based applications.
We have also identified tagged graphs as a succinct syntactic representation for variational graphs and demonstrated how this may provide an efficient representation for variational graph algorithms. However, we have barely scratched the surface of this area. The question of finding efficient variational and tagged graph algorithms for all kinds of graph problems is a wide open research field that can be the subject of future research efforts.
References
|
{"Source-Url": "http://web.engr.oregonstate.edu/~walkiner/papers/fosd13-variational-graphs.pdf", "len_cl100k_base": 13345, "olmocr-version": "0.1.50", "pdf-total-pages": 8, "total-fallback-pages": 0, "total-input-tokens": 34701, "total-output-tokens": 16259, "length": "2e13", "weborganizer": {"__label__adult": 0.0002923011779785156, "__label__art_design": 0.000408172607421875, "__label__crime_law": 0.0002617835998535156, "__label__education_jobs": 0.0009293556213378906, "__label__entertainment": 6.258487701416016e-05, "__label__fashion_beauty": 0.0001308917999267578, "__label__finance_business": 0.00017070770263671875, "__label__food_dining": 0.00026869773864746094, "__label__games": 0.00054931640625, "__label__hardware": 0.0005292892456054688, "__label__health": 0.0003712177276611328, "__label__history": 0.00022077560424804688, "__label__home_hobbies": 7.30752944946289e-05, "__label__industrial": 0.00027751922607421875, "__label__literature": 0.0003292560577392578, "__label__politics": 0.0002028942108154297, "__label__religion": 0.0004067420959472656, "__label__science_tech": 0.01488494873046875, "__label__social_life": 7.909536361694336e-05, "__label__software": 0.00621795654296875, "__label__software_dev": 0.97265625, "__label__sports_fitness": 0.0002346038818359375, "__label__transportation": 0.0003857612609863281, "__label__travel": 0.00016987323760986328}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58480, 0.01123]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58480, 0.68471]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58480, 0.87375]], "google_gemma-3-12b-it_contains_pii": [[0, 5837, false], [5837, 14200, null], [14200, 22508, null], [22508, 29095, null], [29095, 35595, null], [35595, 43458, null], [43458, 51518, null], [51518, 58480, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5837, true], [5837, 14200, null], [14200, 22508, null], [22508, 29095, null], [29095, 35595, null], [35595, 43458, null], [43458, 51518, null], [51518, 58480, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58480, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58480, null]], "pdf_page_numbers": [[0, 5837, 1], [5837, 14200, 2], [14200, 22508, 3], [22508, 29095, 4], [29095, 35595, 5], [35595, 43458, 6], [43458, 51518, 7], [51518, 58480, 8]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58480, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
e72803b9acbad3c155d3810fe4ca5e015f53b215
|
Code Cache Management in Managed Language VMs to Reduce Memory Consumption for Embedded Systems
Forrest J. Robinson
EECS, University of Kansas, USA
fjrobinson@ku.edu
Michael R. Jantz
EECS, University of Tennessee, USA
mrjantz@utk.edu
Prasad A. Kulkarni
EECS, University of Kansas, USA
prasadk@ku.edu
Abstract
The compiled native code generated by a just-in-time (JIT) compiler in managed language virtual machines (VM) is placed in a region of memory called the code cache. Code cache management (CCM) in a VM is responsible to find and evict methods from the code cache to maintain execution correctness and manage program performance for a given code cache size or memory budget. Effective CCM can also boost program speed by enabling more aggressive JIT compilation, powerful optimizations, and improved hardware instruction cache and I-TLB performance.
Though important, CCM is an overlooked component in VMs. We find that the default CCM policies in Oracle’s production-grade HotSpot VM perform poorly even at modest memory pressure. We develop a detailed simulation-based framework to model and evaluate the potential efficiency of many different CCM policies in a controlled and realistic, but VM-independent environment. We make the encouraging discovery that effective CCM policies can sustain high program performance even for very small cache sizes.
Our simulation study provides the rationale and motivation to improve CCM strategies in existing VMs. We implement and study the properties of several CCM policies in HotSpot. We find that in spite of working within the bounds of the HotSpot VM’s current CCM sub-system, our best CCM policy implementation in HotSpot improves program performance over the default CCM algorithm by 39%, 41%, 55%, and 50% with code cache sizes that are 90%, 75%, 50%, and 25% of the desired cache size, on average.
Categories and Subject Descriptors D.3 [Software]: Programming languages; D.3.4 [Programming Languages]: Compilers—Run-time environments
General Terms Performance, Measurement, Languages
Keywords Code-cache, Memory-constrained, HotSpot JVM
1. Introduction
The rise of Java in the mid-1990’s introduced managed runtime environments or virtual machines (VM) to mainstream computing devices, including embedded and mobile systems. High-level managed languages running within a VM, such as Java and JavaScript, have gained extensive adoption since they typically support high-level programming language semantics, portable binary distribution formats, and safe and secure program execution.
VMs execute portable architecture-independent program binaries using interpretation or binary translation. Program emulation via interpretation is inherently slow [23]. Therefore, modern VMs, like those included with web browsers and most Java virtual machines (JVM), employ just-in-time (JIT) compilation to translate (important sections of) the input binary to native code at runtime [10, 20]. The generated native code is stored in a region of heap memory, called the code cache. Thus, the code cache storage enables the native code produced after JIT compilation to be reused later, without re-generating it on every invocation of that region.
JIT compilation consumes computational resources and memory to hold the generated native code at run-time. To trade-off the run-time JIT compilation cost with overall program execution speed, many VMs employ a technique called selective compilation to only translate and optimize the frequently used (or hot) sections of the program [16, 21]. Unfortunately, even with selective compilation, the memory footprint of the code cache can become significant, especially for memory constrained embedded devices [12, 25]. A large code cache can reduce the memory available to the rest of the executing application, increase the frequency and cost of garbage collection, and decrease overall device response time by lowering the number of programs that are simultaneously resident in memory.
Small embedded devices, such as wearables, often feature powerful multi-core processors, but can only accommodate modest memory capacities. 1 Our measurements reveal that compiling only the hot program methods (with Oracle’s production-grade HotSpot c1 compiler [20]) for just the startup run of the standard DaCapo benchmarks [6] results in an average code cache size of over 4MB (see Table 1). Google reported that with Android 4.4, many mobile apps tend to max out the code cache fairly quickly (which by default had been set to 1MB). 2 In fact, with Dalvik, Google recommended the JIT compiler to be entirely disabled for low-memory devices to overcome the increase in memory consumption due to the code cache. However, disabling JIT compilation can significantly degrade program speed. Therefore, it is a critical research challenge to efficiently and accurately determine which methods should reside in the code cache when memory is scarce to maximize overall program performance.
The code cache management (CCM) algorithm was initially designed to maintain program execution correctness in dynamic language VMs by evicting previously compiled regions from the code cache if the assumptions made during compilation are later found
---
1 Android smart-watches have adopted dual-core and quad-core ARM Cortex based processors, but typically offer not more than 512MB of memory.
https://wtvox.com/smartwatches-best-smartwatch-top-10/
2 http://source.android.com/devices/tech/config/low-ram.html
to be incorrect. The CCM algorithm in current VMs is also responsible for finding and evicting compiled regions to accommodate native code from later compilations if the code cache is full. The CCM algorithm has a choice when selecting a method to purge from the code cache. Ideally, the algorithm needs to find a method that is not currently hot and will not become hot and trigger a recompilation in the future. Better code cache management can enable the VM to support larger applications, and enhance performance by allowing a greater number of (phase-specific) compilations [19], enabling more powerful optimizations (like aggressive inlining for critical methods) [18], and enhancing instruction cache and instruction translation look-aside buffer (I-TLB) performance [12].
In this work we investigate the effectiveness of different CCM strategies to sustain program performance with lower code cache sizes. We find that the default CCM policies supported in the HotSpot JVM produce large performance losses even with modest code cache size pressure. We design a novel simulation-based framework to model and evaluate the potential efficiency of different CCM policies in a controlled and realistic environment that is isolated from VM and hardware specific implementation factors. Encouraging results from this modeling study provide the rationale to design and develop improved CCM methods during actual VM executions. We extend the current CCM algorithm in HotSpot and implement and compare new profiling based CCM policies. Even with minimal changes to the rest of HotSpot’s code cache infrastructure, we find that better CCM policies improve average program performance by 39%, 41%, 55%, 58%, and 50% when code cache sizes are limited to 90%, 75%, 50%, 40%, and 25% of the desired cache sizes respectively.
Thus, we make the following contributions in this work:
1. We conduct experiments to measure the impact of constrained code cache sizes on program performance with existing CCM algorithms in HotSpot.
2. We design and build a detailed modeling framework to investigate the effectiveness of different ideal, offline, and online-reactive profiling-based CCM algorithms. The theoretical ideal CCM technique uses knowledge about the future program behavior to select the methods to evict, and provides a baseline to compare the efficiency of other practical CCM policies. To understand their potential, our offline and online profiling based CCM models employ the best profiles possible with each technique by discarding the physical costs of profile data collection.
3. We extend existing and implement new CCM policies in HotSpot, evaluate their performance, and assess the impact of profiling overheads and other implementation factors imposed by HotSpot on the effectiveness of CCM techniques.
The rest of this paper is organized as follows. We present background regarding the CCM infrastructure in the HotSpot VM in the next section. We describe the experimental results with current CCM techniques in Section 3. We describe the design of our simulation framework and provide results with the ideal and practical CCM algorithms in Section 4. We explain the HotSpot implementation of CCM policies, and discuss their performance and impact of physical constraints and implementation choices on their effectiveness in Section 5. We present related work in Section 6. Finally, we discuss future work and present our conclusions from this study in Sections 7 and 8 respectively.
### 2. Background
Our work in this paper employs Oracle’s production-grade HotSpot Java virtual machine [20, 22]. In this section we provide a brief background on the internal workings of HotSpot that are relevant to this current work.
### Table 1. Number of the total and hot program methods, and size occupied by the hot compiled code during the startup run for each benchmark.
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>Total Methods</th>
<th>Hot methods – startup</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>Num</td>
<td>Size (bytes)</td>
</tr>
<tr>
<td>avora</td>
<td>3,808</td>
<td>640</td>
</tr>
<tr>
<td>fop</td>
<td>7,450</td>
<td>1,573</td>
</tr>
<tr>
<td>jython</td>
<td>9,100</td>
<td>2,226</td>
</tr>
<tr>
<td>luindex</td>
<td>3,476</td>
<td>532</td>
</tr>
<tr>
<td>lasearch</td>
<td>2,901</td>
<td>495</td>
</tr>
<tr>
<td>pmn</td>
<td>5,661</td>
<td>1,758</td>
</tr>
<tr>
<td>sunflow</td>
<td>4,457</td>
<td>405</td>
</tr>
<tr>
<td>tomcat</td>
<td>13,465</td>
<td>3,092</td>
</tr>
<tr>
<td>tradebeans</td>
<td>33,653</td>
<td>3,055</td>
</tr>
<tr>
<td>tradesoap</td>
<td>34,319</td>
<td>6,044</td>
</tr>
<tr>
<td>xalan</td>
<td>4,815</td>
<td>1,820</td>
</tr>
<tr>
<td>Average</td>
<td>10,567</td>
<td>1,741</td>
</tr>
</tbody>
</table>
HotSpot’s emulation engine includes a high-performance threaded bytecode interpreter and multiple JIT compilers. The execution of a new program begins in the interpreter. HotSpot uses each method’s hotness count, which is a sum of the method’s invocation and loop back-edge counters, to promote methods to (higher levels of) JIT compilation. The HotSpot JVM has two dynamic compilers: (a) the c1 compiler that is quick, and generates code that is lightly optimized and with a smaller memory footprint due to limited inlining, and (b) the c2 compiler that optimizes code more thoroughly. More recent HotSpot releases support a tiered compilation mode that simultaneously enables both compilers to combine their benefits. For this work we only use the c1 compiler to allow easier experimental setup and more precise analysis of observed results. The compilation unit in HotSpot is a single program method.
The compiled code is stored in the code cache. The code cache in VMs typically has a fixed upper bound on size to prevent excessive memory usage. The code cache can contain different code types. For example, HotSpot maintains two primary code types in the code cache: code that is generated by the JIT compilers and persistent infrastructure code generated by the JVM such as adapters and the interpreter. While earlier HotSpot versions had a single unified code cache, the latest HotSpot release implements a segmented code cache to segregate the different code types. A segmented code cache has been shown to reduce fragmentation overheads and result in lower I-Cache and I-TLB miss rates [12]. For this work, a segmented code cache makes it easier to precisely control the size of only the segment that holds compiled method code.
In HotSpot, a method selected for eviction by the CCM must transition through several states before actually releasing the memory that it occupies. Each subsequent state transition currently only happens at successive safepoints. A CCM algorithm marks a method for eviction by changing its status to non-entrant. A non-entrant method cannot be entered, but can exist on the call-stack of an application thread. HotSpot transitions non-entrant methods to the state zombie if the method is not on any thread’s call-stack. Zombie methods can still be referenced by other methods via in-line caches. HotSpot updates the inline cache entries for zombie methods, if any, and then is able to release the space they occupy. Thus, CCM algorithms in HotSpot experience a lag between when method evictions are requested to create free space to when that space actually becomes available to store new compiled code in the code cache.
All our experiments for this work employ 11 DaCapo Java benchmarks with their default input size [6]. Table 1 shows some
---
1. We leave out batik, eclipse, and h2 because they fail with the default client build of HotSpot-9 without any of our modifications.
relevant properties of the different DaCapo benchmarks. For each benchmark in column 1, we show the total number of loaded methods in column 2 of the table. Columns 3 and 4 display the number and size of the compiled (hot) program methods after the startup iteration. Many more methods are expected to be compiled by the time the program reaches steady-state. All our run-time experiments are performed on a cluster of 8-core 2.84GHz Intel x86-64 machines running Fedora Linux as the operating system. To account for inherent timing variations during the benchmark runs, all the run-time results in this paper report the (geometric) average over 10 runs for each benchmark-configuration pair [9].
3. Current CCM Policies in HotSpot
In this section we assess the effectiveness of existing CCM policies in HotSpot to sustain program performance at different constrained code cache sizes.
We design an experimental setup to systematically limit the code cache size for each program. We first calculate the total accumulated size of all compiled methods in the default startup program run for each benchmark, and use it as the full code cache size for that benchmark (100% code cache size). Then, runs with constrained code cache sizes use 90%, 75%, 50%, 40%, and 25% of this full code cache space needed for each benchmark. Thus, the code cache size limits we use are specific to each benchmark.
We evaluate the performance of two CCM strategies, stop-compiler and stack-scan. The stop-compilation CCM method simply stops all JIT compilation if/when the code cache gets full. This CCM policy is simple and fast, and was therefore employed in several early HotSpot versions and other language VMs, such as Android’s Dalvik.
The latest stable HotSpot release uses a profiling-driven adaptive CCM method that we call stack-scan. The stack-scan policy uses a separate thread to sweep the code cache to remove some of the compiled code when the code cache usage gets close to or over its maximum size limit. The sweeper associates a separate counter with each compiled method in the code cache to keep track of method utilization. This counter is initially set to a high value after method compilation. A method’s counter is decremented every time the method is reached during the code cache sweep, and is reset to its original high value if it is found on the call-stack of any application thread. Hot methods are expected to be encountered often on some call-stack and will therefore maintain a high counter value. Methods with lower counter values are candidates from eviction from the code cache when pressure is high. This policy disables compilation if the code cache is full, and restarts compilation after the sweeper again creates adequate free space in the code cache.
Figure 1 plots the ratio of run-time program performance with the stop-compiler and stack-scan CCM strategies at constrained (90%, 75%, 50%, 40%, and 25%) code cache sizes, as compared to a baseline that uses the same (stop-compiler or stack-scan respectively) CCM policy with 100% code cache size. While the simplistic stop-compiler policy can be expected to perform poorly at very low code cache sizes, results in Figure 1 show that both these CCM policies fail to perform satisfactorily even with modest code cache constraints. On average, program performance degrades by 14%, 62.4%, 3.9X, 5.6X, and 10.1X at 90%, 75%, 50%, 40%, and 25% code cache sizes respectively with the simple stop-compiler policy.
We also observe that even with highly constrained code caches program performance remains significantly better than interpretation alone, showing the importance of JIT compilation. It is interesting to note that with the stop-compiler policy, program performance always improves with an increase in code cache size, as expected. However, this property is not maintained by the stack-scan policy. To reduce profiling overhead, the stack-scan CCM strategy collects and employs imprecise profiling data to guide its eviction decisions. The effect of program performance dropping with an increase in code cache size is a result of imperfect evictions exercised by the stack-scan policy due to poor available profile data.
We also notice that unlike the stop-compiler policy that only activates when the code cache gets full, the stack-scan policy is also triggered at high code cache pressures before the cache limit is actually hit. This property of stack-scan sweeper results in a slight performance drop even in the 100% code cache case.
Thus, these results reveal that modest and high code cache pressure can have a big negative performance impact with existing CCM strategies. Regrettably, (low cost, but imprecise) program profiling employed by the stack-scan policy appears to not offer acceptable benefit to performance over the stop-compiler method. In the later sections of this paper we explore if more accurate profiling data can enable the VM to more effectively sustain program performance at small code cache sizes.
4. Potential of Profiling Based CCM Policies
Implementation choices can affect the behavior and performance of the CCM sub-system in a VM. For example, the layout of the code cache and the amount of lag between issuing a method eviction request to having space available in the code cache can influence the performance of a CCM policy. Likewise, the cost and proficiency of dynamic profiling at run-time depends on the mech-
anisms supported in the available hardware and systems software, and are subject to improvement in future systems. It is hard to isolate the effects of such implementation features during actual VM runs to determine the real potential of different CCM strategies to sustain program performance at constrained memory sizes.
Therefore, we build a detailed simulation framework to compare different CCM strategies using offline and online-reactive profiling information in a VM and hardware-independent manner. A simulation framework allows us to effectively control profiling accuracy, cost, and VM implementation factors, while achieving realistic comparisons. Our simulation framework also enables us to design and evaluate the performance impact of an ideal profiling strategy that can deliver accurate and timely knowledge of all relevant aspects of future program behavior at zero run-time cost. Thus, the ideal CCM policy is able to determine the best methods to evict to minimize the performance impact on future program execution.
In this section we describe our simulation framework, discuss the different CCM algorithms that we modeled, and compare their effectiveness to manage program speed at reduced code cache sizes.
4.1 Performance Metric
The simulations need a simple, effective and accurate performance metric to compare the different CCM policies. In this section we describe the performance metric we devise for our simulation runs.
Method Hotness Count: JIT compilation in a (dual-mode) JVM attempts to improve program performance by reducing the amount of time spent by the program in the slower execution (interpretation) mode. The profiler in the HotSpot interpreter uses the method’s hotness_count (method invocation count + loop backedge count) to estimate the time spent in the method. Thus, a lower total hotness_count over all program methods indicates that the program spent less time in the interpreter and more time in high-performance compiled native code, which should result in better performance.
If a previously compiled method is evicted from the code cache, then future invocations of the method will execute in the interpreter, until the evicted method becomes hot again and is recomplied. Thus, on every request to create space for a new method compile, a good CCM algorithm should find a method to evict that minimizes the (future) time spent by the program in the interpreter. Hence, better code cache management will result in a smaller total program hotness_count over the entire program run. Our simulation framework computes the total program hotness_count as the measure of the quality of the code cache algorithm.
From Hotness Counts to Execution Time: Ultimately, we are interested in the effect of different CCM policies on program execution time. Therefore, we develop a mechanism to associate program hotness_count with execution time.
To relate hotness_counts with program run-time we execute each benchmark with many different configurations and extract the hotness_count and execution time (program wall-time) in each run. Each selected configuration varies some aspect of HotSpot’s default CCM algorithm and/or code cache size. We then plot all the points associating hotness_count and run-time for each benchmark, and use the facilities provided by the language ‘R’ to fit a (quadratic) curve over these points.
Figure 2 shows these plots for (ten) different DaCapo benchmarks (except tomcat to allow a nice fit on the page). The darker band around each curve (too narrow to see on most graphs) plots the 95% confidence interval, while the broader lighter band shows the 95% prediction interval. Thus, we can see that interpreter hotness_counts are a good indicator of overall program performance, even when the measured execution time includes all aspects of VM execution including JIT compilation, CCM, garbage collection, etc.
The per-benchmark mathematical equation forming the regression curve is used to associate hotness counts with time during later simulation runs. We employ this (simulated) time to compare different profiling policies.
4.2 Experimental Setup
In this section we describe the replay-based [17] simulation setup we use for our experiments.
Methodology: We instrument HotSpot to generate and log the profile and execution data for our simulation experiments. We conduct two runs for each benchmark. In the first run, HotSpot runs the program in the interpreter alone, and divides the execution into 10msec intervals. At the end of each 10msec interval, HotSpot dumps the hotness_counts of all program methods.
The other profile run is to determine the size of the compiled native code for all program methods. We run the HotSpot VM in its default mode, and record the space occupied by the native code generated for each compiled method in the code cache. For each benchmark, we also measure the maximum space needed for the code cache when all hot methods are compiled and resident in the cache.
Our evaluation runs use this profile data to simulate the operation of the code cache manager with different method eviction algorithms and different code cache sizes. These runs again use 100%, 90%, 75%, 50%, and 25% of the maximum code cache space needed for each benchmark.
At the end of each 10msec interval, a method is compiled if its total hotness_count exceeds the default HotSpot compilation threshold. If the code cache is full, then the code cache manager uses one of several strategies to find and evict existing methods from the code cache. On every eviction request, each algorithm finds contiguous space that is equal to or greater than the size of the new compiled method. If the new method does not occupy the entire space that is created, then the remainder can be merged with the adjacent unoccupied blocks, whenever possible. We experimented with the following method eviction algorithms:
Ideal: This algorithm looks into the future profile of the program to find (close to) the ideal set of contiguous methods to evict from the code cache to fit the new compiled method. It finds the set of methods that, combined together as a unit, have the smallest remaining hotness_counts. Thus, with this algorithm, methods that will never be used again are given the highest priority for deletion, and are sorted based on their size (largest size first). Methods that will never be compiled again are given the second highest priority and will be deleted in the order of their future hotness_counts (fewer counts first). Lowest priority is given to methods that will exceed their compile threshold again, sorted to order later compiles first.
Offline: This set of algorithms attempts to simulate a CCM policy that uses an offline profiling strategy. The algorithms use information from a prior program run, and aggregate the information over all intervals of the profile run. The profile data is used to sort methods in ascending order of their total hotness counts over the entire run. Then, in the later measured run, methods are selected for eviction from the code cache in the order of lowest counts first. We study the following offline profiling schemes: (a) Offline-same: The same input is used for the offline profiling run and the later evaluation/measured run.
(b) Offline-diff: The profiling run uses a different input for the profiling and measured runs. We use a profile with the DaCapo small input for measured runs with the default input. With different inputs for the profiling and measured runs, it is possible for the profile to not have any information about certain events (invoked methods) in the measured run. For such methods, this algorithm assigns the lowest priority for eviction.
Reactive: These CCM algorithms employ the online reactive profiling strategy, where profiling data collected during the past execution of the same program run is used to guide the CCM task to optimize the remaining program execution. In this case the best (set of contiguous) methods to evict is determined based on their hotness_count in earlier intervals of the same run. The following simple formula finds the hotness_count for each method by assigning progressively lower weights to older profile data:
\[ \tau_{n+1} = \alpha \times t_n + (1 - \alpha) \tau_n \]
where, \( \tau_{n+1} \) is the predicted hotness_count for the next interval, and \( t_n \) is the actual hotness_count in interval \( n \). We experimented with several different \( \alpha \) values of 0, 0.1, 0.5, 0.9, 1.0. We present the results for \( \alpha = 0.1 \), which provided the best overall numbers.
Stop compiler: A simple CCM policy that stops JIT compilation when the code cache gets full.
Stack scan: This is an implementation of a simplified version of HotSpot-8’s CCM algorithm in the simulator.
4.3 Results and Observations
In this section we present the results of our experiments to evaluate and compare the effectiveness of different CCM algorithms compared with an ideal profiling approach that uses knowledge of the future program behavior.
Performance Potential with Ideal CCM Policy Figure 3 shows the potential of ideal profiling with CCM at different constrained code cache sizes. Each bar in this graph plots the ratio of the (simulated) program run-time with the ideal CCM policy and indicated code cache size to the run-time with an ideal algorithm and an unlimited code cache. An unlimited code cache never needs to evict compiled methods from the cache. We observe that an ideal CCM algorithm often finds the right methods to evict from the cache to minimize performance impact. On average, we see very negligible performance losses with code cache sizes restricted to 90%, 75%, and 50% of required code cache space. Even with only 40% and 25% of desired code cache size many benchmarks do not see a noticeable performance impact with an (geometric) average performance loss of only 5% and 20% respectively. This result shows that an ideal feedback-driven CCM policy can significantly reduce an executing program’s code cache memory requirement with minimal performance losses in most cases.
Performance Potential of Other CCM Policies Next we compare the performance effectiveness of practical CCM policies as compared to the performance delivered by the ideal CCM strategy. The profiling driven CCM algorithms in our simulation framework have access to the most comprehensive, accurate, and timely profile data possible by that profiling technique with no run-time overhead. We have also implemented these policies in HotSpot, and in the next section we present evaluation and analysis of their run-time cost and impact on effectiveness.
Figure 4 shows the performance of the CCM algorithm when using the best Reactive profiling strategy (for $\alpha = 0.1$) as compared with the corresponding ideal approach for the same code cache sizes. We find that a good reactive strategy can achieve program performance close to ideal even for heavily constrained code cache sizes. The average performance losses compared to ideal with this reactive strategy are only 0.0%, 0.0%, 0.2%, 0.4%, and 0.8% for code cache sizes that are 90%, 75%, 50%, 40%, and 25% of the maximum needed, respectively. These results suggest that past program behavior is a good indicator of future program execution for code cache management. Remember that the cost of collecting this accurate profiling information at run-time is ignored during this simulation study. While we only show the results for the reactive algorithm with an $\alpha$ of 0.1, we note that other reactive schemes also do similarly well.
Figure 5 presents the performance comparison of the Offline-same code cache eviction algorithm compared with the corresponding ideal CCM approach. We see that with a perfectly representative offline profile, the CCM algorithm again performs quite well. The Offline-same strategy results in an (geometric) average performance loss of 0.0%, 0.1%, 0.6%, 1.5%, and 3.8% for our five code cache sizes respectively, compared to the ideal algorithm. As opposed to online profiling approaches that collect their data during the same program run, offline profiling strategies require a separate program execution to acquire the desired program behavior data. This data must then be structured and aggregated for use by adaptive VM tasks. This data aggregation can reduce the effectiveness of adaptive tasks by limiting its ability to customize for different sections/phases of the program run. The higher performance loss with the offline profiling based CCM strategy, compared with reactive-CCM, shows this negative impact of profile data aggregation.
Offline profiling suffers from another limitation. A different input set or execution environment can cause the application’s run-time behavior to differ from its behavior during the profiling run. The influence of this limitation on the efficiency of the adaptive task will depend on the likeness, of lack thereof, of the profiling and actual evaluation run. We attempt to measure the impact of this limitation with our offline-diff CCM configuration when profile data collected during program runs with the small DaCapo benchmark inputs are used during evaluation runs with the default input. As expected, we see a much more noticeable performance loss with this configuration. We find performance losses of 0.3%, 1.2%, 3.9%, 6.1%, and 10.1%, on average, with the Offline-diff scheme compared to ideal for the code cache sizes of 90%, 75%, 50%, 40%, and 25% respectively.
The default stack-scan CCM policy in HotSpot uses a low-overhead sampling based profiling mechanism, as explained earlier. The stack-scan CCM policy can be considered an instance of a low-cost and less precise online reactive profiling policy. The actual implementation of this policy in HotSpot has been heavily tuned for different situations, and is associated with several flags and other tuning knobs. We implemented a simpler variant of this complex policy in our simulator.
Figure 6 displays the performance comparison of the stack-scan CCM algorithm compared with the corresponding ideal CCM approach. We found that this policy fares quite poorly and achieves performance that is 31%, 50%, 2.44X, 2.83X, and 5.77X worse over the ideal configuration, on average, at 90%, 75%, 50%, 40%, and 25% code cache sizes respectively. Thus, these simulation results do a fair job of tracking the actual HotSpot performance numbers with the stack-scan policy displayed in Figure 1(b).
Additionally, we also simulated the simpler stop-compiler strategy that simply stops compilation if the code cache gets full. The stop-compiler algorithm is the simplest CCM policy and was found to achieve performance that is 6%, 39%, 3.01X, 3.65X, and 6.93X worse when the code cache is constrained to 90%, 75%, 50%, 40%, and 25% of the needed code cache space respectively, on average.
Other than stop-compiler, CCM policies evict program methods when the code cache gets full. These evicted methods will now run in the interpreter. A poor eviction decision (that is, evicting a hot method) will result in the method quickly becoming hot again, and will be recompiled. Thus, the greater the number of method evictions and recompletions triggered by a CCM strategy, the poorer is its quality and effectiveness. Additionally, the task of performing method evictions and recompletions will also incur an overhead at run-time, and can be used to further estimate the run-time cost or overhead of each CCM algorithm.
Table 2 shows the average number of methods evicted and recompletions of evicted methods performed by each of our simulated CCM strategies over all benchmark programs. As expected, we find that strategies that result in better performance keep more of the important methods in the cache longer. The stack-scan CCM policy is an exception because, unlike the other strategies, it temporarily disables compilation when the code cache gets full. For the remaining CCM algorithms, fewer poor eviction decisions in turn also result in fewer recompletions. We can see that availability of future program behavior information allows the ideal CCM policy to often evict methods that do not need to be recompiled later, especially at modest memory pressure. The average number of method evictions and recompletions steadily increases with smaller/constrained code cache sizes. In general, more effective CCM strategies predict better eviction candidates, and will likely incur less overhead at run-time and exhibit better overall performance.
In summary, our experiments in this section reveal several interesting and important results.
1. We find than an ideal CCM strategy with access to detailed profile information regarding future program execution can sustain efficient program performance even with heavily constrained code cache sizes. We expect this observation to fuel much further research in developing practical CCM policies that can realize high program speed and low memory consumption in the code cache in actual VMs.
2. It is encouraging to observe that several profiling-based CCM algorithms can achieve effectiveness close to the ideal policy. However, several hurdles will need resolution to realize these policies in a real VM. Online reactive CCM policies need to overcome the cost of profile collection at run-time. Offline profiling CCM strategies need to not only develop mechanisms to find representative program inputs to generate accurate offline profile data and make it available to the VM at run-time, but may also need to investigate approaches to resolve the profile aggregation effect inherent to offline profiling.
3. Our results also reveal that CCM strategies have the potential to be much more effective than HotSpot’s default stack-scan CCM policy. The stack-scan policy uses an approximate sampling-based online profiling approach to reduce dynamic overhead. It is unclear if the stack-scan policy’s poor performance is due to the imprecise nature of profiling data employed, or if it is caused by implementation decisions in HotSpot. We explore and discuss this issue further in the next section.
5. **Performance of Profiling Based CCM Policies in HotSpot**
In the last section we evaluated the potential effectiveness of several CCM strategies in a controlled simulation setting that allowed us to ignore profiling costs, and other known and unknown VM implementation issues. These simulation experiments provide encouraging results on the potential of CCM algorithms to sustain acceptable program performance even with very limited code cache sizes. Consequently, we explored and implemented a few CCM policies to understand and assess their behavior in the HotSpot JVM. In this section we present an assessment of an extended stack-scan, reactive, and offline CCM policies implemented in HotSpot.
5.1 **Impact of VM Implementation Choices**
Design and implementation choices exercised in the VM can make a large impact on the performance delivered by the CCM policies. The method eviction (or sweeper) mechanism implemented in the HotSpot JVM differs significantly from the perfect method employed by the simulation algorithm in Section 4. This difference impacts the properties of all CCM policies in HotSpot.
In particular, our simulation algorithm installs the compiled methods at the end of each interval. At that time, if sufficient contiguous space is not available, then the algorithm uses the selected CCM policy to find the methods to evict. These selected methods are then evicted and space to install the new compiled method is created instantaneously. The program execution can use the newly compiled method immediately in the next execution interval.
<table>
<thead>
<tr>
<th>Strategy</th>
<th>Evic</th>
<th>Recom</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ideal</td>
<td>48.6</td>
<td>0.9</td>
</tr>
<tr>
<td>Offline-same</td>
<td>149.5</td>
<td>64.5</td>
</tr>
<tr>
<td>Offline-diff</td>
<td>204.1</td>
<td>171.7</td>
</tr>
<tr>
<td>React-α = 0.1</td>
<td>277.9</td>
<td>105.0</td>
</tr>
<tr>
<td>Stack-scan</td>
<td>7459.6</td>
<td>6468.4</td>
</tr>
</tbody>
</table>
Table 2. Average number of method evictions and re-compilations for each code cache management algorithm.

In contrast, HotSpot’s sweeper mechanism works differently, and was described earlier in Section 2. With HotSpot, the space needed for future compilations needs to be made available before the compiled code is generated. Additionally, method eviction needs to follow several stages from active to non-entrant to zombie, requires several code cache sweeps, and therefore takes some time and is not instantaneous. In our current work, we do not attempt to make changes to the sweeper sub-system in HotSpot. Therefore, all CCM policies implemented in HotSpot have to respect the VM’s default sweeper mechanism.
5.2 **Stack-Scan No-Stop Compiler (SS-no-stop) CCM Policy**
We observe the CCM policy implemented in the latest HotSpot release (called stack-scan) performs poorly with small code cache sizes. These results with the default stack-scan policy were presented in Figure 1(b). Stack-scan is in fact an instance of a conservative low-cost reactive CCM policy that collects very limited profile information to guide its CCM decisions. Our simulation studies reveal that a reactive CCM strategy (albeit, one with access to detailed profile information) can achieve close to ideal performance numbers. Therefore, it is not entirely clear weather the stack-scan policy’s lower than expected performance is due to: (a) the quality of employed profile information, or (b) some other implementation factors. We conducted a study to first alleviate the effect of possible implementation factors.
The stack-scan CCM algorithm in HotSpot stops the JIT compiler if the code cache gets full. The policy should restart compilation once adequate code cache space becomes available and certain other conditions are satisfied. However, we observed that the compiler restart rarely happens for our benchmarks. We experimented with relaxing the conditions to restart compilation.
Figure 7 plots the performance of our most aggressive extended stack-scan policy that does not stop method compilations even when the cache is full. Generated compiled code that does not find room in the code cache will be discarded. We note that JIT compilation with the c1 compiler is very fast, and we found that the few discarded compilations do not add much overhead to the overall VM execution time. We observe that this simple extension
to HotSpot’s default stack-scan implementation makes it much more efficient at sustaining program performance at lower code cache sizes. On average, this extended stack-scan CCM policy degrades program speed by 0%, 6.1%, 43.1%, 89.9%, and 3.6X when code cache size is restricted to 90%, 75%, 50%, 40%, and 25% respectively, and as compared to a baseline that employs the same CCM policy with 100% code cache size.
5.3 Reactive (Online) CCM Policy
Next, we implement a reactive CCM policy in HotSpot based on our Reactive simulation setup that collects and employs more comprehensive profile information. This reactive CCM strategy implements method-specific counters that are incremented on each method entry and loop back-edge (in both the interpreter and the compiler). We again employ Equation 1 to calculate the hotness score of each method on every sweeper activation. This hotness score accounts for the parameter $\alpha$ to appropriately account for the method’s recent hotness and past (historical) hotness.
Our modified HotSpot sweeper evicts methods that have the smallest hotness scores until we evict 15% of the code cache (by size), or until the score passes below some costliness threshold. This heuristic allows the policy to keep deleting past 15% of free space as long as those additional methods evicted are cold. We found this heuristic to reduce the number of compile failures, increase responsiveness, and allow the VM to better handle any surges in compilation requests.
Figure 8 plots program performance with the reactive CCM policy in HotSpot. Similar to our simulation setup, we again use an $\alpha$ value of 0.1. Thus, we can see that the quality of profile information used by the CCM algorithm has a definite impact on its effectiveness. On average, we find that the reactive CCM policy leaves performance unchanged for 90% code cache size, and degrades program speed by 1.5%, 5.5%, 13.6%, and 99.3% with code cache size that is 75%, 50%, 40%, and 25% respectively, when compared to a baseline that employs the same reactive CCM policy with 100% code cache size. Note that the selected baseline allows us to ignore the cost of the profiling overhead. Program performance including the profiling overhead is presented and discussed in Section 5.5.
5.4 Offline-Same CCM Policy
An offline profiling based optimization has the benefit that there is no cost of collecting profiling data at run-time, and can simplify VM implementation by removing the need to support any profiling infrastructure in the VM. However, an offline profiling based strategy requires prior training runs, and generally aggregates profiling data across the training runs. Profile data aggregation makes it difficult to customize the optimization for different execution-time program phases.
We implemented an offline CCM policy in HotSpot based on our Offline-same simulation setup. We conduct a single training run in interpretation mode and calculate the overall hotness (invocation + loop back-edge) counts of all program methods. A list of methods sorted in ascending order of their hotness counts is given to HotSpot at the start of the program’s evaluation run. The CCM policy evicts methods from the code cache in this provided order.
Figure 9 shows program performance with the offline CCM policy in HotSpot. We observe that this strategy does not perform as well as the reactive CCM policies. On average, the offline CCM policy drops performance by 5%, 46%, 4.28X, 7.38X, and 12.37X with code cache size that is 90%, 75%, 50%, 40%, and 25% respectively, when compared to a baseline that employs the same offline CCM policy with 100% code cache size. Thus, even with perfectly representative offline profile data, our current implementation of this policy in HotSpot fails to deliver acceptable effectiveness. These poor results from the offline CCM policy contradict our observations from the simulation studies, and we will attempt to understand and possibly resolve this behavior in future work.
5.5 Overall Comparison of CCM Policies in HotSpot
Figure 10 compares the effectiveness of all the HotSpot CCM policies using a common baseline. The selected baseline is program performance with the simplest stop-compiler CCM algorithm and 2X the code cache size desired by each benchmark (200% code cache size). Remember, that 100% code cache size is benchmark-specific, and is computed by summing the sizes of all methods.
compiled for each benchmark in the default HotSpot configuration. We use 200% code cache size for our baseline because some CCM policies, like stack-scan, activate when available free cache space approaches some threshold of allocated cache size, and therefore trigger even with the 100% code cache size configuration.
From Figure 10 we can observe that the stop-compiler and off-line CCM policies only achieve acceptable performance at very modest memory pressure, when most methods are able to reside in the cache. At higher memory pressures, these policies degrade quickly and significantly. The comprehensive profile data available to the reactive policy allows it to make excellent decisions about which methods to evict, but the overhead of incrementing counters at every method entry and loop back-edge hurt execution time. Only at very heavily constrained code cache sizes does the benefit of better eviction decisions overcome the profiling cost with this strategy. In future work, we will further investigate the trade-offs between profile quality and cost for reactive CCM policies. Finally, HotSpot’s stack-scan is an implementation of a low-cost reactive CCM strategy that collects and uses approximate profile data. The effectiveness of HotSpot’s default stack-scan policy improves significantly with our extensions, and this SS-no-stop policy achieves the best or close-to-best overall performance results for most code cache sizes. Compared to the default HotSpot policy, the SS-no-stop CCM implementation improves performance by 20.4%, 39.0%, 41.3%, 54.9%, 57.8%, and 49.7% at our various code cache pressures respectively, on average.
It is important to appreciate that all these policies still perform much better than completely disabling JIT compilation and only using the interpreter. On average across all our benchmarks, interpreter-only execution time is 17.35 times worse than the stop-compiler CCM policy with 200% code cache size.
6. Related Work
Code caches are used to store translated and/or optimized code in managed language VMs and dynamic binary translators (DBT). Researchers in both these related areas have previously investigated issues regarding code cache layout and CCM to reduce memory consumption. In this section we present and compare past research that is related to our current work in this paper.
Zhang and Krintz were among the first researchers to study and present the effect of method eviction from the code cache on memory consumption and program speed in a JVM [25, 26]. Similar to our present research, this work evaluated the efficiency of off-line and online profiling techniques to find the appropriate set of methods to evict from the code cache. Additionally, they also studied techniques to decide when to invoke their eviction algorithm. However, this work was conducted in a compile-only JVM (Jikes RVM [1, 2]), which presents many different properties compared to the HotSpot JVM that employs a baseline interpreter and only compiles the hot program methods. The influence of a compile-only JVM, and Jikes in particular, cause critical differences in the profiling techniques employed and experimental setup used as compared to our current research. Moreover, the simulation studies are another unique contribution of our work that investigate the potential and properties of many different CCM algorithms in a controlled and VM-independent environment.
Several researchers have explored code cache eviction techniques for DBTs. Hazelwood and Smith found that a medium-grained FIFO eviction scheme achieved better performance than a single-block FIFO scheme by lowering replacement overhead [13]. Dynamo conducts a full cache flush at anticipated program phase changes when the trace generation rate becomes high [5]. Intel’s Pin DBT also supports a full code cache flush [15]. DynamoRio adaptively scales up the code cache size based on the program’s working set size, but does not implement algorithms to evict compiled blocks to reduce memory consumption in the code cache [7]. The Strata DBT implements techniques to bound code cache memory usage by reducing the space required for DTB-injected code [4]. Hazelwood and Smith proposed a generational code cache that can transition methods from a nursery cache to a persistent cache and evict unused code blocks from the cache [14]. Guha et al. designed a least-recently-used (LRU) profiling policy to selectively (or partially) flush code cache blocks for their DBT [11]. However, DBT code caches store blocks or traces instead of program methods, have fine-grained inter-block linking, and, in general, have different requirements compared to a managed-language JVM.
The organization of the code cache can influence the feasibility and effectiveness of CCM algorithms. Jikes RVM allocates compiled native code to Java objects that are then placed on the common heap with other data objects [1]. Jikes can then use the garbage collector (GC) to manage code cache objects and evict unused compiled code. Thus, low memory consumption by code cache objects can enable the Jikes RVM to place more data objects or reduce the frequency of GC [25]. While HotSpot earlier employed a single unmanaged code cache, the latest HotSpot release now employs a segmented code cache, with each segment servicing a distinct type to code [12]. Oracle’s Maxine JVM also partitions their code cache into different regions for holding the VM’s code, and that generated by its two compilers [24]. Most DBTs employ a single code cache, but may use either a simpler thread-private or a more space efficient thread-shared configuration [8]. The Strata DBT introduced a code cache organization split between the scratchpad and main memory to mitigate performance overhead on embedded systems [3]. We do not vary the default code cache organization in our current work, but plan to explore more effective code cache designs in the future.
7. Future Work
There are many avenues for future work on this topic. Our immediate plan is to further study the properties and improve the implementation of CCM policies in HotSpot, and add other policies, such as FIFO. Second, there is little current research to dynamically find the optimal code cache size for individual program executions in a VM. We will investigate techniques to adaptively and quickly find the ideal balance between performance and code cache size for each program at run-time for memory sensitive embedded devices. Third, a smaller code cache can result in more method evictions and recombinations. Our current work did not measure the effect of a smaller cache size on energy consumption with different CCM policies, which we plan to do in the future. Fourth, the placement of native code in a code cache can influence the amount of cache fragmentation and achieved I-Cache and I-TLB performance. We plan to better understand the impact of these tradeoffs and develop new JIT compilation orders or native code placement techniques in the code cache to optimize these performance factors. Fifth, we will study mechanisms to derive accurate and low-cost profiling data, and explore issues such as the tradeoff between profile data accuracy, quality and performance benefit. Finally, the code cache subsystem includes many components, including the CCM algorithm to find methods to evict, method eviction strategy, and code cache layout. In the future we plan to study and redesign all these components together to find the best overall strategy.
8. Conclusions
The goal of this work is to understand the potential and evaluate the effectiveness of different CCM policies to sustain program performance when code cache sizes are too constrained to hold all the desired hot methods during program execution in a managed-language VM. We design a creative simulation setup to investigate the potential of an ideal and many other practical CCM policies.
We discover that an ideal CCM strategy can allow the VM to maintain close-to-full program speed even with high code cache memory pressure. Furthermore, we found that profiling-based practical CCM policies can realize close to ideal results. Unfortunately, the current CCM strategy in the popular HotSpot Java VM, based on a low-cost approximate reactive profiling mechanism, produces large program slow-downs at small code cache sizes. We investigate this disparity in HotSpot’s CCM strategy. We implement extensions to HotSpot’s default CCM policy and design and re-engineer our other simulated CCM policies in HotSpot. Our CCM algorithms in HotSpot deliver positive results and uncover many other interesting questions that will need resolution to find an optimal CCM strategy for future runtime systems.
The abundance of managed languages and the expectation from small embedded devices to simultaneously support multiple resource-consuming programs makes memory capacity management an important issue for embedded systems. We hope that our work can guide researchers to develop/provide the necessary hardware and software structures to maximize the efficiency of CCM techniques for memory constrained embedded systems.
Acknowledgments
We thank the anonymous reviewers for their thoughtful and constructive feedback. This research is supported in part by the National Science Foundation under CAREER award CNS-0953268, and award CNS-1464288.
References
|
{"Source-Url": "http://web.eecs.utk.edu/~mrjantz/papers/CodeCache.pdf", "len_cl100k_base": 11336, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 35317, "total-output-tokens": 14164, "length": "2e13", "weborganizer": {"__label__adult": 0.0004177093505859375, "__label__art_design": 0.000278472900390625, "__label__crime_law": 0.0003147125244140625, "__label__education_jobs": 0.0005145072937011719, "__label__entertainment": 5.704164505004883e-05, "__label__fashion_beauty": 0.00018167495727539065, "__label__finance_business": 0.0002312660217285156, "__label__food_dining": 0.00031948089599609375, "__label__games": 0.0007238388061523438, "__label__hardware": 0.0024204254150390625, "__label__health": 0.0005159378051757812, "__label__history": 0.00026297569274902344, "__label__home_hobbies": 0.00010353326797485352, "__label__industrial": 0.0004808902740478515, "__label__literature": 0.00020802021026611328, "__label__politics": 0.0002613067626953125, "__label__religion": 0.00047135353088378906, "__label__science_tech": 0.0223541259765625, "__label__social_life": 6.216764450073242e-05, "__label__software": 0.004589080810546875, "__label__software_dev": 0.9638671875, "__label__sports_fitness": 0.0003743171691894531, "__label__transportation": 0.0007829666137695312, "__label__travel": 0.0002340078353881836}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61263, 0.0538]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61263, 0.14697]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61263, 0.89019]], "google_gemma-3-12b-it_contains_pii": [[0, 5507, false], [5507, 13171, null], [13171, 18613, null], [18613, 25262, null], [25262, 29279, null], [29279, 35267, null], [35267, 41184, null], [41184, 45627, null], [45627, 53540, null], [53540, 61263, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5507, true], [5507, 13171, null], [13171, 18613, null], [18613, 25262, null], [25262, 29279, null], [29279, 35267, null], [35267, 41184, null], [41184, 45627, null], [45627, 53540, null], [53540, 61263, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61263, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61263, null]], "pdf_page_numbers": [[0, 5507, 1], [5507, 13171, 2], [13171, 18613, 3], [18613, 25262, 4], [25262, 29279, 5], [29279, 35267, 6], [35267, 41184, 7], [41184, 45627, 8], [45627, 53540, 9], [53540, 61263, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61263, 0.11957]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
f991e284eeecb8d2fd5c9d11b9e6c4304373220b
|
Logic Based Modeling and Analysis of Workflows *
(Extended Abstract)
Hasan Davulcu Michael Kifer C.R. Ramakrishnan I.V. Ramakrishnan
SUNY at Stony Brook SUNY at Stony Brook SUNY at Stony Brook
davulcu@cs.sunysb.edu kifer@cs.sunysb.edu cram@cs.sunysb.edu ram@cs.sunysb.edu
Abstract
We propose Concurrent Transaction Logic (CTR) as the language for specifying, analyzing, and scheduling of workflows. We show that both local and global properties of workflows can be naturally represented as CTR formulas and reasoning can be done with the use of the proof theory and the semantics of this logic. We describe a transformation that leads to efficient algorithms for scheduling workflows in the presence of global temporal constraints, which leads to decision procedures for dealing with several safety related properties such as whether every valid execution of the workflow satisfies a particular property or whether a workflow execution is consistent with some given global constraints on the ordering of events in a workflow. We also provide tight complexity results on the running times of these algorithms.
1 Introduction
A workflow is a collection of cooperating, coordinated activities designed to carry out a well-defined complex process, such as trip planning, graduate student registration procedure, or a business process in a large enterprise. An activity in a workflow might be performed by a human, a device, or a program. Workflow management systems provide a framework for capturing the interaction among the activities in a workflow and are recognized as a new paradigm for integrating disparate systems, including legacy systems [20, 8]. Ideally, they should also help the user in analysis and reasoning about complex business processes.
It has been realized that analysis and reasoning about workflows requires a formal specification model with a well-defined semantics [18, 2]. In this paper, we develop a novel framework for specifying, analyzing and executing workflows based on Transaction Logic [5, 4, 6, 7].
Workflow representation frameworks. Figure 1 depicts three most common frameworks for specifying workflows: control flow graph, triggers (also known as event-condition-action rules), and temporal constraints.
Flow graphs are the primary specification means in most commercial implementations of workflow management systems. A typical graph specifies the initial and the final activity in a workflow, the successor-activities for each activity in the graph, and whether these successors must all be executed concurrently, or it suffices to execute just one branch nondeterministically. In Figure 1, all successors of activity a must be executed, which is indicated with the "AND" label. In contrast, "OR" indicates that when b is finished, there is a choice of executing d, h, then j or e then j. Successful execution of any one of these branches should suffice for the overall success of the workflow.
Arcs in a control flow graph can be labeled with transition conditions. The condition applies to the current state of the workflow (which, in a broad sense, may include the current state of the underlying database, the output of the completed tasks, the current time, etc.). When the task at the tail of an arc completes, the task at the head can begin only if the corresponding transition condition evaluates to true.
The Workflow Management Coalition [10] identifies additional controls, such as loops and sub-workflows. Various researchers have also suggested other types of controls, including alternative execution and compensation for failed activities [12, 17, 15, 25, 26, 4, 13]. However, control flow graphs have one obvious limitation: they cannot be used to specify global dependencies between workflow tasks, such as those expressed as global constraints on the right-hand side of Figure 1.
Defining workflows using triggers is yet another possibility [11]. However, this method is not as general as control flow graphs. For instance, like the graphs, triggers cannot be used to specify global task dependencies, and they are not sufficiently expressive when it comes to representing alternatives in workflow execution (depicted as "OR" nodes in Figure 1). In fact, it follows from a result in [7] that triggers with so-called "immediate" execution semantics can be represented using control flow graphs, and this result can be adapted to triggers with the "eventual" execution semantics as well. Since triggers can be "compiled into" the control flow graph, we shall be treating triggers as part of the control flow graph.
Other researchers proposed frameworks that rely exclusively on constraints to specify both local and global prop-
---
*This work is partially supported by a DLA/DARPA contract and by the NSF grants IRI-9404629, CCR-9705998, 9711386, 9510072 9404921, CDA-9504177, 9303181, INT-9600958.
1. Apply transformation enables us to determine:
(a) Whether every legal execution of a given workflow specification satisfies a particular property. Moreover, if some execution does not satisfy the property, then the verification procedure returns a counter example which is the most general execution of the workflow that violates the property in question.
(b) Whether the specification made up of the control flow graph and global constraints is consistent; and
(c) Whether some of the specified constraints are redundant.
2. The transformation eliminates the parts of the control graph that are inconsistent with the constraints, which facilitates scheduling of events at run-time.
3. The separation of control flow graph and global constraints in the workflow specifications leads to tighter complexity results for the verification problem.
Our results also contribute to the theory of Transaction Logic itself. Here, we essentially extend the efficient SLD-style proof procedure of $CTR$ from so called concurrent-Horn goals to a larger class of formulas, which incorporates temporal constraints (a more precise formulation appears in Section 2).
2 An Overview of Concurrent Transaction Logic
This section provides a short summary of the $CTR$ syntax, which is used in this paper to represent workflows. Due to space limitation, we cannot discuss the model theory of the logic or its proof theory. Instead, we rely on the procedural reading of $CTR$ statements. A thorough treatment of the main aspects of Transaction Logic appears in [6, 5, 4]. A fairly detailed, yet informal introduction can be found in [21].
$CTR$ is a conservative extension of the classical predicate logic in the sense that both its proof theory and the model theory reduce to those of the classical logic for formulas that do not cause state transitions (but only query the current state).
---
Klein constraints are of the form: (1) if events $a$ and $b$ both occur, then $a$ occurs earlier than $b$; or (2) if event $a$ ever occurs then $b$ must occur as well (before or after $a$).
Basic syntax. The atomic formulas of CTR are identical to those of the classical logic, i.e., they are expressions of the form $p(t_1, \ldots, t_n)$, where $p$ is a predicate symbol and the $t_i$'s are function terms. More complex formulas are built with the help of connectives and quantifiers.
Apart from the classical $\lor, \land, \neg, \forall$, CTR has two additional connectives, $\otimes$ (serial conjunction) and $\mid$ (concurrent conjunction), and two modal operators, $\odot$ (executability) and $\otimes$ (isolation). For instance, $\otimes(p(X) \otimes q(Y)] \mid (\forall Y (p(Y) \lor s[X, Y])))$ is a well-formed formula.
Informal semantics. Underlying the logic and its semantics is a set of database states and a collection of paths. For the purpose of this paper, the reader can think of the states as just a set of relational databases, but the logic does not rely on the exact nature of the states — it can deal with a wide variety of them.
A path is a finite sequence of states. For instance, if $s_1, s_2, \ldots, s_n$ are database states, then $\langle s_1 \rangle, \langle s_1, s_2 \rangle$, and $\langle s_1, s_2, \ldots, s_n \rangle$ are paths of length 1, 2, and $n$, respectively.
Just as in classical logic, CTR formulas assume truth values. However, unlike classical logic, the truth of CTR formulas is determined over paths, not at states. If a formula, $\phi$, is true over a path $\langle s_1, \ldots, s_n \rangle$, it means that $\phi$ can execute starting at state $s_i$. During the execution, the current state will change to $s_2, s_3, \ldots$, etc., and the execution terminates at state $s_n$.
With this in mind, the intended meaning of the CTR connectives can be summarized as follows:
- $\circ \phi \land \psi$ means: execute $\phi$ then execute $\psi$. Or, model-theoretically, $\phi \land \psi$ is true over a path $\langle s_1, \ldots, s_n \rangle$ if $\phi$ is true over a prefix of that path (say, $\langle s_1, \ldots, s_i \rangle$) and $\psi$ is true over the suffix (i.e., $\langle s_i, \ldots, s_n \rangle$). In terms of control flow graphs (cf. Figure 1), this connective corresponds arcs connecting adjacent activities.
- $\circ \phi \lor \psi$ means: $\phi$ and $\psi$ must both execute concurrently, in an interleaved fashion. This connective corresponds to the “AND”-nodes in control flow graphs.
- $\circ \phi \land \circ \psi$ means: $\phi$ and $\psi$ must both execute along the same path. In practical terms, this is best understood in terms of constraints on the execution. For instance, $\phi$ can be thought of as a transaction and $\psi$ as a constraint on the execution of $\phi$. It is this feature of the logic that lets us specify temporal constraints as part of workflow specifications.
- $\circ \phi \lor \circ \psi$ means: execute $\phi$ or $\psi$ non-deterministically. This connective corresponds to the “OR”-nodes in control flow graphs.
- $\not\circ \phi$ means: execute in any way, provided that this will not be a valid execution of $\phi$. There are many uses for this feature. One is that, just as in classical logic, the negation lets us define deductive rules which, in terms of the workflows, correspond to sub-workflow definitions. Negation is also an important component in temporal constraint specifications.
- $\not\circ \phi$ means: execute $\phi$ in isolation, i.e., without interfering with other concurrently running activities. This operator enables us to specify the transactional parts of workflow specifications.
- $\diamond \phi$ means: check if $\phi$ is executable at the current state. Section 7 discusses the role of the possibility operator $\diamond$ in workflow modeling.
Concurrent-Horn subset of CTR. Next, we define the implication, $p \leftarrow q$, as $p \lor \neg q$. The form and the purpose of the implication in CTR is similar to that of Datalog: $p$ can be thought of as the name of a procedure and $q$ as the definition of that procedure. However, unlike Datalog, both $p$ and $q$ assume truth values on execution paths, not at states.
More precisely, $p \leftarrow q$ means: if $q$ can execute along a path $\langle s_1, \ldots, s_n \rangle$, then so can $p$. If $p$ is viewed as a subroutine name, then the meaning can be re-phrased as: one way to execute $p$ is to execute $q$, the definition of $p$.
Having provided the intuition behind the logical connectives, it is now easy to see how control flow graphs are represented in CTR. For instance, the graph in Figure 1 is represented as:
$$a \otimes \left( (\text{cond_1} \otimes b \otimes ((d \otimes \text{cond_3} \otimes h) \lor e) \otimes j) \right) \mid (\text{cond_2} \otimes c \otimes ((f \otimes i \otimes \text{cond_4}) \lor (g \otimes \text{cond_5})) \otimes k)$$
(1)
Expressions of the above form are called concurrent-Horn goals. Formally:
- any atomic formula is a concurrent-Horn goal;
- $\phi \land \psi, \phi \lor \psi$ are concurrent-Horn goals, if so are $\phi$ and $\psi$;
- $\circ \phi$ and $\not\circ \phi$ are concurrent-Horn goals, if so is $\phi$.
It should be clear from the above example how control flow graphs translate into concurrent-Horn goals.
A concurrent-Horn rule is a CTR formula of the form $\text{head} \leftarrow \text{body}$, where $\text{head}$ is an atomic formula and $\text{body}$ is a concurrent-Horn goal.
In this paper, we limit our attention to non-iterative workflows, which means that we do not allow recursive concurrent rules. Section 7 discusses to what extent our present results apply to recursively defined workflows.
From the workflow point of view, the primary use for the rules is to represent sub-workflows. Indeed, since workflows and sub-workflows can be described using concurrent-Horn goals, we can use the rules of the form $\text{subWorkflowName} \leftarrow \text{subWorkflowDefinition}$ to define sub-workflows. For instance, $\text{subWorkflowName}$ can be used in workflow specifications as if it were a regular activity, thereby completely hiding the underlying structure of the activity from top-level specifications.
Observe that the definition of concurrent-Horn rules and goals does not include the connective $\land$. In general, $\land$ represents constrained execution, which is usually hard to implement, since constraints must be checked at every step of the execution. If a constraint violation is detected, a new execution path must be tried out. In contrast, the concurrent-Horn fragment of CTR is efficiently implementable, and there exist an SLD-style proof procedure that proves concurrent-Horn formulas and executes them at the same time [6].
The efficiency gap between concurrent-Horn execution and constrained execution is the main motivation for our results. In logical terms, we show that, for a large class of
constraints, formulas of the form \( \text{ConcurrentHornGoal} \land \text{Constraints} \) have an equivalent concurrent-Horn form (which, therefore, does not use the connective \( \land \)). In practical terms, therefore, this means that there is an efficient workflow scheduling strategy and, moreover, this strategy can be determined at “design time” of the workflow (as opposed to run-time scheduling of [27]).
**Elementary updates.** We complete our informal introduction to \( CTR \) by explaining how execution of (some) formulas may actually change the underlying database state. Most of the machinery has already been introduced (albeit very informally). What is missing is the notion of elementary updates.
In \( CTR \), elementary updates are represented by ordinary atomic, variable-free formulas. Syntactically, \( CTR \) does not distinguish elementary updates in any way, but the user may want to do so by adopting a syntactic convention (*e.g.*, a convention could be that \( \text{ins}_p(t) \) represents the act of insertion of tuple \( t \) into the relation \( p \)).
What distinguishes elementary updates is their semantics. Through some black magic, called *transaction oracle*, \( CTR \) arranges so that each elementary update is always true along certain arcs, i.e., paths of the form \( \langle s_1, s_2 \rangle \). Informally, one can think of an elementary update as a binary relation over states. For instance, if \( \langle s_1, s_2 \rangle \) belongs to the relation corresponding to an elementary update \( u \), it means that \( u \) can cause a transition from state \( s_1 \) to state \( s_2 \). Note that an update can be non-deterministic (any one of a number of alternative state transitions might be possible) and it is possible for an update to be applicable in certain states (but it is also possible for an update to apply in every state). This mechanism is very general. It accounts for a wide variety of elementary state changes: from simple tuple insertions and deletions, to relational assignments, to updates performed by legacy programs, to whatever workflow activities might do. The connectives of \( CTR \) are then used to build more complex updates from the elementary ones and then to combine these complex updates into even more complex update programs. This process of building \( CTR \) programs from the ground up is very natural and powerful.
The reader is referred to [4, 5, 6] for concrete examples.
Now we can explain how the various workflow activities (*e.g.*, the symbols \( \alpha, \beta, \gamma \), etc., in (1)) appear to \( CTR \). Namely, each activity is encoded as a variable-free atomic formula, \( \eta \), that represents either a sub-workflow defined by a set of concurrent-Horn rules, or it can represent an ordinary activities, in which case \( \eta \) is an elementary update. The latter is appropriate, since individual activities appear to workflow management systems as “black boxes” that perform state changes in ways that are (at best) only partially specified.
### 3 Events and Temporal Constraints
In workflow systems, tasks are typically modeled in terms of their significant, externally observable events, such as *start*, *commit*, or *abort*. For the purpose of control flow, we can represent these events as regular activities and incorporate them directly into the control flow graph in appropriate spots. The temporal constraints on workflow execution can then be expressed in terms of these events. Without loss of generality (as far as workflow modeling goes), we make the following assumptions:
- **No significant event occurs twice during the execution.** Indeed, we can always rename different occurrences of the same type of event.
- **Each significant event is represented as an elementary update that applies in every state.** This assumption is appropriate since, typically, a significant event amounts to nothing more than forcing a suitable record into the system log.
The first assumption translates into the following *unique event property*, which limits the kinds of concurrent-Horn goals that we shall consider in this paper:
**Definition 3.1 (Unique Event Property).** A concurrent-Horn goal \( G \) has the *unique event property* if and only if every significant event occurs at most once in any execution of \( G \). In such cases, we shall also say that \( G \) is a *unique-event goal*.
Unique-event goals can be recognized in linear time in the size of the goal, but we shall not present this algorithm here. Instead, we mention some obvious, yet useful properties of such goals, which suffice for our purposes. Let \( \alpha \) be a significant event. Then:
- If \( G = E_1 \odot E_2 \) is a unique-event goal and \( \alpha \) occurs in \( E_1 \) then it cannot occur in \( E_2 \).
- If \( G = E_1 | E_2 \) is a unique-event goal and \( \alpha \) occurs in \( E_1 \) then it cannot occur in \( E_2 \).
- If \( G = E_1 \lor E_2 \) then \( G \) is a unique-event goal if and only if so are both \( E_1 \) and \( E_2 \).
In the rest of this paper, all concurrent-Horn goals are assumed to have the unique event property.
Transaction Logic can express a wide variety of temporal constraints [5], but here we focus on a relatively simple algebra of constraints, which we denote by \( \text{Constraints} \). \( \text{Constraints} \) is as expressive as Singh’s Event Algebra [27]. Using these constraints we can specify that one task must start before some other task, that the execution of one task causes some other task to be executed or not executed, etc. These constraints are believed to be sufficient for the needs of workflow management systems, and they are far beyond the capabilities of the currently available commercial systems.
We specify all significant events in the system as propositions drawn from a set, denoted by \( \mathbb{E} \). In addition, we introduce one special proposition, path, which is defined as \( \phi \lor \neg \phi \), for any \( CTR \) formula. This means that path is true on all possible execution paths.
**Definition 3.2 (Constraints).** The basic building blocks of \( \text{Constraints} \) are formulas of the form \( \phi \odot \sigma \odot \sigma \), where \( e \in \mathbb{E} \). To save space, we shall use a shortcut for such formulas: \( \forall \phi \equiv \text{path} \odot \phi \odot \text{path} \), by definition. Then the following constraints form the constraint algebra \( \text{Constraints} \):
1. An example of the first kind is an update that deletes \( p(t) \) only if \( p(t) \) is true in the current state. An example of the second update is deletion of \( p(t) \) regardless of whether \( p(t) \) is true. If \( p(t) \) is not true in some state, \( s \), then no state transition takes place, but the update will still be true over the arc \( \langle s, s \rangle \).
2. This is one of the counterparts of “true” in classical logic. In \( CTR \), one can define other propositions that express various truths. For instance, we can express the proposition state, which is true precisely on paths of length 1, i.e., at states. It is also possible to express formulas that are true precisely on arcs, etc.
1. **Primitive constraints**: If \( e \in \text{CONST} \) then \( \forall e \) (event \( e \) must happen) and \( \neg \forall e \) (event \( e \) must not happen) are *primitive constraints* in \( \text{CONST} \). The constraint \( \forall e \) is a *positive primitive constraint* and \( \neg \forall e \) is a *negative primitive constraint*.
2. **Serial constraints**: If \( s_1, \ldots, s_n \in \text{CONST} \) are *positive primitive constraints*, then \( s_1 \circ \cdots \circ s_n \in \text{CONST} \) is a *serial constraint*. For convenience, primitive constraints are also viewed as serial constraints.
3. **Complex constraints**: If \( C_1, C_2 \in \text{CONST} \) then so are \( C_1 \land C_2 \), and \( C_1 \lor C_2 \).
Nothing else is in \( \text{CONST} \).
To get a better grasp of the capabilities of \( \text{CONST} \), here are a few typical constraints and their real-world interpretation:
- \( \forall e \land \forall f \) — events \( e \) and \( f \) must both occur (in some order);
- \( \neg \forall e \lor \neg \forall f \) — it is not possible for \( e \) and \( f \) to happen together.
- \( \neg \forall e \lor (\forall e \circ \forall f) \) — if \( e \) occurs, then \( f \) must occur some time later.
- \( \neg \forall e \lor \neg \forall f \lor (\forall e \circ \forall f) \) — if both \( e \) and \( f \) occur, then \( e \) must come before \( f \). This is known as Klein's order constraint [22].
- \( \neg \forall f \lor (\forall e \circ \forall f) \) — if \( f \) has occurred, then \( e \) must have occurred some time prior to that;
- \( \neg \forall e \lor \forall f \) — if \( e \) occurs, then \( f \) must also occur (before or after \( e \)). This is known as Klein's existence constraint [22].
Note that Definition 3.2 does not explicitly state that \( \text{CONST} \) is closed under negation. Nevertheless, we can show that it is.
**Proposition 3.3 (Splitting Serial Constraints).** Under the assumptions (9), any serial constraint is equivalent to a \( \land \)-conjunction of serial constraints, each composed of no more than two primitive constraints.
**Proof.** Consider a positive serial constraint composed of more than two primitive constraints: \( \forall e_1 \circ \forall e_2 \circ s \), where \( s \) is a serial constraint. We can show that this is equivalent to \( (\forall e_1 \circ \forall e_2) \land (\forall e_2 \circ s) \).
A serial constraint of the form \( \forall e \circ \forall f \) is called an *order constraint*; it says that \( \alpha \) and \( \beta \) must both occur and \( \alpha \) must occur before \( \beta \). (Note that this is somewhat stronger than Klein's order constraint mentioned earlier.)
**Lemma 3.4 (Constraint Negation).** Let \( C \in \text{CONST} \). Then \( \text{CONST} \) has a constraint that is equivalent to \( \neg C \) under the assumptions (9).
**Proof.** We can push negation down to the serial constraints in \( C \) using the classical De Morgan's laws for \( \land, \lor \), and \( \neg \), which are valid also in \( \text{CTR} \):
\[
- (\phi \land \psi) \equiv -\phi \land -\psi \\
- (\phi \lor \psi) \equiv -\phi \lor -\psi \\
-\neg\phi \equiv \phi
\]
Since \( -\neg\phi \) is equivalent to \( \forall e \), we only need to show that \( s = -\{\forall e_1 \circ \cdots \circ \forall e_n\} \) is equivalent to some constraint in \( \text{CONST} \).
By Proposition 3.2, we can assume that \( n < 3 \). If \( n = 1 \), then \( s = -\forall e_1 \) is a negative primitive constraint. If \( n = 2 \), then \( s = -\{\forall e_1 \circ \forall e_2\} \), which is equivalent (under the assumptions (2)) to \( -\forall e_1 \lor -\forall e_2 \lor (\forall e_2 \circ \forall e_1) \).
The previous results lead to the following normal form for the members of \( \text{CONST} \):
**Corollary 3.5 (Normal Form for Constraints).**
Every constraint in \( \text{CONST} \) is equivalent to a constraint of the form \( \forall a(\land_{i} \text{serialConstr}_i) \) where each \( \text{serialConstr}_i \) is either a primitive constraint or a serial constraint composed of two positive primitive constraints.
**Proof.** Follows from Proposition 3.3, Lemma 3.4, and the fact that, as in classical logic, \( \lor \) distributes through \( \land \) and vice versa.
Lemma 3.4 helps express certain constraints much more easily. For instance:
- \( -\{\forall e \circ \forall f\} \) — it is not possible for \( f \) to occur after \( e \) (and for \( e \) before \( f \)).
- \( -\{\forall e \circ \forall f \circ \forall g\} \) — if \( e \) happens and then \( f \) does, the event \( g \) cannot happen later.
4 Consistency, Verification, and Scheduling Problems for Workflows
This section and the next assumes that the control flow graphs do not have transition conditions on the arcs and that the specification does not contain concurrent-Horn rules that define sub-workflows. In Section 7, we discuss how our results apply to graphs that include these features.
Let \( G \) be a concurrent-Horn goal with unique event property (Definition 3.1), which represents a control flow graph, and let \( C \subseteq \text{CONST} \) be a set of constraints. The three central problems in workflow management systems can be formulated as follows:
**Consistency:** Determine whether \( G \) is consistent with \( C \).
**Verification:** Determine whether every legal execution of the workflow satisfies some property \( \Phi \in \text{CONST} \).
**Scheduling:** Find an execution path (or all paths) in \( G \) where \( C \) holds.
In \( \text{CTR} \), the consistency problem is tantamount to the existence of an execution for the formula \( G \land C \).
The verification problem is a special case of the consistency problem. Indeed, every legal execution of the workflow satisfies \( \Phi \) iff \( G \land C \land \neg \Phi \) cannot execute (i.e., \( G \) is inconsistent with \( C \land \neg \Phi \)).
The verification problem also subsumes the redundancy problem: \( \Phi \in C \) is redundant iff every legal execution of \( G \land (C - \{\Phi\}) \) satisfies \( \Phi \).
In this paper, we solve the verification problem constructively by transforming the formula \( G \land C \) into an equivalent concurrent-Horn formula \( G' \), which is always executable; or if this is impossible, \( G \land C \) reduces to \( \neg \text{path} \) — a non-executable transaction, which is the \( \text{CTR} \) analog of the classical *false*. Our algorithm is exponential in the size of \( C \) (in the worst case), which turns out to be inherent to the verification problem:
Proposition 4.1 (Complexity of Verification). Let $T$ be a concurrent goal and $C \subseteq \text{CONSTRAINTS}$ be a set of constraints. Then determining whether $G \land C$ is executable in $\text{CTR}$ is NP-complete.
The NP-hardness proof is by reduction to satisfiability of propositional logic [16]. That the decision problem is in NP follows from the fact that given an arbitrary sequence of events the satisfiability of a set of constraints and a unique-event control flow graph is decidable in polynomial time. A similar result has been previously obtained in [24]. However, their NP-completeness result is based on synchronization constraints. Each synchronizer corresponds to a combination of an existence constraint and an order constraint in our formalism. We tighten their complexity result by showing that synchronization per se is not a culprit: the problem is NP-complete even in the presence of just the existence constraints. In fact, it follows from our solution to the consistency problem that for order constraints the verification problem can be solved in polynomial time.
The scheduling problem needs more explanation. Workflow literature distinguishes two approaches to the problem: passive and proactive.
Passive schedulers receive sequences of events from an external source, such as a workflow or a transaction manager, and validate that these sequences satisfy all global constraints (possibly after reordering some events in the sequences). Several such schedulers are described in [26, 3, 19]. To validate a particular sequence of events, each of these schedulers takes at least quadratic time in the number of events. However, in passive scheduling environments, it is left to an unspecified external system to do consistency checking, to ensure the liveness of the scheduling strategy and to select the event sequences for validation. The known algorithms for these tasks are worst-case exponential.
In contrast to passive scheduling, our approach is proactive. In particular, we do not rely on any external system. Instead, we construct a "compressed" explicit representation of all allowed executions (i.e., executions that are known to satisfy all constraints). This representation can be used to enumerate all allowed executions at linear time per execution path (linear in the size of the path). In this way, at each stage in the execution of a workflow, the scheduler knows all events that are eligible to start. There is no need to validate constraints at run time, since the constraints are "compiled into" the structure.
More precisely, our solution to the scheduling problem capitalizes on the solution to the consistency problem. First, we verify that the specifications are consistent by transforming $G \land C$ into an equivalent concurrent-Horn goal $G'$, as explained above. The formula $G'$ plays the role of the aforesaid explicit representation for the set of all allowed executions of $G \land C$.
If the transformation succeeds (i.e., the specifications are consistent), enumerating all execution paths of $G'$ takes time linear in $G$ per path (note: linear in the original graph, not in the much larger graph $G'$!). This means that after the compilation, we can pick a legal schedule for workflow activities in time linear in the size of the original control flow graph. In contrast, the event scheduler of [27] has quadratic complexity.
Thus, while expanding the effort on consistency checking (which needs to be done anyway), we compile the original specifications into a form that lets us find allowable schedules much more efficiently than with the passive approaches of [27, 3, 19] (It should be noted that, these latter algorithms do not do consistency checks).
5 Compiling Constraints into the Control Flow Graph
We define the process of compiling the constraints in $\text{CONSTRAINTS}$ into unique-event goals by starting with simple events and extending the transformation to more complex ones. The unique-event property assumption is crucial for the correctness of the results in this section.
Compiling primitive constraints.
The following transformation takes a primitive constraint of the form $\neg \alpha \lor \neg \beta$ and a control flow graph (expressed as a concurrent unique-event goal) and returns a concurrent-Horn goal whose executions are precisely those executions of the original graph that satisfy the constraint. Intuitively, this means that the contraint is compiled into the graph.
Definition 5.1 (Primitive Constraint Compilation). Let $\alpha, \beta \in \text{EVENT}$. Then:
$$\text{Apply}(\neg \alpha, T) = \alpha$$
$$\text{Apply}(\neg \alpha, \beta) = \neg \alpha \lor \beta$$
$$\text{Apply}(\neg \alpha, \beta) = \neg \alpha \lor \beta$$
Let $T$ and $K$ be concurrent-Horn goals and let $\sigma$ stand for $\neg \alpha \lor \neg \beta$. Then:
$$\text{Apply}(\alpha, T \land K) = (\text{Apply}(\alpha, T) \land K) \lor (\text{Apply}(\beta, K) \lor \text{Apply}(\alpha, \beta))$$
$$\text{Apply}(\alpha, \beta) = \alpha \lor \beta$$
$$\text{Apply}(\alpha, \beta) = \alpha \lor \beta$$
Let $T$ and $K$ be concurrent-Horn goals and let $\sigma$ stand for $\neg \alpha \lor \neg \beta$. Then:
$$\text{Apply}(\alpha, T \land K) = (\text{Apply}(\alpha, T) \land K) \lor (\text{Apply}(\beta, K) \lor \text{Apply}(\alpha, \beta))$$
$$\text{Apply}(\alpha, \beta) = \alpha \lor \beta$$
$$\text{Apply}(\alpha, \beta) = \alpha \lor \beta$$
Observe that, due to the properties given in (3), the above transformation preserves the unique-event property of concurrent-Horn goals. For example, if $T = \gamma \land (\alpha \land \beta \lor \gamma) \land \delta$, then:
$$\text{Apply}(\gamma, T) = \gamma \land (\alpha \land \beta \lor \gamma) \land \delta$$
$$\text{Apply}(\gamma, T) = \gamma \land (\alpha \land \beta \lor \gamma) \land \delta$$
Proposition 5.2 (Primitive Constraint Compilation). If $T$ is a concurrent-Horn goal and $\sigma$ is a primitive constraint, then $\text{Apply}(\sigma, T) \equiv T \land \sigma$.
Compiling order constraints. Next we extend $\text{Apply}$ to work with order constraints, i.e., constraints of the form $\alpha \land \neg \beta$. (We do not use $\lor$ since $\lor$ is not a valid connective in $\text{EVENT}$.)
Definition 5.3 (Order Compilation). Let $\alpha, \beta \in \text{EVENT}$ and let $T$ be a concurrent-Horn goal. Then:
$$\text{Apply}(\alpha \land \neg \beta, T) = \text{sync}(\alpha < \beta, \text{Apply}(\alpha, \text{Apply}(\neg \beta, T)))$$
The transformation sync is designed to synchronize events in the desired order. It is defined as follows:
$$\text{sync}(\alpha < \beta, T) = T'$$
where $T'$ is like $T$, except that every occurrence of event $\alpha$ is replaced with $\alpha \circ \text{send}(\xi)$ and every occurrence of event $\beta$ is replaced with $\text{receive}(\xi) \circ \beta$, where $\xi$ is a new constant.
The actions send and receive are easily expressed in CTR (see [6]) and their semantics is what one would expect of such synchronization primitives: $\text{receive}(\xi)$ is true if and only if $\text{send}(\xi)$ has been previously executed. In this way, $\beta$ cannot start before $\alpha$ is done.
It is easy to verify that, due to [3], the above transformation preserves the unique-event property of concurrent-Horn goals. The following examples illustrate the transformation:
\[
\begin{align*}
\text{Apply}(\forall \alpha \circ \lor \beta \cdot \gamma \lor (\beta \circ \alpha)) &= \\
\text{receive}(\xi) \circ \beta \circ \alpha \circ \text{send}(\xi) &= \\
\text{Apply}(\forall \alpha \circ \lor \beta \cdot \alpha | \beta \circ \rho_1 | \ldots | \rho_n) &= \\
(\alpha \circ \text{send}(\xi)) | (\text{receive}(\xi) \circ \beta) | \rho_1 | \ldots | \rho_n \quad (4)
\end{align*}
\]
Proposition 5.4 (Order Compilation). Let $T$ be a concurrent-Horn goal and $\alpha, \beta \in \text{Excise}_T$. Then
\[
\text{Apply}(\forall \alpha \circ \lor \beta, T) \equiv T \land (\forall \alpha \circ \lor \beta).
\]
Compiling general constraints. We are now ready to extend apply to handle the general constraints in $\text{Constrs}_T$.
Definition 5.5 (Compiling General Constraints). Let $T$ be a concurrent-Horn goal. We assume that workflows are specified by a set of constraints $C$ and each individual constraint is represented in the normal form of Corollary 3.5. Therefore, $C$ can be written as a single dependency of the form
$$\delta_1 \land \delta_2 \land \ldots \land \delta_n$$
where each $\delta_i$ is in the normal form. In particular, all serial constraints are assumed to have been split into simpler order constraints. To extend apply to such constraints, we only need to define:
\[
\begin{align*}
\text{Apply}(C_1 \lor C_2, T) &\equiv \text{Apply}(C_1, T) \lor \text{Apply}(C_2, T) \\
\text{Apply}(C_1 \land C_2, T) &\equiv \text{Apply}(C_1, \text{Apply}(C_2, T))
\end{align*}
\]
As before, it is easy to see that the above transformation preserves the unique-event property.
Proposition 5.6 (Compiling General Constraints). Let $T$ be a concurrent-Horn goal and let $\delta$ be a constraint of the form (5). Then $\text{Apply}(\delta, T) \equiv T \land \delta$.
Knobs. After compiling the constraints $C$ into the graph $G$, several things still need to be done. First, the result of the compilation, $G_C$, can have literals of the form -path so, strictly speaking, $G_C$ is not a concurrent-Horn goal. However, we can use the following CTR tautologies to simplify $G_C$:
- $\text{path} \circ \phi \equiv \phi \circ \text{path} \equiv \text{path}$
- $\text{path} \circ \phi \equiv \phi \circ \text{path} \equiv \text{path}$
- $\text{path} \lor \phi \equiv \phi \lor \text{path} \equiv \phi$
The result would be either a concurrent-Horn goal or -path.
If the result is not -path, this still does not mean that we have a directly executable workflow specification. The reason is that the send/receive synchronization primitives may cause a “deadlock”. In model-theoretic terms, this means that such a formula is $\text{CTR}$-equivalent to -path, and in proof-theoretic terms this means that the proof procedure would halt and declare that no execution exists. In this case, we rewrite $G_C$ into -path.
Also, when the proof procedure declares a failure, it produces a concurrent-Horn goal, $G_{fail}$, which in a sense is the smallest subpart of the original workflow that is inconsistent with the constraints. In this way, the workflow designers can be given a feedback that might help them find the bug in their specifications.
Even if the proof procedure of $\text{CTR}$ does find a proof and thus $G_C$ is an executable workflow specification, $G_C$ may have sub-formulas where the send/receive primitives cause a cyclic wait, which we call knots.
The problem with knots is that, when they exist, finding an execution path in $G_C$ may not be a linear task (despite what we have promised in Section 4). Fortunately, it is easy to show that a variant of the proof theory of $\text{CTR}$ can be used to remove all knots from $G_C$ in time linear in the size of $G_C$. This procedure, which we call Excise, yields either a knot-free concurrent-Horn goal equivalent to $G_C$, or -path, if $G_C$ is inconsistent.
We illustrate the Excise process with the following example.
Example 5.7 (Knots). Let the graph $G$ be $\gamma \circ (\eta \lor (\alpha | \beta | \eta))$ and let the constraints be as follows: $c_1 \equiv \neg \alpha \lor (\forall \alpha \circ \lor \beta)$, $c_2 \equiv \neg \beta \lor (\forall \beta \circ \lor \eta)$, $c_3 \equiv \neg \alpha \lor (\forall \alpha \circ \lor \eta)$. The constraint $c_4$ says, if $\alpha$ takes place, then $\beta$ must also happen afterwards. The other constraints have similar interpretation. Omitting some intermediate steps, we have:
\[
\begin{align*}
\text{Apply}(c_1, G) &= \text{Apply}(\neg \alpha, G) \lor \text{Apply}(\forall \alpha \circ \lor \beta, G) = G_1 \lor G_2, \\
\text{where } G_1 &\equiv \gamma \circ (\alpha \circ \text{send}(\xi)) \lor \text{receive}(\xi) \circ \beta \lor \eta \text{ and } G_2 \equiv \gamma \circ \eta \\
\text{Apply}(c_2, G_1 \lor G_2) &= \text{Apply}(c_2, G_1) \lor \text{Apply}(c_2, G_2) = G_3 \lor G_2, \\
\text{where } G_3 &\equiv \gamma \circ (\alpha \circ \text{send}(\xi) \lor \text{receive}(\xi) \circ \beta \lor \eta) \text{ and } G_2 \equiv \gamma \circ \eta \\
\text{Apply}(c_3, G_1 \lor G_2) &= G_4 \lor G_2, \\
\text{where } G_4 &\equiv \gamma \circ (\alpha \circ \text{send}(\xi) \lor \text{receive}(\xi) \circ \beta \lor \eta) \lor \text{send}(\xi)
\end{align*}
\]
Finally, $\text{Excise}(G_1 \lor G_2) = \text{Excise}(G_4) \lor \text{Excise}(G_2)$. The proof procedure of $\text{CTR}$ finds no knots in $G_4$, so $\text{Excise}(G_2) = G_2$. On the other hand, it detects a knot in $G_4$ as follows.
First, the proof procedure “executes” $\gamma$ and deletes it from $G_4$. This results in a goal where each concurrent conjunct starts with a receive and the corresponding send’s are slated to occur only later in the execution. Therefore, the proof procedure halts and we declare a knot in $G_4$. Thus $\text{Excise}(G_4) = -$path. Hence, $\text{Excise}(\text{Apply}(c_1 \land c_2 \land c_3, G)) = G_2$.
Main results. We are now ready to summarize how the Apply and Excise transformations help solve the consistency, verification, and related problems. Theorems 5.8 through 5.10 assume that every activity in the workflow (except for the receive primitive) always succeeds. Without this
assumption, only the "if"-part of Theorem 5.8 holds and its corollaries, Theorems 5.9 and 5.10, must be adjusted accordingly.
Theorem 5.8 (Consistency Checking). Given a workflow specification \( G \land C \), it is inconsistent iff \( \text{Excise}(\text{Apply}(C, G)) = \neg \text{path} \).
Proof. Follows from Proposition 5.6 and the soundness and completeness of CTR proof theory.
Theorem 5.9 (Property Verification). Given a workflow specification \( G \land C \) and a property \( \Phi \in C_{\text{CONST}} \), there is a constructive way of verifying whether every execution of the workflow satisfies \( \Phi \).
Proof. \( \Phi \) is satisfied by every execution of the workflow if and only if \( \text{Excise}(\text{Apply}(\neg \Phi \land C, G)) = \neg \text{path} \). Otherwise, \( \text{Excise}(\text{Apply}(\neg \Phi \land C, G)) \) rewrites to the most general counterexample where \( \Phi \) fails to hold.
Theorem 5.10 (Redundancy Elimination). Given a workflow specification \( G \land C \) and a constraint \( \Phi \in C \), we can verify whether \( \Phi \) is redundant.
Theorem 5.11 (Complexity). Let \( G \) be a control flow graph and \( C \subseteq C_{\text{CONST}} \) be a set of global constraints in the normal form of Corollary 5.5. Let \( |G| \) denote the size of \( G \), \( N \) be the number of constraints in \( C \), and \( d \) be the largest number of disjuncts in a constraint in \( C \). Then
- The worst-case size of \( \text{Apply}(C, G) \) is \( O(d^N \times |G|) \).
- The worst-case time complexity of applying \( \text{Excise} \) is proportional to the size of \( \text{Apply}(C, G) \).
A simple corollary of Theorem 5.11 is: If \( C \) consists of serial constraints only, then \( d = 1 \) and the size of \( \text{Apply}(C, G) \) is proportional to \( |G| \).
6 Related Formalisms
Workflow verification. Process algebras and temporal logic formalisms have been used for modeling concurrent systems (akin to workflows) for over a decade now, and model checking is a pretty standard mechanism for verifying such systems.
However, the salient benefits of using CTR over process algebras and related formalisms are very tangible. First, CTR is a uniform formalism in which workflows can be specified, verified, and scheduled. This should be contrasted with the use of the algebras and temporal logic for specifying workflows, model-checking for their verification, and automata for scheduling.
Second, the use of CTR has enabled us to find more efficient verification algorithms. Indeed, standard model checking techniques [7] used for verification are worst-case exponential in the size of the control flow graph. This is often referred to as the state-explosion problem. In contrast, Apply is linear in the size of the graph — it is exponential only in the size of the constraint set (Theorem 5.11), which is a much smaller object. In a sense, Apply (along with the proof theory of CTR) can be viewed as specialized, more efficient model checker for the problem at hand.
Third, CTR integrates "process oriented" and "data oriented" features, which makes it easy to model processes that perform complex transformations over the database. In fact, extending our techniques to workflows that query the underlying database state is the next logical step for our work. In contrast, using process algebras to model database state is awkward and impractical.
Failure semantics. Failure atomicity is built into CTR semantics. However, more complex workflows require more advanced failure semantics, such as compensation [15]. Some such semantics can be expressed using the possibility operator of CTR, \( \Diamond \). Work is in progress on extending our framework to handle other failure semantics.
Acknowledgements. The authors would like to thank Tony Bonner for the helpful comments on a draft of this paper.
References
|
{"Source-Url": "http://www3.cs.stonybrook.edu/~cram/Papers/DKRR_PODS98/paper.pdf", "len_cl100k_base": 11276, "olmocr-version": "0.1.49", "pdf-total-pages": 9, "total-fallback-pages": 0, "total-input-tokens": 40877, "total-output-tokens": 13785, "length": "2e13", "weborganizer": {"__label__adult": 0.0003139972686767578, "__label__art_design": 0.00037550926208496094, "__label__crime_law": 0.00038361549377441406, "__label__education_jobs": 0.0010919570922851562, "__label__entertainment": 8.249282836914062e-05, "__label__fashion_beauty": 0.00017011165618896484, "__label__finance_business": 0.0005898475646972656, "__label__food_dining": 0.00038552284240722656, "__label__games": 0.000690460205078125, "__label__hardware": 0.00095367431640625, "__label__health": 0.0006527900695800781, "__label__history": 0.000263214111328125, "__label__home_hobbies": 0.00014770030975341797, "__label__industrial": 0.0006031990051269531, "__label__literature": 0.0003736019134521485, "__label__politics": 0.0002532005310058594, "__label__religion": 0.0004508495330810547, "__label__science_tech": 0.09063720703125, "__label__social_life": 9.91225242614746e-05, "__label__software": 0.0132598876953125, "__label__software_dev": 0.88720703125, "__label__sports_fitness": 0.00025725364685058594, "__label__transportation": 0.0006241798400878906, "__label__travel": 0.0001837015151977539}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 49985, 0.01624]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 49985, 0.52107]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 49985, 0.86263]], "google_gemma-3-12b-it_contains_pii": [[0, 4876, false], [4876, 6952, null], [6952, 13744, null], [13744, 20941, null], [20941, 27521, null], [27521, 34025, null], [34025, 41042, null], [41042, 44904, null], [44904, 49985, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4876, true], [4876, 6952, null], [6952, 13744, null], [13744, 20941, null], [20941, 27521, null], [27521, 34025, null], [34025, 41042, null], [41042, 44904, null], [44904, 49985, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 49985, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 49985, null]], "pdf_page_numbers": [[0, 4876, 1], [4876, 6952, 2], [6952, 13744, 3], [13744, 20941, 4], [20941, 27521, 5], [27521, 34025, 6], [34025, 41042, 7], [41042, 44904, 8], [44904, 49985, 9]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 49985, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-27
|
2024-11-27
|
e10b63a74c18d8a9d12203e8fd578c9731ee57fb
|
[REMOVED]
|
{"Source-Url": "https://core.ac.uk/download/pdf/50531798.pdf", "len_cl100k_base": 11445, "olmocr-version": "0.1.53", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 57659, "total-output-tokens": 13508, "length": "2e13", "weborganizer": {"__label__adult": 0.0006303787231445312, "__label__art_design": 0.00060272216796875, "__label__crime_law": 0.0006289482116699219, "__label__education_jobs": 0.0014142990112304688, "__label__entertainment": 0.00022864341735839844, "__label__fashion_beauty": 0.0003304481506347656, "__label__finance_business": 0.0004963874816894531, "__label__food_dining": 0.0008869171142578125, "__label__games": 0.0016241073608398438, "__label__hardware": 0.0019474029541015625, "__label__health": 0.0018663406372070312, "__label__history": 0.0005564689636230469, "__label__home_hobbies": 0.00019121170043945312, "__label__industrial": 0.0009307861328125, "__label__literature": 0.0012416839599609375, "__label__politics": 0.0006623268127441406, "__label__religion": 0.0010700225830078125, "__label__science_tech": 0.334228515625, "__label__social_life": 0.00017178058624267578, "__label__software": 0.006763458251953125, "__label__software_dev": 0.6416015625, "__label__sports_fitness": 0.0004425048828125, "__label__transportation": 0.0011243820190429688, "__label__travel": 0.00029730796813964844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 38956, 0.02311]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 38956, 0.50388]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 38956, 0.76562]], "google_gemma-3-12b-it_contains_pii": [[0, 1104, false], [1104, 3846, null], [3846, 7203, null], [7203, 10626, null], [10626, 12834, null], [12834, 15547, null], [15547, 19239, null], [19239, 22084, null], [22084, 25708, null], [25708, 29372, null], [29372, 32797, null], [32797, 36249, null], [36249, 38956, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1104, true], [1104, 3846, null], [3846, 7203, null], [7203, 10626, null], [10626, 12834, null], [12834, 15547, null], [15547, 19239, null], [19239, 22084, null], [22084, 25708, null], [25708, 29372, null], [29372, 32797, null], [32797, 36249, null], [36249, 38956, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 38956, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 38956, null]], "pdf_page_numbers": [[0, 1104, 1], [1104, 3846, 2], [3846, 7203, 3], [7203, 10626, 4], [10626, 12834, 5], [12834, 15547, 6], [15547, 19239, 7], [19239, 22084, 8], [22084, 25708, 9], [25708, 29372, 10], [29372, 32797, 11], [32797, 36249, 12], [36249, 38956, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 38956, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
9aa82389b7ce524268edcee904a929573ca5c9d8
|
Learning to Find Naming Issues with Big Code and Small Supervision
Jingxuan He
ETH Zurich, Switzerland
jingxuan.he@inf.ethz.ch
Cheng-Chun Lee
EPFL, Switzerland
cheng-chun.lee@alumni.epfl.ch
Veselin Raychev
Snyk, Switzerland
veselin.raychev@snyk.io
Martin Vechev
ETH Zurich, Switzerland
martin.vechev@inf.ethz.ch
Abstract
We introduce a new approach for finding and fixing naming issues in source code. The method is based on a careful combination of unsupervised and supervised procedures: (i) unsupervised mining of patterns from Big Code that express common naming idioms. Program fragments violating such idioms indicates likely naming issues, and (ii) supervised learning of a classifier on a small labeled dataset which filters potential false positives from the violations.
We implemented our method in a system called NAMER and evaluated it on a large number of Python and Java programs. We demonstrate that NAMER is effective in finding naming mistakes in real world repositories with high precision (~70%). Perhaps surprisingly, we also show that existing deep learning methods are not practically effective and achieve low precision in finding naming issues (up to ~16%).
CCS Concepts: • Software and its engineering → Software defect analysis; • Theory of computation → Program analysis.
Keywords: Name-based program analysis, Static analysis, Bug detection, Anomaly detection, Machine learning
1 Introduction
Names in source code are important as they often convey program semantics and capture developers’ intention, helping with tasks such as code understanding [8], completion [7], and debugging [38]. Names also play a key role in code quality and software maintenance [18], while some naming problems are misuses and even bugs [9, 28, 41]. The importance of names is reassured by many works in academia [30, 34] and industry [41]. Thus, a system able to automatically detect and fix naming issues is highly desirable.
Key challenge. While important, detecting and fixing naming issues in programs is a difficult task. Conventional methods such as abstract interpretation [21], symbolic execution [19], or testing [1], do not capture names and thus fail to detect naming issues. Indeed, since identifier names are closer to natural language, differentiating between good and bad names inherently requires statistical reasoning [13, 40]. Statistical naming issue detectors are ideally built on a large scale supervised dataset where real programs are labeled with having naming issues or not. However, to the best of our knowledge, such a large dataset does not exist and is hard to obtain with either manual or automatic approaches.
To address this challenge, existing works rely on either generating synthetic mistakes or on methods where labels are not required. Deep neural networks are currently trained and tested on large labeled datasets constructed by injecting synthetic defects in programs [9, 28, 45, 47]. However, despite achieving high test accuracy, we found these methods to have low precision in finding real world issues (discussed in § 5.6). While initially surprising, further thought reveals that the issue is caused by the fundamental problem of distribution mismatch: the distribution induced by generating synthetic defects does not match the distribution of real world mistakes. Alternatively, anomaly detection based approaches do not require labeled data but often require substantial manual effort for creating effective rules and tuning appropriate thresholds [34, 38, 41]. As a result, these systems are often limited to certain types of bugs (e.g., wrong usages of argument names) and language (e.g., Java).
This work. In this work, we propose a new recipe for learning to detect naming issues. The key idea is to split the learning procedure into two steps, see top of Figure 1: (i) mine name patterns, interpretable naming rules that capture a diverse set of naming idioms, from a large dataset of programs (i.e., Big Code), and (ii) train a binary classifier that uses high-level expressive features and predicts whether a violation of a name pattern is an issue. Importantly, step (i) does not require programs to be labeled with having issues or not, while step (ii) only requires a small labeled dataset, which is feasible to produce manually. This combination obviates the need to provide synthetic data and ensures that one trains and tests on the same real-world data. To use the method at inference time, we follow the steps shown at the bottom of Figure 1. Given a program fragment (with its representation): (i) we query the mined name patterns to check if the fragment violates any of them, and (ii) if it does, we query our learned binary classifier. A naming issue is reported only if the classifier predicts the violation to be true. The suggested fix is to change the relevant parts of the fragment so the originally violated pattern is satisfied.
We implemented our recipe in a system called Namer and evaluated it on both statically typed (Java) and dynamically typed (Python) languages. We show that Namer is significantly more effective at finding naming issues than state-of-the-art deep networks trained on synthetic defects.
Main contributions. Our key contributions are:
- A novel method for detecting and fixing naming issues in code consisting of interpretable name patterns mined from Big Code which capture a diverse set of naming idioms (§3.2, §3.3), and a machine learning classifier with expressive, high-level features to filter false positives (§4.2).
- An end-to-end implementation of our method in a tool called Namer. Namer supports Python and Java, leverages powerful static analyses for extracting semantic information, and is readily applicable to other languages (§5.1).
- An extensive evaluation of Namer on a large, real-world dataset containing millions of files from GitHub, demonstrating that Namer achieves high precision (∼70%) and is practically effective (§5). Our evaluation also shows that despite being accurate on programs with synthetic defects, current deep learning techniques [9, 28] achieve very low precision (i.e., up to ∼16%) on detecting real issues (§5.6).
2 Overview
In this section, we provide an overview of Namer on an illustrative example. We run the inference pipeline in Figure 1 to show how Namer finds and fixes a naming issue.
Example program. In Figure 2(a), we present a code snippet taken from an open-source Python project hosted on GitHub1. This snippet defines a class TestPicture inheriting from TestCase, which is from the unittest library and is used for representing test units. The TestPicture class contains a function test_angle_picture that calls assertTrue, a function from the parent class TestCase, with two arguments picture.rotate_angle and 90. We underline the described call statement in the figure.
The use of assertTrue in Figure 2(a) is incorrect. Based on the documentation [6], the second argument of assertTrue is an optional error message to display instead of a value to compare to. Therefore, we can infer that this code calls the wrong API function, which will cause unexpected behavior at runtime. Based on the code context, the correct function to call is assertEquals, which checks whether the values of the first two arguments are equal. Namer finds this bug and suggests to replace assertTrue with assertEquals. Next, we run the pipeline in Figure 1 on the buggy program statement and describe in detail how Namer finds and fixes this bug.
Program statement to AST+. Namer first parses the input program and obtains an abstract syntax tree (AST) for each program statement. Figure 2(b) shows the AST for the buggy program statement in our example with the nodes for picture.rotate_angle omitted for simplicity. Then the following transformations are applied on the parsed tree to obtain a transformed tree (AST+) as shown in Figure 2(c):
1. Replace integer values (i.e., 90) with a special token NUM.
2. Add a special node NumArgs(2) as the parent of the function call node Call, showing that the function call has two arguments (i.e., picture.rotate_angle and NUM).
3. Split each terminal node into subtokens based on standard naming conventions and insert a node NumST(k) where k is the number of subtokens in the original node. In the example, assertTrue is split into assert and True, and NumST(2) is inserted as a parent of the subtoken nodes. The nodes with value NumST(1) are added for node self and node NUM because they are unsplittable and contain only one subtoken.
These transformations allow Namer to detect naming issues on the subtoken level and make decisions based on additional information such as the number of function arguments.
Then, Namer applies an additional semantic transformation. Namer runs interprocedural points-to and data flow analyses which track the origin of each object and decorates
---
1https://github.com/paulhildebrandt/python-keynote/blob/master/tests/test_keynote_api.py
the AST with semantic information obtained from the analyses results. For our example program, the analyses identify that the origin of the object self is
```python
class TestPicture(TestCase):
...
def test_angle_picture(self):
rotated_picture_name = "IMG_2259.jpg"
for picture in self.slide.pictures:
if picture.relative_path:
== rotated_picture_name:
picture = self.slide.pictures[0]
assert True
break
```
(a) An example Python program from GitHub.
```plaintext
(d) Name paths extracted for the transformed AST in Figure 2(c).
```
```plaintext
(AST+ to name paths. Namer then traverses the transformed AST in a top-down fashion to extract name paths, our program abstraction for identifier name usages. A name path represents a path from the tree root to a leaf subtoken. In Figure 2(d), we show a list of name paths extracted from the transformed AST in Figure 2(c). Each name path contains two parts. The first part is a list where each element consists of a node and the index of the next node in the current node’s children list. The second part of a name path is a leaf subtoken. For instance, the first line represents the name path from the tree root to the leaf self. Along this path, the first child is always selected so the indices are all zero. We formally define name paths in § 3.1. Compared to existing syntactically constructed path abstractions [11–13, 33], our name paths contain richer semantic information from the transformed ASTs and have finer granularity as they can be used for modeling subtokens.
Pattern matching. The extracted name paths are then checked against a set of interpretable naming rules called name patterns. The name patterns are automatically mined from a large dataset of open source repositories and capture a wide range of common naming idioms. If the name paths violate any of the name patterns, then the statement deviates from common naming behaviors and a potential naming issue is detected by Namer. Moreover, the violated name pattern suggests how to fix the issue: modify the statement so that the violated pattern becomes satisfied. We formally define name patterns in § 3.2 and describe the mining algorithm in § 3.3. In Figure 2(e), we show an example name pattern which consists of two sets of name paths, the condition and the deduction. At a high level, the name pattern indicates if a program statement calls a function that satisfies the following three requirements, as specified by the three name paths in the condition:
1. the receiver is self and is an instance of TestCase, and
2. the first subtoken of the function name is assert, and
3. the second function argument is a numerical value,
then the second subtoken of the function name should be Equal, as specified by the name path in the deduction. Our example statement
```plaintext
Self.assertTrue(picture.rotate_angle, 90)
```
violates the name pattern in Figure 2(e) because its name paths satisfy the condition but contradict with the deduction. The violation exhibits a potential naming issue and the fix suggested by Namer is to replace True with Equal.
Classifying violated patterns. So far, the mined name patterns can already identify anomalous naming behaviors and report them as naming issues. Balancing the tradeoff between recall and precision is known to be difficult for anomaly detectors [38, 41], especially when our mining process is performed on millions of source files. As a result, with different choices of hyperparameters in the matching and mining processes, the mined patterns will either find very few issues because the violations are rarely triggered, or will
We start by formally defining ASTs for program statements. The tree (AST) for a program statement is a tuple \( N \) where \( \phi \) is a function mapping a node (either terminal or non-terminal) to its associated value. A parsed AST is shown in Figure 2(b).
Issues handled by Namer. Namer targets a wide range of program elements (e.g., variables, functions, API calls, types, etc.) and usually reveals issues (e.g., indescriptive names, wrong API usages, wrong types, etc.) where the names of the elements do not correctly capture the underlying code semantics. On the AST level, Namer targets all terminal nodes with code names. Examples of naming issues detected by Namer are shown in Tables 3 and 6. In Figure 2, we show a semantic defect that causes an unexpected program behavior. The vast majority of Namer’s reports are code quality issues that may impair code readability and maintainability.
3 Program Abstraction for Names
In this section, we describe our program abstractions for code names. We start by defining how we augment abstract syntax trees (ASTs) with results of program analyses and then how we extract name paths from these ASTs. Next, we define name patterns for representing common usages of identifier names. Finally, we present the algorithms for mining name patterns from a large dataset of code.
3.1 Abstract Syntax Tree and Name Path
We start by formally defining ASTs for program statements. Intuitively, this is part of the abstract syntax tree of the whole program, projected on a specific statement only.
Definition 3.1 (Abstract Syntax Tree). An Abstract Syntax Tree (AST) for a program statement is a tuple \( (N, T, r, \delta, V, \phi) \), where \( N \) is a set of non-terminal nodes, \( T \) is a set of terminal nodes, \( r \in N \) is the root node, \( \delta : N \to (N \cup T)^+ \) is a function mapping a non-terminal node to the list of child nodes, \( V \) is a set of node values, and \( \phi : (N \cup T) \to V \) is a function mapping a node (either terminal or non-terminal) to its associated value. A parsed AST is shown in Figure 2(b).
Given a parsed AST, Namer performs the following steps to obtain a transformed AST:
1. Transform all numerical values into a special token NUM, all string values into STR, and all boolean values into BOOL to improve generalization.
2. For each function definition or function call node \( n \), insert a node \( n' \) with value \( \text{NumArgs}(k) \) between \( n \) and \( n' \)'s parent, where \( k \) is the number of arguments in the definition or the call.
3. For each terminal node \( n \) whose value is an identifier name, split the name into subtokens based on standard naming conventions such as camelCase and snake_case.
4. For each terminal node representing an object name, insert a node whose value is the origin of the object as the parent.
Note that due to variadic or keyworded arguments, calls to the same function may have a different number of arguments. Such cases are captured by the AST and are not treated specially. The pattern mining process in § 3.3 will automatically learn the behaviors of such functions. We show an example of transformed ASTs in Figure 2(c). Transformed ASTs contain more fine-grained (e.g., subtokens), semantic information (e.g., results from static analyses) than parsed ASTs, which strengthens the precision of our name path and name pattern abstractions. A given transformed AST, the next step is to extract name paths defined in the following.
Definition 3.2 (Name path). A name path extracted from a (transformed) AST is a tuple \((S, n)\). We call \( S \) the prefix and \( n \) the end node. \( S \) is a list of non-terminal nodes along the path from the AST root to a terminal node. Formally, \( S = [(n_i, i_i)]_{i=1}^k \) where \( n_j \in N \) is a non-terminal node in the AST and \( i_j \in \mathbb{N} \) is an index, such that \( n_1 = r \) (\( n_1 \) is the root node) and \( \delta(n_i)[i_i] = n_{i+1} \) (\( n_{i+1} \) is the \( i \)th child of \( n_i \)). Node \( n \) is either the concrete terminal node where the AST path ends \( \delta(n_k)[i_k] = n \), i.e., \( n \) is the \( i \)th child of \( n_k \) or a special symbolic node \( \epsilon \) introduced for adding more degrees of freedom to name patterns defined later in § 3.2. We call the name path a concrete (resp., symbolic) name path if \( n \) is concrete (resp., symbolic).
Example 3.3. In the following, we show three name paths \( np_1, np_2, np_3 \). \( np_1 \) and \( np_2 \) are concrete name paths, and \( np_3 \) is a symbolic name path.
\[
np_1: \text{NumArgs}(2) \circ \text{Call} \circ \text{AttributeLoad} \circ \text{Attr} \circ \text{NumST}(2) \circ \text{TestCase} \circ \text{True}
\]
\[
np_2: \text{NumArgs}(2) \circ \text{Call} \circ \text{AttributeLoad} \circ \text{Attr} \circ \text{NumST}(2) \circ \text{TestCase} \circ \text{Equal}
\]
\[
np_3: \text{NumArgs}(2) \circ \text{Call} \circ \text{AttributeLoad} \circ \text{Attr} \circ \text{NumST}(2) \circ \text{TestCase} \circ \epsilon
\]
Definition 3.4 (Relational operators of name paths). Given two input name paths \( np_1 \) and \( np_2 \), we define the following two relational operators:
- \( np_1 \sim np_2 \): is true if \( np_1.S = np_2.S \). That is, if \( np_1.S \) and \( np_2.S \) have the same length, and all corresponding elements in \( np_1.S \) and \( np_2.S \) are equal; is false otherwise.
The definition of name patterns is generic and allows one to define different types of patterns to capture different kinds of naming idioms. Next, we introduce two types of name patterns in NAMER while leaving the addition of more patterns as future work items. The first one is consistency name patterns whose purpose is to ensure that code fragments with the same underlying semantics should be named consistently, which is an important aspect of code quality.
**Definition 3.7 (Consistency name pattern).** A consistency name pattern requires that $D = \{d_1, d_2\}$ (i.e., the deduction $D$ consists of two name paths $d_1$ and $d_2$), and both $d_1$ and $d_2$ are symbolic. The satisfaction and violation relationships of consistency name patterns are defined as follows:
- **Satisfaction:** $s$ satisfies $p$ if $s$ matches $p$ and $\forall a_1, a_2 \in A$. $(a_1.S = d_1.S \land a_2.S = d_2.S)$ implies $(a_1.n = a_2.n)$. Intuitively, it requires that any two name subtokens in the statement prefixed by paths $d_1$ and $d_2$ must be equal.
- **Violation:** $s$ violates $p$ if $s$ matches $p$ but does not satisfy $p$.
**Example 3.8.** In the following, we show a simple consistency name pattern which enforces that in a Python statement of the form `self.<name1> = <name2>`, the two names `<name1>` and `<name2>` must be equal.
Condition: Assign $\in$ AttributeStore $\cup$ NameLoad $\cup$ NumST(1) $\cup$ Object $\cup$ self
Deduction: Assign $\in$ AttributeStore $\land$ Attr $\land$ NumST(1) $\lor$ nil
Assign $\land$ NameLoad $\land$ NumST(1) $\land$ Str $\lor$ nil
The second type of name pattern used in NAMER is the confusing word name pattern. Its goal is to detect words that developers tend to mistakenly use and to suggest a correction. To obtain such patterns, we extract the pairs of mistaken and correct words, referred to as confusing word pairs.
**Confusing word pairs.** A confusing word pair consists of two words $\langle w_1, w_2 \rangle$ where in some prior version of the code, $w_1$ was used instead of $w_2$. We call $w_1$ the mistaken word and $w_2$ the correct word. We discover confusing word pairs from all of the (deduplicated) commits in our dataset. First, we apply a diff matching algorithm [37] over the AST of the program before and after the commit. For each pair of matched nodes, the names are split into subtokens and if there is one difference in the subtokens, the pair of subtokens is added as a confusing word pair. We extracted 950K confusing word pairs for Java and 150K for Python. Examples of mined confusing word pairs are: `<name, key>`, `<value, key>`, `<x, y>`, `<min, max>`, `<True, Equal>`.
**Definition 3.9 (Confusing word name pattern).** A name pattern is a confusing word name pattern if $D = \{d\}$ (i.e., the deduction $D$ consists of a single name path $d$) and there exists a pair $\langle w_1, w_2 \rangle$ in the set of mined confusing word pairs such that $d.n = w_2$. The satisfaction and violation relationships of confusing word patterns are defined as follows:
3.3 Mining Name Patterns from Big Code
After defining name patterns, the next question then is how to obtain the most representative name patterns adopted by most developers. We propose to mine name patterns from a large dataset of open source repositories, i.e., Big Code. To this end, we propose an algorithm based on the frequent pattern trees (FP trees) mining methods [24, 32]. The original procedures from [24, 32] treat all items the same. In our scenario, name paths can be part of a condition or a deduction. Therefore, in our algorithm, we split name paths into condition paths and deduction paths. At a high level, the algorithm iterates through programs in the open source repositories and extracts name paths to grow the FP tree. The nodes of the FP tree store the extracted name paths and their occurrence counts. After the growth of the FP tree, we traverse the FP tree to generate the most common name patterns based on the frequency information.
The algorithm minePatterns for mining name patterns is outlined in Algorithm 1. minePatterns takes a set of programs from open source repositories and the type of patterns to mine as input, and outputs a set of mined name patterns. First, we obtain the transformed ASTs of the program statements in the repositories by parsing the programs and applying the transformation rules (Line 2), and initialize the FP tree (Line 3). Then, we iterate through the obtained ASTs to update the FP tree (Line 4 to 7). For each AST, we extract the name paths by calling getNamePaths at Line 5. The name paths are then split (with the splitPaths function at Line 6) to condition (variable cond) and deduction (variable deduct). For the consistency name pattern, we treat pairs of name paths with the same end node as the deduction. For the confusing word name pattern, we treat name paths whose end node is equal to the correct word of a confusing pair as the deduction. The name paths not treated as the deduction are included in the condition. We iterate through all possible ways to split (Line 6), put the sorted condition and the sorted deduction into a single list, and update the FP tree with the resulted list (Line 7). During the update, we maintain the occurrence count of each node and set the flag isLast (initialized to be false) of the last node in the input list to true (not shown in Algorithm 1). The isLast flag is used later to determine when to generate name patterns. After the FP tree is constructed, we traverse its nodes to extract name patterns (Line 8) by calling a recursive algorithm genPatterns described in the next paragraph. Given the extracted name patterns (variable patterns), we further call pruneUncommon to prune uncommon patterns. To achieve this, we iterate through asts in the input dataset and count the number of matches and satisfactions for each pattern. We only keep the patterns whose ratio between the number of satisfactions and the number of matches is above a certain threshold (we used 0.8), which means that the pattern is commonly adopted in the dataset.
Algorithm 1: Mining name patterns.
Procedure minePatterns(progs, t)
Input : progs, a set of programs.
t, the type of the name patterns to mine.
Output: patterns, a set of mined name patterns.
1
asts = getStmtAsts(progs)
tree = FPTree()
for ast in asts do
5 paths = getNamePaths(ast)
6 for cond, deduct in splitPaths(paths, t) do
7 tree.update(sort(cond) + sort(deduct))
8
patterns = genPatterns(tree.root, list(t), t)
9
return pruneUncommon(patterns, asts)
• Satisfaction: s satisfies p if s matches p and ∀a ∈ A. a.S = d.S ⇒ a.n = d.n. Intuitively, it requires that the name subtoken prefixed by the name path d in the deduction must be equal to the correct word.
• Violation: s violates p if s matches p but does not satisfy p.
Algorithm 2: Generating name patterns in FP tree.
Procedure genPatterns(node, paths, t)
Input : node, current node in the FP tree.
paths, a list of visited name paths.
t, the type of the name patterns to mine.
Output: patterns, a set of mined name patterns.
1
paths.append(node.path)
2
patterns = set()
3
if node.isLast then
4 deduct = getDeduction(paths, t)
5 conds = getConditions(paths, t)
6 for cond in combinations(conds) do
7 patterns.add((cond, deduct))
8
for child in node.children() do
9 newPatterns = genPatterns(child, paths, t)
10 patterns = patterns ∪ newPatterns
11
return patterns
Figure 2(e) shows an example of a confusing word pattern.
PLDI ’21, June 20–25, 2021, Virtual, Canada Jingxuan He, Cheng-Chun Lee, Veselin Raychev, and Martin Vechev
where each combination can be seen as a valid condition, and to augment the ASTs for each statement in a program, the same procedure is performed recursively for the descendants of the current node (Line 10). We provide two examples below which illustrate the intermediate results of the algorithms.
Example 3.10 (A constructed FP tree). In Figure 3(a), we show a FP tree constructed after Line 7 of Algorithm 1 for mining confusing word name patterns. Each node represents a name path and shows its occurrence count. Green denotes nodes with the flag isLast set to true.
Example 3.11 (Results of running Algorithm 2). In Figure 3(b), we show all the extracted name patterns by running genPatterns on the FP tree in Figure 3(a). This result corresponds to variable patterns before Line 9 of Algorithm 1.
4 Detecting Naming Issues
In this section, we describe the points-to and data flow analyses for extracting the origins of objects, and the defect classifier for pruning false positives.
4.1 Static Analyses for Name Path Context
To augment the ASTs for each statement in a program, NAMER statically analyzes each source file of the program. Every file is analyzed in isolation, assuming every public method or function to be a possible entry point. NAMER computes flow-and context-sensitive Andersen style points-to analysis by using k-call site sensitivity with k set by default to 5, unless for a specific program this leads to a combinatorial explosion of more than 8 contexts per method on average. Practically, this happens for a few programs in our large dataset. Our points-to analysis is implemented in Datalog. We refer the reader to [44] for definitions of points-to analysis in Datalog. Since our points-to analysis is performed on a per-file basis, any function or method defined outside the file is considered to return a fresh allocation site. As a result, the analysis is not always sound, but this is not a requirement in our setting.
Using the results of the points-to computation, a dataflow analysis is performed for primitive types. This allows us for every variable, field, array access, and other action to obtain possible origins. The origin of objects is their allocation site. The origin of values is a function returning a value or $\top$ if the value was modified after its creation. When the origin sites are precisely computed (i.e. not abstracted to $\top$), this information is added to the AST. This effectively provides an abstraction where placing results of expressions into temporary variables, extracting methods, or doing other simple refactorings does not affect the augmented tree.
4.2 Defect Classifier
A violation of the name patterns indicates a potential naming issue but can result in a false positive. This is because when matching and naming pattern, we increase the violation consisting of patterns before Line 9 of Algorithm 1.
Table 1. Extracted features for a violation consisting a statement $s$ and a violated name pattern $p$.
<table>
<thead>
<tr>
<th>Index</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Number of name paths used to represent $s$</td>
</tr>
<tr>
<td>2</td>
<td>Number of statements identical to $s$ on the file level</td>
</tr>
<tr>
<td>3</td>
<td>Number of statements identical to $s$ on the repository level</td>
</tr>
<tr>
<td>4</td>
<td>Satisfaction rate of $p$ on the file level</td>
</tr>
<tr>
<td>5</td>
<td>Satisfaction rate of $p$ on the repository level</td>
</tr>
<tr>
<td>6</td>
<td>Satisfaction rate of $p$ over the entire mining dataset</td>
</tr>
<tr>
<td>7</td>
<td>Number of violations for $p$ on the file level</td>
</tr>
<tr>
<td>8</td>
<td>Number of violations for $p$ on the repository level</td>
</tr>
<tr>
<td>9</td>
<td>Number of violations for $p$ over the entire mining dataset</td>
</tr>
<tr>
<td>10</td>
<td>Number of satisfactions for $p$ on the file level</td>
</tr>
<tr>
<td>11</td>
<td>Number of satisfactions for $p$ on the repository level</td>
</tr>
<tr>
<td>12</td>
<td>Number of satisfactions for $p$ over the entire mining dataset</td>
</tr>
<tr>
<td>13</td>
<td>Whether $p$ targets on object name or function name</td>
</tr>
<tr>
<td>14</td>
<td>Number of name paths in $p$’s condition</td>
</tr>
<tr>
<td>15</td>
<td>Match ratio between $p$ and $s$</td>
</tr>
<tr>
<td>16</td>
<td>Edit distance between the original name and the suggested name</td>
</tr>
<tr>
<td>17</td>
<td>Whether the original and suggested names form a confusing word pair</td>
</tr>
</tbody>
</table>
A violation of the name patterns indicates a potential naming issue but can result in a false positive. This is because when matching and naming pattern, we increase the likelihood to trigger more violations so that most issues are not missed. Therefore, it is critical to prune false positives. To this end, NAMER feeds the violations of name patterns into a machine learning procedure. Formally, given a program statement $s$ and a name pattern $p$, NAMER invokes a feature extraction function $\phi$ and a binary classifier $\psi$. NAMER reports the violation consisting of $s$ and $p$ as a naming issue if and only if $\psi(\phi(s, p)) = true$. Intuitively, the violations classified by $\psi$ as true are highly likely to be true naming issues so they are reported. Those classified as false are recognized by NAMER as false positives so NAMER abstains from reporting them. $\psi$ can be obtained by applying off-the-shelf learning algorithms. To make the classification effective, the key then is to extract a set of expressive features with $\phi$.
Features for violations. In Table 1, we show the list of features extracted by $\phi$ for a violation. In general, these features calculate the statistics of the violation and capture the strength of the violation. In the following, we describe the features one by one.
Feature 1-3 capture characteristics of the program statement $s$. Feature 1 calculates the number of name paths extracted from $s$. The more name paths $s$ has, the more complex $s$ is. Feature 2 and 3 count the number of statements identical to $s$ in the file and the repository, respectively. More identical statements indicate a lower degree of anomaly.
Feature 4-14 measure various statistics of the violated pattern $p$. Feature 4-6 calculate the satisfaction rate (the number of satisfactions divided by the number of matches) of $p$ in the file containing the statement $s$, in the repository containing $s$, and over the entire dataset used for mining the name patterns, respectively. A higher satisfaction rate indicates that the naming idiom represented by $p$ is more commonly adopted. Feature 7-9 count the number of violations for $p$ and feature 10-12 count the number of satisfactions for $p$, both over three different levels. The larger feature 7-9 are or the smaller feature 10-12 are, the more common $p$ is. Feature 13 is a boolean feature that checks whether $p$ targets an object name or a method name. The motivation here is that during our early experiment, we found that most of the false positives came from name patterns targeting method names as inferring correct usages of method names typically requires more contexts. Feature 14 counts the number of name paths in $p$'s condition. The more name paths in the condition, the more difficult to match $p$.
Feature 15-17 jointly consider the statement $s$ and the violated pattern $p$. Feature 15 is the match ratio between $p$ and $s$, i.e., the number of name paths in $p$'s condition divided by the number of name paths in $s$ minus the number of name paths in $p$'s deduction. The higher the match ratio is, the better $p$ captures the structure of $s$, and the more likely the violation is a true naming issue. Feature 16 calculates the edit distance between the original name that violates the pattern and the suggested name. Smaller edit distance indicates a higher probability of a true naming issue (e.g., typo). Feature 17 is a boolean feature that checks whether the original name and the suggested name form a confusing word pair.
Unlike deep learning approaches [9, 28, 39] which use low-level embedding as initial features, all our features are high level, enabling our classifier to be trained with a small manually labeled dataset. Most of our features consider different levels (i.e., file, repository, and the entire dataset), as opposed to anomaly detection based approaches [34, 38, 41] which rely only on a single or few measures. This is an important design choice to make the classifier effective. As we show in § 5.5, the same feature can have different contributions to the final decision over different levels.
5 Experimental Evaluation
The evaluation of NAMER focuses on four main questions:
- What is the precision of NAMER on finding naming issues in open source repositories?
- What is the impact of points-to and data flow analyses (§ 4.1) and the defect classifier (§ 4.2)?
- What features are most important in the classifier?
- How does NAMER compare to existing deep neural network based approaches?
5.1 Implementation and Evaluation Setup
NAMER currently supports Python and Java though our framework is generic and can be applied to other languages.
Dataset. For both Python and Java, we obtained a large real world dataset of open source repositories on GitHub [3]. The Python (resp., Java) dataset contains about 1 million (resp., about 4 million) source files from 33, 144 (resp., 33, 308) repositories. We selected the set of repositories based on the highest number of stars. For finding confusing word pairs, we also used the entire histories of these repositories. Aware of code duplication on Github [35], we pruned our dataset to make it free from project forks and file-level duplicates.
Mining name patterns. To obtain name patterns, we ran the pattern mining algorithm introduced in § 3.3 over the entire dataset. The statistics of the mined patterns are discussed later in the evaluation. To avoid overfitting and strengthen generalization, we adopted standard techniques [12] to regularize name paths and patterns.
- We limited the number of name paths for a statement by simply keeping the first 10 paths.
- At Line 5 of Algorithm 1, we only returned frequent name paths that occurred more than 10 times in our dataset. As a result, over 99% of infrequent name paths were removed.
- At Line 6 of Algorithm 2, we limited the maximal number of name paths used in conditions to 10.
- At Line 9 of Algorithm 1, to prune uncommon patterns, we only returned name patterns that occurred more times than a given threshold. We found that setting the threshold to 100 for Python (500 for Java) yielded good results.
Training the classifier. To train the classifier, we need a supervised dataset where violations are manually labeled to true naming issues or false positives. In general, more training data can help the classifier perform better but the labeling process requires expensive human labor. Since we use simple models and high-level features, a small training set should be sufficient. For both Python and Java, we manually labeled 120 violations, which strikes a good tradeoff between precision and the amount of manual effort needed for building the NAMER tool.
Among all labeled violations, one half were labeled true and the other half were labeled false. We leveraged cross-validation for model selection. We selected the support vector machine model with the linear kernel (the other choices are logistic regression and linear discriminant analysis) as it resulted in the best cross-validation results. We used feature standardization and principal component analysis as a preprocessing step for the features.
Testing and metric. At test time, we ran the pattern matching module of Namer over the entire Python and Java dataset excluding the samples used for training the classifier. For each dataset, we randomly selected 300 violations and ran the trained classifier on the selected violations to obtain the final reports of Namer. Then, we inspected all of Namer’s bug reports and found that Namer is able to report various kinds of naming issues. Following [39], we classify a naming issue into two categories:
- **Semantic defect**: a naming issue is a semantic defect if the name in the evaluated program causes unexpected program behavior, is inconsistent with the program semantics, or may introduce errors.
- **Code quality issue**: a naming issue is a code quality issue if it is not a semantic defect but impairs code quality by confusing the readers or is inconsistent with the naming style in the file. It is strongly recommended to fix those issues to improve code readability.
If a report does not belong to the above two categories, we mark it as a false positive. We provide examples of semantic defects, code quality issues, and false positives in Tables 3 and 6. We calculate precision as the number of reported naming issues (including semantic defects and code quality issues) divided by the total number of reports. Note that unlike standard bugs (e.g., buffer overflow), naming issues are less studied and their importance lacks common understanding. Moreover, the severity of code quality issues can be subjective and varies among developers. To demonstrate that the issues reported by Namer are relevant, we conducted a small user study with professional developers, described in § 5.4.
**Speed of Namer.** The experiments were performed on a 28-core machine with two 2.60 GHz Intel Xeon E5-2690 CPUs and 512 GB RAM running Ubuntu 18.04. The experiments for [9] and [28] in § 5.6 require GPU so they were performed on a machine with RTX 2080 Ti GPUs.
Namer is quite performant with its runtime dominated by the program analyses described in § 4.1. On average, Namer spent 20ms for Java and 39ms for Python analyzing one source file on a single core of the test server. Because each file is analyzed separately, we parallelized the analysis on all 28 cores of the machine.
<table>
<thead>
<tr>
<th>Baseline</th>
<th>Report</th>
<th>Semantic defect</th>
<th>Code quality issue</th>
<th>False positive</th>
<th>Precision</th>
</tr>
</thead>
<tbody>
<tr>
<td>Namer</td>
<td>134</td>
<td>5</td>
<td>89</td>
<td>40</td>
<td>70%</td>
</tr>
<tr>
<td>w/o C</td>
<td>300</td>
<td>13</td>
<td>124</td>
<td>163</td>
<td>46%</td>
</tr>
<tr>
<td>w/o A</td>
<td>88</td>
<td>2</td>
<td>50</td>
<td>36</td>
<td>59%</td>
</tr>
<tr>
<td>w/o C & A</td>
<td>300</td>
<td>12</td>
<td>108</td>
<td>180</td>
<td>40%</td>
</tr>
</tbody>
</table>
5.2 Results for Python
We now evaluate Namer on the Python dataset. We first discuss the precision of Namer. Then, we provide examples of naming issues found by Namer. At last, we show detailed statistics on the mined name patterns and the classifier.
**Precision of Namer.** For Python, we obtained 134 reports by running the trained classifier on the randomly selected 300 violations. The results of the manual inspection are shown in the first row of Table 2. Among the reports by Namer, we manually found 5 semantic defects, 89 code quality issues, and 40 false positives, resulting in a precision of 70%. The high precision demonstrates the effectiveness of Namer on real world Python code.
**Necessity of classifier and analyses.** We now investigate the impact of the static analyses and the defect classifier on the effectiveness of Namer. To this end, we constructed three baselines, by excluding the defect classifier, the analysis module, or both, from Namer. For each baseline, we similarly inspected the bug reports on 300 randomly selected violations. The inspection results are reported in rows 2–4 of Table 2. Row 2 shows the results for the baseline where the classifier was excluded from Namer, i.e., only pattern matching was performed. All 300 violations were reported as naming issues where 163 were false positives, resulting in a precision of 46%. Row 3 shows the results for the baseline for which the program analyses in § 4.1 were not performed. Compared to Namer, this baseline found fewer semantic defects and fewer code quality issues and was less precise.
From the comparison, we can see that the analyses and the classifier are both necessary parts of Namer. The analyses not only improved Namer’s precision but also helped Namer find more issues. The classifier may filter out some true positives but significantly reduced the number of false positives, resulting in significantly higher precision while retaining similar recall as before, which is a desired property in practice as it allows Namer’s users to spend minimal efforts on inspecting the bug reports.
Examples of reports made by Namer. We ran Namer on more statements in our Python dataset and present examples of reports in Table 3. For each example, we show the reported statement and the fix suggested by Namer:
- **Example 1** is similar to the one described in § 2 but the call has different arguments. The issue may cause unexpected runtime behavior. Namer correctly suggested to change `assertTrue` to `assertEqual`.
- **Examples 2 and 3** show the cases where Namer detects and fixes deprecated API calls. In Example 2, `xrange` is a built-in function in Python 2 but gets removed in Python 3. In Example 3, `assertEqual` is a deprecated function in the `unittest` library.
- **Example 4** contains a typo. Namer proposed a correct fix to the typo by changing `or` to `of`.
- **Examples 5 and 6** are code quality issues where the original names do not conform with the standard naming conventions. In Example 5, `args` is used for keyworded variable length arguments. However, `kwargs` should be used instead for keyworded arguments and `args` should be used for non-keyworded variable length arguments. Namer suggested the exact fix for Example 5. In Example 6, `N` is used as the abbreviation for the library `numpy`. However, `np` is commonly used and is a more informative name.
- **Examples 7 and 8** are false positives of Namer. Example 7 asserts whether a given file path in the path variable is a symbolic link by calling the function `islink`. However, Namer wrongly suggested to replace the function with `exists`. This is because the usage of `exists` inside `assertTrue` is more frequent than the usage of `islink` in our dataset. For Example 8, Namer suggested to replace `line` with `log` according to the violated pattern. However, `line` is not an incorrect or confusing name according to the semantics of the function (not shown here).
The above examples show that Namer can find and fix different kinds of naming issues, including those that require a deep semantic understanding of the program (e.g., correct usage of API calls).
Statistics on pattern mining and classification. In total, 65, 619 name patterns were mined for the Python dataset. 496, 306 program statements, 439, 508 source files (50% of all source files), and 30, 388 repositories (92% of all repositories) violated at least one of the mined patterns. These numbers show that the mined patterns did not represent only very rare events in our dataset.
As discussed in § 5.1, we used cross-validation for model selection. Now we report the cross-validation results for our selected model (support vector machine). We randomly took 80% of labeled samples for training the model and then tested the trained model on the remaining 20% samples. We repeated this for 30 times. The average accuracy, precision, recall, and F1 score were 81%, 81%, 81%, and 80%, respectively.
Distribution of naming issues per pattern type. In our evaluation, around 29% of the reports came from consistency name patterns, while 81% of the reports were from confusing word patterns. The sum is above 100% because 10% of the reports were detected by both patterns. To obtain more detailed statistics on the precision of Namer per pattern type, we ran Namer on all of the repositories in our dataset, randomly selected 100 new reports for each of the two name pattern types, and manually inspected the selected reports. The inspection results are shown in Table 4. We can see that the confusing word name pattern tended to recover more semantic defects, while the consistency name pattern produced fewer false positives.
### Table 3. Examples of reports by Namer for Python.
<table>
<thead>
<tr>
<th>Index</th>
<th>Reported statement</th>
<th>Suggested fix</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td><code>self.assertTrue(vec, 4)</code></td>
<td><code>Equal</code></td>
</tr>
<tr>
<td>2</td>
<td><code>for i in xrange(10)</code></td>
<td><code>range</code></td>
</tr>
<tr>
<td>3</td>
<td><code>self.assertEqual(3, val)</code></td>
<td><code>Equal</code></td>
</tr>
<tr>
<td>4</td>
<td><code>num_or_process = 3</code></td>
<td><code>of</code></td>
</tr>
<tr>
<td>5</td>
<td><code>def evolve(self, ..., **args):</code></td>
<td><code>kwargs</code></td>
</tr>
<tr>
<td>6</td>
<td><code>self.sz = N.array(sz)</code></td>
<td><code>np</code></td>
</tr>
<tr>
<td>7</td>
<td><code>self.assertTrue(os.path.islink(path))</code></td>
<td><code>exists</code></td>
</tr>
<tr>
<td>8</td>
<td><code>self.read_line_block()</code></td>
<td><code>log</code></td>
</tr>
</tbody>
</table>
### Table 4. Manual inspection of 100 Python Namer reports per pattern type with a breakdown of code quality issues.
<table>
<thead>
<tr>
<th>Inspection outcome</th>
<th>Consistency</th>
<th>Confusing word</th>
</tr>
</thead>
<tbody>
<tr>
<td>Semantic defect</td>
<td>1</td>
<td>9</td>
</tr>
<tr>
<td>Code quality issue</td>
<td>71</td>
<td>53</td>
</tr>
<tr>
<td>False positive</td>
<td>28</td>
<td>38</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>Breakdown of code quality issues</th>
</tr>
</thead>
<tbody>
<tr>
<td>Confusing name</td>
</tr>
<tr>
<td>Indescriptive name</td>
</tr>
<tr>
<td>Inconsistent name</td>
</tr>
<tr>
<td>Minor issue</td>
</tr>
<tr>
<td>Typo</td>
</tr>
</tbody>
</table>
Table 5. Precision of Namer and baselines on 300 randomly selected violations from the Java dataset. "C" stands for the defect classifier and "A" stands for the static analyses.
<table>
<thead>
<tr>
<th>Baseline</th>
<th>Report</th>
<th>Semantic defect</th>
<th>Code quality issue</th>
<th>False positive</th>
<th>Precision</th>
</tr>
</thead>
<tbody>
<tr>
<td>Namer</td>
<td>97</td>
<td>2</td>
<td>64</td>
<td>31</td>
<td>68%</td>
</tr>
<tr>
<td>w/o C</td>
<td>300</td>
<td>0</td>
<td>66</td>
<td>72</td>
<td>48%</td>
</tr>
<tr>
<td>w/o A</td>
<td>138</td>
<td>0</td>
<td>90</td>
<td>208</td>
<td>31%</td>
</tr>
<tr>
<td>w/o C & A</td>
<td>300</td>
<td>0</td>
<td>87</td>
<td>213</td>
<td>29%</td>
</tr>
</tbody>
</table>
5.3 Results for Java
Next, we evaluate Namer on the Java dataset. The procedures and experiments for the Java dataset were performed in the same way as those for the Python dataset.
**Precision of Namer.** The results of Namer on the 300 selected violations from the Java dataset are shown in the first row of Table 5. The precision was 68%, similar to the precision of Namer for the Python dataset (70%), showing that the framework is generic and can precisely detect naming issues for different types of languages.
**Necessity of classifier and analyses.** The last three rows of Table 5 show the results when the classification module, the analyses module, and both of them, were excluded from Namer, respectively. Namer outperformed all three baselines in precision by a large margin, reassuring the importance of the static analyses and the classifier.
**Examples of reports found by Namer.** We present examples of reports found by Namer for Java in Table 6:
- **Example 1** calls `getStackTrace`, which returns the stack trace information, with receiver e (a thrown exception). However, the return value is not assigned to any variable, which makes the call redundant. As a result, the user might miss important information about the exception. Namer suggested to fix it by calling `printStackTrace` to print the stack trace to the standard error stream.
- **Example 2** uses type `double` for loop index variable i, which may cause unexpected program behavior due to floating-point operations. Namer suggested to use type `int`.
- **Example 3** catches a `Throwable` variable e. `Exception` and `Error` are both subclasses of `Throwable`. Catching `Throwable` includes catching `Error`. However, the official documentation [2] suggests that `Error` should not be caught. Namer correctly suggested to catch `Exception` instead of `Error`.
- **Example 4–6** show cases where Namer suggested more descriptive variable names than the original names. In Example 4, Namer detected and fixed a typo where `public` is misspelled into `publick`. Example 5 is an Android API call for creating a new activity. The argument of the function `startActivity` is of type Intent and thus Namer suggested to use the name `intent` instead of i. Example 6 dismisses an Android dialog represented by the variable `progDialog`. Namer suggested to replace `progDialog` with `progress` to indicate that the dialog is a progress dialog.
- **Examples 7 and 8** are two false positives. In Example 7, Namer suggested to change the name `outputWriter` to `StringWriter` to better fit the class name `StringWriter`. However, according to program context, the original name is better. In Example 8, Namer suggested to replace class `ConektaObject` with `JsonObject` because `JsonObject` is used more frequently in our dataset. However, `ConektaObject` should be the correct class.
**Statistics on pattern mining and classification.** For the Java dataset, 79, 417 name patterns were mined, which resulted in over 1.8 million violations. Moreover, 11% (i.e., 453, 450) of all the source files and 77% (i.e., 25, 496) of all the repositories had at least one violation. Similar to Python, the mined patterns had a high coverage for the Java dataset. In the cross-validation, the average accuracy, precision, recall, and F1 score were 90%, 90%, 90%, and 89%, respectively.
**Distribution of naming issues per pattern type.** For the Java dataset, around 14.5% of the reports came from consistency name patterns and 91.7% of the reports were from confusing word patterns. The sum is above 100%, because 6.2% of the reports were detected by both patterns. To obtain more detailed precision statistics, we ran Namer on all the repositories in our evaluation and obtained 100 new reports of each of the two bug pattern types. Then, we performed a manual inspection. For the consistency pattern, 0, 76 and 24 reports were classified as semantic defects, code quality issues and false positives, respectively. For the confusing word pattern, the number of semantic defects, code quality issues and false positives was 3, 36 and 61, respectively.
Table 7. Code quality issues selected for our user study described in § 5.4.
<table>
<thead>
<tr>
<th>Issue category</th>
<th>Original code snippet</th>
<th>Detected issue & suggested fix</th>
</tr>
</thead>
<tbody>
<tr>
<td>Inconsistent name</td>
<td>if docstring is not None: self.help = docstring</td>
<td>Rename help to docstring</td>
</tr>
<tr>
<td>Minor Issue</td>
<td>def fullpath_set(self, value): self._fullpath = value</td>
<td>Rename value to a more descriptive name like fullpath</td>
</tr>
<tr>
<td>Confusing name</td>
<td>def <strong>init</strong>(self, song, **kwargs): self._defaults = CODED_DEFAULTS self._factory = song</td>
<td>Change some name to avoid code like self._factory = song</td>
</tr>
<tr>
<td>Typo</td>
<td>self.port = por</td>
<td>Rename por to port</td>
</tr>
<tr>
<td>Indescriptive name</td>
<td>def reset(self, *e): self._autostep = 0</td>
<td>Rename e to a more descriptive name</td>
</tr>
</tbody>
</table>
Table 8. User study results of seven professional developers on whether to accept code quality issues reported by Namer.
<table>
<thead>
<tr>
<th>Issue category</th>
<th>Not accepted</th>
<th>Accepted with IDE plugin</th>
<th>Accepted with pull request</th>
<th>Would even fix manually</th>
</tr>
</thead>
<tbody>
<tr>
<td>Confusing name</td>
<td>0</td>
<td>3</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>Indescriptive name</td>
<td>0</td>
<td>3</td>
<td>2</td>
<td>2</td>
</tr>
<tr>
<td>Inconsistent name</td>
<td>2</td>
<td>0</td>
<td>4</td>
<td>1</td>
</tr>
<tr>
<td>Minor issue</td>
<td>2</td>
<td>4</td>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>Typo</td>
<td>1</td>
<td>2</td>
<td>1</td>
<td>3</td>
</tr>
</tbody>
</table>
Table 9. Feature weights of the learned classifier.
<table>
<thead>
<tr>
<th>Feature</th>
<th>File level</th>
<th>Repo level</th>
<th>Entire dataset</th>
</tr>
</thead>
<tbody>
<tr>
<td>Identical statement</td>
<td>0.6345</td>
<td>-2.854</td>
<td>-</td>
</tr>
<tr>
<td>Satisfaction count</td>
<td>1.86</td>
<td>0.468</td>
<td>-0.7305</td>
</tr>
<tr>
<td>Violation count</td>
<td>-1.121</td>
<td>-1.0655</td>
<td>1.5565</td>
</tr>
</tbody>
</table>
5.4 User Study on Severity of Code Quality Issues
To gain more insights into the severity of code quality issues found by Namer, we performed a small user study showing 5 Python reports to professional developers from a software company with no mandatory naming style guides. The 5 reports, shown in Table 7, were chosen by randomly picking one sample from each category in the breakdown of Table 4 and were shuffled. The participants were not aware of Namer and were not told that the reports were provided by an automatic tool. They were asked if and at what conditions they would accept the changes in the reports as the project maintainers. The conditions include (i) at coding time with an automatic IDE plugin, (ii) after coding time with an automatic pull request, and (iii) the developer is willing to fix the issue manually once seeing it.
The study received 7 responses which are shown in Table 8. The results demonstrate that the developers found the issues relevant. Only in 5 cases, an issue was not accepted and in 9 cases, the developers were even willing to fix the issues themselves. For most cases, developers accepted a report only if an automatic tool like Namer, either in the form of an IDE plugin or pull requests, locates the issue and suggests a fix for them.
5.5 Understanding Classifier Decision Making
Seeing the effectiveness of Namer, one natural question to ask is why the classifier performed well and based on what the classifier made decisions. Since we used a linear model on standardized features, the weights of the learned classifier are useful in measuring how much each individual feature contributes to the final decision. In Table 9, we summarize the feature weights averaged from the learned classifiers for Python and Java. The three rows show the weights of feature 2-3, 4-6, and 7-9, respectively.
We can see that the absolute values of all weights were non-negligible, meaning that the classifier makes decisions based on various features. Moreover, the classifier learned interesting behaviors non-obvious to a human: the contribution of the same type of feature can be completely opposite over different levels. For example, for the violation count feature, the weights over file and repository level were negative but over the entire dataset, the weight was positive. This phenomenon demonstrates that jointly considering both local and global features is another key reason for the classifier to precisely distinguish between true issues and false positives. The above observations are in contrast to previous works [34, 38, 41] which involves only one or few weak predictors, and can give insights for future bug finding tools.
5.6 Comparison with Deep Learning Approaches
We now compare Namer with two state-of-the-art deep learning based approaches for finding name based issues,
Table 10. Precision comparison of GGNN, GREAT and NAMER on 134 randomly selected reports for Python.
<table>
<thead>
<tr>
<th>System</th>
<th>Semantic defects</th>
<th>Code quality issues</th>
<th>False positives</th>
<th>Precision</th>
</tr>
</thead>
<tbody>
<tr>
<td>GGNN</td>
<td>1</td>
<td>20</td>
<td>113</td>
<td>16%</td>
</tr>
<tr>
<td>GREAT</td>
<td>2</td>
<td>9</td>
<td>123</td>
<td>8%</td>
</tr>
<tr>
<td>NAMER</td>
<td>5</td>
<td>89</td>
<td>40</td>
<td>70%</td>
</tr>
</tbody>
</table>
Table 11. Precision comparison of GGNN, GREAT and NAMER on 97 randomly selected reports for Java.
<table>
<thead>
<tr>
<th>System</th>
<th>Semantic defects</th>
<th>Code quality issues</th>
<th>False positives</th>
<th>Precision</th>
</tr>
</thead>
<tbody>
<tr>
<td>GGNN</td>
<td>2</td>
<td>7</td>
<td>88</td>
<td>9%</td>
</tr>
<tr>
<td>GREAT</td>
<td>2</td>
<td>3</td>
<td>92</td>
<td>5%</td>
</tr>
<tr>
<td>NAMER</td>
<td>2</td>
<td>64</td>
<td>31</td>
<td>68%</td>
</tr>
</tbody>
</table>
GGNN [9] and GREAT [28]. Both works leverage deep neural networks over program graphs to detect misuses of variable names and reported high accuracy on testing datasets with synthetic bugs. However, the high testing accuracy does not necessarily reflect their capability of finding real world issues. This is because the distribution of true issues is not necessarily the same as the distribution of synthetic issues used to train and test the network models. In fact, both works presented only limited evaluation results on finding real problems in code. The authors of GGNN presented case studies on bugs but did not include quantitative measures. GREAT’s precision dropped to 29.4% on a dataset of only hundreds of buggy and non-buggy programs that the authors collected by comparing GitHub commits. Therefore, the practical effectiveness of GGNN and GREAT on finding real world issues is still unknown. Through our evaluation, we aim to understand the practical effectiveness of these works and compare their precision with NAMER.
Training and measuring accuracy. We re-implemented the pipeline of GGNN and GREAT based on the machine learning modules open sourced by the authors [4, 5]. To obtain training program graphs, we followed the original works [9, 28] to introduce synthetic changes to the programs in our Python and Java datasets. Note that it is impossible to train GGNN and GREAT with real issues as we did with NAMER. This is because deep networks are data hungry and a dataset with a sufficient amount of real issues does not exist and is hard to obtain with either manual labor or automation. The training processes took around 70h to 130h.
After training, we measured the accuracy of GGNN and GREAT to ensure that each individual model can achieve high accuracy as reported in the original papers [9, 28]. We did not aim to compare the accuracy across those models. For each model, we sampled a subset of programs from our dataset, introduced synthetic changes to them, and constructed 10,000 new program graphs. The new graphs were not used in training though the original programs could be. Then, we fed the graphs into the trained models and obtained the accuracy. For GGNN, the accuracy was 71% (resp., 83%) for Python (resp., Java). For GREAT, the classification accuracy, localization accuracy and repair accuracy for Python (resp., Java) were 91%, 83%, and 79% (resp., 91%, 82%, and 81%), respectively.
From these results on accuracy, we could reproduce the fact that GGNN and GREAT result in high accuracy on the dataset of synthetic code changes. Further, these numbers closely match the results in the original papers [9, 28].
Precision of detecting issues. Next, we evaluate GGNN and GREAT on finding real world issues. To this end, we tested GGNN and GREAT on our dataset without any synthetically introduced changes. Same as NAMER, we inspected a randomly selected set of issue reports for GGNN and GREAT. All true variable misuses were classified as semantic issues as they usually cause unexpected program behaviors. We found that some reports were not variable misuses but pointed to other kinds of naming issues, e.g., unused variables. We included them as true positives and classified them into semantic issues and code quality issues based on our criterion in § 5.1.
A factor that affects the precision and recall of a bug finding tool is the confidence level above which a report is made. For GGNN and GREAT, we could not determine the total number of true issues that can be theoretically reported by the respective models in comparison to the total number of issues discoverable by NAMER, but based on a sample of the frequency of the issues in code, we estimated that a name misuse predictor should be applicable to at least one fifth of the naming problems. To compensate for this effect, we tuned the confidence levels so that both GGNN and GREAT reported around 5x fewer issues than NAMER.
The results on randomly inspected reports for Python are shown in Table 10. Both GGNN and GREAT found very few true issues, resulting in the reported low precision: GGNN achieved 16% precision with 1 semantic defect and 20 code quality issues; GREAT achieved 8% precision with 2 semantic defects and 9 code quality issues. This low detection capabilities of the networks do not mean that there are no true issues of the specific kind, it just shows that the probability distribution of issues encoded in the predictor did not correlate with that of real naming issues. As shown in Table 11, the networks also achieved low precision for Java (9% for GGNN and 5% for GREAT). We tried to increase the confidence levels of GGNN and GREAT to the maximum level, i.e., inspecting the most confident reports, as done by [9, 39]. This enabled GGNN and GREAT to find more semantic issues and increased their precision to ~40%. However, with such high confidence
levels, the recall became nearly zero, which is not desired in practice, and the precision was still non-satisfactory.
Compared to GGNN and Great, Namer has a much higher precision of ~70%, despite returning 5x more reports. Another important aspect is that the naming rules mined by Namer and the decision making process of the classifier are highly interpretable, while neural code models are non-interpretable and are vulnerable to adversarial attacks [16]. As a result, developers can inspect and better understand the issues reported by Namer. Therefore, we conclude that Namer is practically more effective than GGNN and Great.
6 Related Work
In this section, we discuss works mostly related to ours.
6.1 Naming issue detection and repair
Existing techniques on naming issue detection can be categorized into two kinds: rule-based and learning-based. Namer can be seen as a combination of the two types of techniques.
**Rule-based approaches.** The works of [30, 34, 38] leverage rule-based anomaly detection for finding naming issues. The detection solely depends on extracted rules [30] or similarity measures [34, 38], while Namer’s decision process considers more factors and features. The work of [41] uses a graph matching algorithm to detect argument selection defects in an industry level codebase. The above approaches only focus on a specific type of naming issue (wrong usages of function arguments) and a specific language (Java). On the contrary, Namer can detect more kinds of naming issues and targets both Java and Python.
**Learning-based approaches.** A number of recent works propose machine learning techniques for name-based bug finding. Apart from GGNN [28] and Great [28] discussed in § 5.6, GINN [47] is another graph neural network for code that leverages a hierarchy of intervals over the control flow graph for better message passing. For detecting variable misuses, GINN achieves higher accuracy than GGNN and Great, but suffers from the same limitation: synthetic issues are used for training. DeepBugs [39] learns embeddings for code snippets to detect three types of naming bugs for Javascript: swapped arguments, wrong binary operator, and wrong binary operand. DeepBugs achieves high precision on the most confident reports (i.e., low number of reports). It is unclear how effective DeepBugs is in a realistic scenario where a higher number of reports is desired.
Instead of detecting bugs, other works learn probabilistic models for predicting or suggesting identifier names. Probabilistic graphical models are employed in [15, 27, 40] for predicting identifier names for minified Javascript program, obfuscated Android applications and stripped binaries, respectively. Naturalize [8] suggests identifier names by learning statistical language models representing coding conventions. Convolutional attention networks are used in [10] for code summarization, i.e., method name suggestion. Other notable works [11, 13] use paths between AST nodes as input features to a neural network trained to summarize code and predict descriptive method names.
6.2 Machine Learning and Program Reasoning
In the following, we discuss research at the intersection of machine learning and program reasoning.
**Static analysis.** Bayesian optimization [36] and reinforcement learning [29, 43] have been used for balancing the tradeoff between precision and performance for numerical program analysis. API specifications are a key ingredient in modern static analysis. Atlas [14] leverages active learning to obtain points-to specifications. Uspec [22] learns API aliasing specifications with unsupervised learning. Seldon [20] infers taint specifications by solving linear optimization. Statistical methods have been used to rank and classify alerts from static analyzers [25, 31].
7 Conclusion
We proposed a novel approach for finding and fixing naming issues. Our method combines interpretable name patterns mined from Big Code to represent different kinds of naming idioms together with a machine learning classifier that filters false positives, trained on expressive features. Importantly, making use of Big Code does not require labeling the programs (which would be practically infeasible), while we only require a small amount of labeled data to train the classifier.
We implemented our approach in a system called Namer which supports both Python and Java, and evaluated it extensively on a massive dataset of open source repositories. Our experimental results showed that Namer is able to find real-world naming issues and suggest correct fixes with high precision (~70%). We also showed that Namer is practically more effective than state-of-the-art deep neural network approaches (that use synthetic data).
We believe this work presents new insights in building a practical bug finding tool with machine learning. It also reassures the importance of program abstraction and analyses in finding defects and other issues in real world code.
|
{"Source-Url": "https://files.sri.inf.ethz.ch/website/papers/pldi21-namer.pdf", "len_cl100k_base": 16030, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 60162, "total-output-tokens": 16719, "length": "2e13", "weborganizer": {"__label__adult": 0.0003812313079833984, "__label__art_design": 0.0004048347473144531, "__label__crime_law": 0.0003058910369873047, "__label__education_jobs": 0.0010004043579101562, "__label__entertainment": 7.045269012451172e-05, "__label__fashion_beauty": 0.00015819072723388672, "__label__finance_business": 0.0001512765884399414, "__label__food_dining": 0.0002970695495605469, "__label__games": 0.0006461143493652344, "__label__hardware": 0.000919342041015625, "__label__health": 0.0003619194030761719, "__label__history": 0.00021076202392578125, "__label__home_hobbies": 0.00011354684829711914, "__label__industrial": 0.00029754638671875, "__label__literature": 0.0002448558807373047, "__label__politics": 0.0002067089080810547, "__label__religion": 0.00044608116149902344, "__label__science_tech": 0.0118560791015625, "__label__social_life": 0.00010287761688232422, "__label__software": 0.005222320556640625, "__label__software_dev": 0.9755859375, "__label__sports_fitness": 0.00028252601623535156, "__label__transportation": 0.0003750324249267578, "__label__travel": 0.0001885890960693359}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 69690, 0.04542]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 69690, 0.35074]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 69690, 0.88789]], "google_gemma-3-12b-it_contains_pii": [[0, 3666, false], [3666, 8995, null], [8995, 12728, null], [12728, 18151, null], [18151, 21196, null], [21196, 25809, null], [25809, 31121, null], [31121, 36798, null], [36798, 42189, null], [42189, 47115, null], [47115, 51963, null], [51963, 57455, null], [57455, 63373, null], [63373, 68939, null], [68939, 68939, null], [68939, 69690, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3666, true], [3666, 8995, null], [8995, 12728, null], [12728, 18151, null], [18151, 21196, null], [21196, 25809, null], [25809, 31121, null], [31121, 36798, null], [36798, 42189, null], [42189, 47115, null], [47115, 51963, null], [51963, 57455, null], [57455, 63373, null], [63373, 68939, null], [68939, 68939, null], [68939, 69690, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 69690, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 69690, null]], "pdf_page_numbers": [[0, 3666, 1], [3666, 8995, 2], [8995, 12728, 3], [12728, 18151, 4], [18151, 21196, 5], [21196, 25809, 6], [25809, 31121, 7], [31121, 36798, 8], [36798, 42189, 9], [42189, 47115, 10], [47115, 51963, 11], [51963, 57455, 12], [57455, 63373, 13], [63373, 68939, 14], [68939, 68939, 15], [68939, 69690, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 69690, 0.23907]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
020e0672d2c7067892b1db8ae6078b5fc04e32e4
|
FINAL REPORT
ENGAGING DESIGN & PLANNING PRACTITIONERS IN A VIDEO GAME DECISION SUPPORT SYSTEM
BY QIUTONG GE & XUESI SHAO
# Table of Contents
1. ACKNOWLEDGMENTS
2. EXECUTIVE SUMMARY
3. OUR TEAM
4. INTRODUCTION
5. BACKGROUND
6. PROJECT PURPOSES
7. METHODS & FINAL DELIVERABLES
8. CHALLENGES AND LIMITATIONS
9. NEXT STEPS
10. REFERENCES
11. APPENDIX
ACKNOWLEDGMENTS
Our practicum team would like to express our special thanks of gratitude to our advisor, Mark Lindquist, Assistant Professor of Landscape Architecture at the University of Michigan School for Environment and Sustainability. He gave us the golden opportunity to do this wonderful project on the Video Game Decision Support System. We would also like to thank Dr. Ramiro Serrano Vergel. His guidance and encouragement throughout this project were integral to our success in this project. We are really thankful to them.
EXECUTIVE SUMMARY
The primary purpose of the project was to evaluate and refine the Land.Info decision support system (DSS). Land.Info is a 3D immersive video game-based DSS that casts users in the role of designer, allowing them to design park infrastructure in virtual city spaces and receive real-time feedback based on their decisions (e.g. cost, amount of rainwater stored, carbon sequestration, etc. Ultimately Land.Info empowers citizens with decision support for the design of open spaces.
This project builds on an existing prototype of the Land.Info DSS that was developed by a previous team. The current prototype requires user testing and further refinement to become an intuitive and fully functioning DSS to aid users. This project was built upon a previous team’s final deliverables. We continued exploring what are the usability issues of the current version of the DSS; the severity of those issues and recommend prioritizing the major issues to bridge the gap between the current gaming experience with an ideal one.
We first evaluated the usability of the current DSS by using the Heuristic Evaluation method. The major issues were Consistency and Standards, Aesthetic and Minimalist Design, and Instruction and Documentation. Informed by the results of the heuristic evaluation, we implemented significant features that were missing from the current version so that the DSS would be more intuitive with improved functionality. The features we added include a smoother player perspective with all the movements. We also implemented 4 tutorials for visualizing important effects: rainstorm; snow, grass, and flower blooming, as well as lighting and shade effects. It is recommended that future work conduct a usability analysis of these new features.
- Heuristic Evaluation process and results: examine the game based on Jakob Nielsen’s ten general principles and identify the usability issues
- New features implantation on the six tutorials for visualizing: based on the evaluation results, implement essential features into the game that bridge the gap between the current and the ideal tutorial experiences
OUR TEAM
We are a two-person team who have a passion for technology.
Team Member 1: Xuesi Shao
Email: source@umich.edu
Education experience:
University of Michigan- Shanghai Jiaotong University Joint Institute (2017.9-2021.8)
Major: Electrical and computer engineering
University of Michigan
Master of SEAS - Sustainable Systems track (Expected Graduation 2022)
Experiences:
- Designed a music and light control system that emits light according to the emotions, rhythm, and beat of a song judged by the software
- Peter the Great St.Petersburg Polytechnic University winter program (2019.1-2019.2)
- Intern Experience media (2018.1-2018.3)
Bio: Xuesi Shao has a background in engineering. His major at Shanghai Jiaotong University was electrical and computer engineering, which gives him a background in programming. Also, his talents in video games will help him in developing a fascinating game.
Team Member 2: Qiutong Ge
Email: qjutongg@umich.edu
Education experience:
University of Michigan
Master of Science in Information GPA: 4.0/4.0
Master of Landscape Architecture GPA: 4.0/4.0 (Expected Graduation 2022)
Work experience:
Website Designer at UMich
- Redesigned the official website of the Landscape Architecture Program in SEAS school at the University of Michigan
- Analyzed related stakeholders and user needs to define the priority for web design
Design Intern at Skidmore, Owings & Merrill
- Led user research and collected feedback to turn the conceptual ideas into high-strategic design solutions
- Worked collaboratively with PMs to define the key features and narrow down the scope of the project
Bio: Qiutong Ge is doing a Landscape Architecture program in SEAS school and doing a joint degree in the information field, which gives her a solid design and technology background. This project fits her skill sets and academic interest well.
INTRODUCTION
Urban scenes that involve many human interactions and environmental facilities, such as parks, open spaces, green spaces, community centers, etc are not only important for urban resilience but also for social justice. The conventional top-down decision-making approaches can prohibit residents’ voices in arranging and managing these landscapes.
Land.info is a gamified software that allows users to get involved in the design of open spaces. It leverages the 3D video-game innovation and a data-driven approach to help with decision-making for designing and planning parks, open spaces, and any other green infrastructures. Land.info currently supports practitioners with planning and designing city, community, and open spaces. This tool allows users to place natural objects (such as terrain, trees) and also man-made objects (such as roads, benches, and green infrastructure) into a city scenario. On the other hand, it utilizes a data-driven approach that calculates the environmental and social impact in real-time, such as rainwater storage and carbon sequestration, etc. The goal of this project is to evaluate and refine the current video game. In order to better guide ourselves, we formed the project into two major steps, Heuristic Evaluation and New Features Implantation.
- **Step 1 Heuristic Evaluation**: examine the current game based on Jakob Nielsen’s ten general principles and identify the usability issues
- **Step 2 New Features Implantation**: based on the evaluation results, implement essential features into the game that bridge the gap between the current and the ideal tutorial experiences
Public participation in urban planning and development is a widely used process that intends to enable better decision-making. Stakeholder participation is increasingly being embedded into environmental decision-making processes (Stringer et al., 2007). By involving stakeholders, many benefits have been recognized, for example, the quality and durability of decisions can be improved (Fischer, 2000, Beierle, 2002, Reed et al., 2008).
User and community co-production are important to society however rarely noticed because citizens are only willing to co-produce in a small range of activities that are genuinely important to them. There are also some concerns about the risks that co-production may trigger compared to professionalized service provision. However, the value of co-production has been increasingly recognized. The process has been seen as a way to build trust with communities, promote a better decision-making process, and increase public support. (Bovaird and Loeffler, 2012).
Many technologies have been created and developed in order to improve decision-making and Decision Support Systems (DSS) is one of them. Decision Support Systems have emerged in professional fields ranging from urban designing and planning, public policymaking, and information science since the 1980s (Klosterman, 1997, Arnott & Pervan, 2012). DSS require three components: 1) an interface that allows immediate graphical representation of analysis, 2) a database that includes information from multiple sources, and 3) analytical models that help analyze given inputs and the data (Klosterman, 1997). Such technology was designed to help with decision-making processes by facilitating the analysis of multiple scenarios simultaneously (Klosterman, 1997). As more urban data sets become available, opportunities for data-driven approaches to better support decision-making emerge. Through a data-driven understanding of the existing condition and potential changes, urban designers, planners, and developers can better collaborate and make wiser decisions (Ferreira, 2015).
It has been shown that 3D imagery and interactive environments can change the public’s perceptions and increase the sense of responsibility (Schroth et al., 2014). 3D visualizations can better convey a conceived image or scenario to the participants.
Developed by a research team led by Prof. Mark Lindquist at the University of Michigan, Land.Info can be backed up by the discussions and ideas above. It was developed to support residents in the design of vacant lots to address flooding in their neighborhoods. The video game leverages the DSS and 3D visualizations technologies and was co-produced with residents (Lindquist & Campbell-Arvai, 2021). Land.Info serves as a tool that helps stakeholders and residents to translate their local knowledge and insights into a design decision with a 3D virtual interface (Lindquist & Campbell-Arvai, 2021). The development of this video game has the intention to help city planners and designers to make better designing and planning decisions.
PROJECT PURPOSES
The primary purpose of the project is to evaluate and refine Land. Info, a 3D immersive video game that casts users in the roles of designers, allowing them to create park infrastructure in virtual city spaces in order to receive real-time feedback based on their decisions, such as the cost of trees, rainwater storage, and carbon sequestration, etc. It enables interactive evaluation and mutual feedback during users’ decision-making process. There is an existing initial hi-fi prototype of the video game, but it requires some polishing work to become an intuitive, user-friendly, and fully functioning modern game for users to play.
The first version of the Land.info video game has been developed by the previous team in 2019. In the early phases of Land.info’s development, a series of workshops were held to determine important features of the software. One of the features that have been developed is the ability to measure environmental improvements that result from urban designs created in the software, such as planting trees, adding facilities or changing terrains, etc in an open space.
However, the current version of the video game does not offer the best user experience to users. There are still significant usability issues to solve and many opportunities to improve to make the video game more intuitive and user-friendly. Therefore, this project would be built upon the previous team’s final deliverables. We will continue improving the user experiences and exploring the potential of using video game methods to support more sustainable and engaging communities.
In order to better guide ourselves throughout the process, our project was framed in two steps: firstly to evaluate the usability of the current game to identify the major usability issues and rank them in severity, and secondly, to add necessary and significant new features to refine the current game based on the evaluation results.
METHODS & FINAL DELIVERABLES:
Step.1 Evaluation of the current game
Method: Heuristics Evaluation
We approached the Heuristics Evaluation of Land.Info by utilizing the popular method proposed by Jakob Nielsen. Although Jakob Nielsen offers 10 heuristics for usability analysis, he acknowledges that additional heuristics may be equally well-suited and while some of the suggested heuristics may be less applicable for certain interfaces. We evaluated the system through all ten of Nielsen’s heuristic principles, however, we also made some minor changes to the criteria under each category to make the ten principles more suitable for our video game.
Ten Heuristics to evaluate:
- Visibility of System Status
- Match Between System and the Real World
- User Control and Freedom
- Consistency and Standards
- Error Prevention
- Recognition Rather Than Recall
- Flexibility and Efficiency of Use
- Aesthetic and Minimalist Design
- Help Users Recognize, Diagnose, and Recover From Errors
- Help and Documentation
To guide our analysis, we created user flows and tasks to complete as if we were users. The current version of the video game is simple and does not have too many interactions, therefore we applied a linear user flow, as the image below shows.
Starting from log-in, users land in the default scene where they need to rotate the view and walk towards the two pieces of open space in the environment. After users arrive at the open space, they need to add items to the space. In order to do that, users first need to select a certain type of item from the top bar and then go through all the options from the card top up on the screen. They secondly pick one certain item and put it in an open space, they can move the item around, delete the item and undo/redo it for one step. We went through all these key interactions through the liner user flow we picked and the image below shows the details of them.
Figure 1: Linear user flow
Full version: https://drive.google.com/file/d/1WnzV41LPtAAlloXBBWOq0Vsh1PINNMT7/view?usp=sharing
Figure 2: Key interactions of the user flow
Full version: https://drive.google.com/file/d/1XrZXB23n1U2itmAllJTrCQoQo5h4Xr/view?usp=sharing
We conducted a heuristics evaluation based on these interactions and screens. In order to ensure we were aligned with the evaluation process and on the same page, we had a kick-off meeting to go through the Heuristic Evaluation Principles. From there, we created a Heuristic Evaluation Checklist for each of the ten heuristics to ensure we were applying the heuristics to evaluate Land.Info and deliver actionable results.
We then scored the problems we identified based on heuristics evaluation. Severity scores were on a scale of 0-5, with 0 being a “No problem” and 5 being a “Catastrophe” to Land.Info. The severity score was based on the frequency the problem occurs, the impact of the problem, and the persistence of the problem. (Nielsen, 1994)
Severity Score:
0 = No problem or usability strength
1 = Cosmetic only, low priority
2 = Minor issue, fix as time allows
3 = Major issue, important to fix
4 = Catastrophe, imperative to fix
Figure 3: Heuristics Evaluation Checklist
Full version can be found: https://docs.google.com/spreadsheets/d/1InevvM2Z2ZcMTzg8-UyWPbH1pRVnZ7y7_/edit?usp=sharing&ouid=101986354738210466400&rtpof=true&sd=true
<table>
<thead>
<tr>
<th>Problem Identified</th>
<th>Heuristic Used</th>
<th>Severity</th>
<th>Recommendations</th>
</tr>
</thead>
<tbody>
<tr>
<td>No instruction & documentation easy to access</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>No instruction & documentation easy to show</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>Instruction & documentation not easy to read</td>
<td>10. Help & documentation</td>
<td>3 = Major issue</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>There is not any type of instruction or tutorial</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe</td>
<td>Add built-in instructions</td>
</tr>
<tr>
<td>No clear UI system and design guideline</td>
<td>4. Consistency</td>
<td>3 = Major issue</td>
<td>Add UI design system</td>
</tr>
<tr>
<td>The numbers under metric icons are centered</td>
<td>4. Consistency</td>
<td>1 = Cosmetic only</td>
<td>-</td>
</tr>
<tr>
<td>There are 13 different icons on the same screen</td>
<td>4. Consistency</td>
<td>2 = Minor issue</td>
<td>Have less icons on a single screen</td>
</tr>
<tr>
<td>No clear UI system and design guideline</td>
<td>4. Consistency</td>
<td>3 = Major issue</td>
<td>Add UI design system</td>
</tr>
<tr>
<td>It uses the Unity default style, works but not</td>
<td>4. Consistency</td>
<td>3 = Major issue</td>
<td>Add UI design system</td>
</tr>
<tr>
<td>There is no color categories</td>
<td>5. Aesthetic & minimalist</td>
<td>2 = Minor issue</td>
<td>Build a proper color coding system</td>
</tr>
<tr>
<td>No color coding throughout the system</td>
<td>5. Aesthetic & minimalist</td>
<td>2 = Minor issue</td>
<td>Build a proper color coding system</td>
</tr>
<tr>
<td>Color contrast is not good enough and cause</td>
<td>5. Aesthetic & minimalist</td>
<td>4 = Catastrophe</td>
<td>Improve the accessibility issues</td>
</tr>
<tr>
<td>Light green to highlight the 4 matrices as distinct</td>
<td>5. Aesthetic & minimalist</td>
<td>4 = Catastrophe</td>
<td>Improve the accessibility issues</td>
</tr>
<tr>
<td>There is not enough color contrast between</td>
<td>5. Aesthetic & minimalist</td>
<td>4 = Catastrophe</td>
<td>Improve the accessibility issues</td>
</tr>
<tr>
<td>Not clear and enough white space between</td>
<td>5. Aesthetic & minimalist</td>
<td>2 = Minor issue</td>
<td>Add more white space</td>
</tr>
<tr>
<td>No “breathing space” around them</td>
<td>5. Recognition over recall</td>
<td>3 = Major issue</td>
<td>Add more white space</td>
</tr>
<tr>
<td>White space is not used to create symmetry</td>
<td>5. Recognition over recall</td>
<td>3 = Major issue</td>
<td>Add more white space</td>
</tr>
<tr>
<td>Items have not been grouped into logical zones</td>
<td>5. Recognition over recall</td>
<td>3 = Major issue</td>
<td>Group and categorize the icons</td>
</tr>
</tbody>
</table>
Figure 4: Severity Score Ranking
Full version can be found: https://docs.google.com/spreadsheets/d/1P9R0AlgeEDBiwkwgvzDULXWIE01_Lk/edit?usp=sharing&ouid=101986354738210466400&rtppf=true&sd=true
Based on the ranking of the severity scores, we categorized the problems we identified into 4 tiers so that we have a better vision of which potential improvements are on a higher priority and should be done soon and which improvements can be future steps.
Figure 5: Issues in tiers
Full version can be found: https://drive.google.com/file/d/1TZmtGfd_bdoRaSolCXvFV4pTLxzYipH0/view?usp=sharing
Result: Findings and Recommendations
1. Instruction for users' comprehension
Finding #1.1
There are not any type of tutorials to educate users on the purposes and key functions of the game. A well-designed tutorial allows us to efficiently introduce new users to even very complex processes. In our case, educating users that certain design decisions can affect which aspects of the environment seems important to introduce ahead of time.
Recommendation #1.1
Add a quick tutorial process for users to review the environmental impact in different scenarios so that they have a better understanding of the goals of this video game and can interact with it better.
Figure 6: Tutorial mock-up
Finding #1.2
There are no built-in instructions to guide users on how to interact with the game. For example, when users land the game and open the default scene, they can see this city view, however, they are not informed that they should go to the open space to place items onto it and start the game.
Recommendation #1.2
Adding tooltips for key interactions throughout the entire gaming process to guide users to the next step so that they can be more aware of the situation.
Figure 7: Tooltips mock-up
Finding #1.3
There is no label on each icon to explain its meaning. This is problematic because users might have trouble recognizing the icons and thus can not select the right icons/button to interact with the game. Although this can be eliminated by the in-person education in a real workshop for data collecting, it still would be more efficient if users can recognize the icons by themselves.
Recommendation #1.3
Add labels on each key interactive icon or have a very quick one-time tutorial at the very beginning to go through all the icons users might interact with.
Figure 8: One-time tutorial mock-up
2. UI aesthetic and consistency
Finding #2.1
Color contrast is not enough for the item icons when they are deactivated because of the lower opacity.
Recommendation #2.1
Rather than having the icons on a low-opacity background, we can keep the background color always solid and assign the deactivate icons a lower opacity. In that case, we can still keep the difference between active and deactivate icons and won’t cause accessibility issues at the same time.
Finding #2.2
There is not a clear category for the icons and buttons on the screen and there are over 13 of them. It is considered overcrowded when there are more than 12 icons on a single screen, especially when they are not properly grouped based on the logic categories.
Recommendation #2.2
Adding tooltips for key interactions throughout the entire gaming process to guide users to the next step so that they can be more aware of the situation.
Figure 11: Improved icons category mockup
Finding #2.3
The UI issues are mainly caused by not having a clear design system to guide the design through the interface. The primary benefit of design systems is their ability to replicate designs quickly by utilizing premade UI components and elements. Teams can continue to use the same elements over and over, reducing the need to reinvent the wheel and thus risking unintended inconsistency.
Figure 12: Current UI
**Recommendation #2.3**
Among all different types of design systems, Component Library seems to be the most appropriate approach in our case. Component libraries contain predetermined, reusable UI elements and serve as a one-stop shop for designers and developers to select and implement specific UI elements.

*Figure 13: Component Library example*
(Source: [https://www.uistore.design/items/eva-design-system-for-sketch/](https://www.uistore.design/items/eva-design-system-for-sketch/))
3. Error prevention
Finding #3.1
We currently do not have any error prevention when users place the items in the wrong place. It’s important to note that there are two types of errors that users make: slips and mistakes. Slips occur when users intend to perform one action, but end up doing another (often similar) action. Mistakes occur when a user has developed a mental model of the interface that isn’t correct and forms a goal that doesn’t suit the situation well (Nielsen Norman Group, 2015). In our case, the error type is considered a Mistake.
Recommendation #3.1
We can give users a Confirm Message before Destructive Actions. When users delete an item or place the items at an inappropriate spot, the system will trigger a pop-up dialog with an error message on it. This can be an effective, simple, and familiar way to give the user a final chance to stop and double-check if they really want to take the action.
Step.2 New features implementation
**Method: Unity Development**
Based on the Heuristic Evaluation results and the instructions from our mentor, Dr. Ramiro Serrano Vergel, we decided to improve and implement 6 visualizing tutorials in the Unity scenes for future incorporation into the game.
The first two, stormwater and snow, are weather contexts that will be incorporated into the game. Different weather conditions can have different outcomes for planting different trees in the scene. The third one is the shade, where users should be able to experience and realize the timescale of the game. The fourth one is flowering, which allows users to visualize the growth and blooming of their plants. The fifth one is similar to flowering, we also wanted to show users how the plant grows fruits. The last one is carbon sequestration, where an animation should be created to visualize the process of carbon being fixed into the ground. We chose to prioritize the first four tutorials due to the time limit.
On top of all the tutorials implementation, we also updated the camera movement function, so that we can make sure users can move around and look around in the newly implemented and old scenes at a comfortable speed and sensitivity.
Result: Implemented 4 Tutorials
1. Stormwater
The stormwater feature is accomplished through the Unity asset WeatherMaker (Jeff Johnson). The testing background is based on the Nature Starter Kit 2’s Demo terrain. In the test scene, raindrops start falling down after a trigger, and the intensity can be adjusted through a sliding bar or automatically through a script. After a period of time, water will start to accumulate on the earth’s surface to form puddles. The water surface will rise if the intensity of rain is high enough. For the rain that is over a certain threshold value, fogging effect will start to appear to make the terrain covered with water vapor.
Figure 14: Game View of the rain scene
Figure 15: Scene view of the rain scene
2. Snow
The snow features are also accomplished through WeatherMaker based on the demo terrain of Natural Starter Kit 2. Similar to rain effects, the snowstorm is also controlled by a sliding bar signaling its intensity. In order to accumulate snow, a snow overlay effect is triggered through a script to cover the terrain with white snow textures. The overlay will change its texture according to the intensity of the snow. Also, snowflakes will tend to be attached to any object (trees, grass) in the terrain. A snowstorm is created when the intensity of the snow is high enough, and similarly, fogging effects will appear just the same as the rainy scene.
Figure 16: Game View of the snow scene
Figure 17: Scene View of the Snow Scene
3. Shade
The Shade feature is also based on the WeatherMaker demo scene. The scene is given a timescale context where a light source rotates above the terrain like a sun. Therefore, shades are created according to the different positions of the “sun”. The timescale can be manually manipulated or just played at a set speed by a script.
The following pictures depict 4 different times of the scene, night, morning, noon, and afternoon. There are also dusk and dawn times when the sun glows pink.
Figure 18: Shade in the morning
Figure 19: Shade at night
Figure 20: Shade at noon
Figure 21: Shade in the afternoon
4. Flowering
The flowering effect can be divided into two minor categories, flower bloom, and grass bloom. The flower bloom effect is realized through Garden Flowers and Herb's assets by Greenworks. The flower is able to bloom according to the light source. Petals can freely open and close according to a sliding bar.
Figure 21: Flower blooming Stages 1-4
The grass bloom effect is achieved by the Plant Growing Asset by Dmitry Raskalov. Similarly, the grass is able to grow out of the farmland scene gradually until mature.
Figure 22: Grass Growing process 1-3
CHALLENGES AND LIMITATIONS
During the heuristic evaluation, there were a number of limitations we encountered throughout the heuristic analysis process. It is important to note that many Land.Info features haven’t been fully implemented yet, and we are only focusing on the key screen and major features that are essential for collecting data from users. However, this didn’t interfere with our ability to conduct the full heuristic analysis. Also, we are a group of two, the limited number of team members and time may make our finding biased to some extent. If there are more designers and developers involved in the process, we will be able to identify more usability issues more accurately and profoundly.
A lot of challenges also occurred during the implementation process. The first one, and probably the most challenging one, is to read through all the previous code in Unity. The massive number of lines of codes had different references to different game objects, which confused us a lot. Another challenge that was worthy to mention is that we do not develop models, so it is quite difficult to find a suitable model from the asset store that fits the project. In fact, in the process of choosing assets, we encountered many assets that seem pretty well from pictures but have uncompileable scripts.
**NEXT STEPS**
We have implemented the 4 prioritized tutorial scenes based on Dr. Ramiro Serrano Vergel’s guide and the heuristic evaluation results. There are two more scenes we can continue working on to implement, the carbon sequestration visualization and the fruiting animation. After the implementation of all the tutorials we need, we can have usability testing on the animations with real users to see if those are intuitive for people who have no environment science or urban design background. Then we can make changes upon the feedback from the target users.
From the evaluation process, we have identified other issues for Tier 1, which have the highest priority other than the ‘Instruction and Documentation’ issue. There are some other categories that require improvements, such as the UI redesign and having a complete design system to better guide the future design and implementations for this game. As the project moves on, our team plans to produce a new design system and finish up the other implementations to give the tutorial a whole new look.
REFERENCES
REFERENCES
UNITY ASSETS
https://assetstore.unity.com/packages/tools/modeling/plants-growing-system-107128
https://assetstore.unity.com/packages/3d/environments/nature-starter-kit-2-52977
# Evaluation Severity Ranking
<table>
<thead>
<tr>
<th># Problem Identified</th>
<th>Heuristic Used</th>
<th>Severity</th>
<th>Recommendations</th>
</tr>
</thead>
<tbody>
<tr>
<td>No Instruction & documentation easy to access</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe (imperative to fix)</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>No Instruction & documentation easy to show</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe (imperative to fix)</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>Instruction & documentation not easy to do</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe (imperative to fix)</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>There is not any type of instruction or tutorials</td>
<td>10. Help & documentation</td>
<td>4 = Catastrophe (imperative to fix)</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>No clear UI system and design guideline</td>
<td>4. Consistency</td>
<td>3 = Major issue (important to fix)</td>
<td>Add UI design system</td>
</tr>
<tr>
<td>The numbers under metric icons are centered</td>
<td>4. Consistency</td>
<td>1 = Cosmetic only (low priority)</td>
<td>Have less icons on a single screen</td>
</tr>
<tr>
<td>There are 13 different icons on the same screen</td>
<td>4. Consistency</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Have less icons on a single screen</td>
</tr>
<tr>
<td>No clear UI system and design guideline</td>
<td>4. Consistency</td>
<td>3 = Major issue (important to fix)</td>
<td>Add UI design system</td>
</tr>
<tr>
<td>It uses the Unity default style, works but not as</td>
<td>4. Consistency</td>
<td>3 = Major issue (important to fix)</td>
<td>Add UI design system</td>
</tr>
<tr>
<td>There is no color categories</td>
<td>8. Aesthetic & minimalistic</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Build a proper color coding system</td>
</tr>
<tr>
<td>No color coding throughout the system</td>
<td>8. Aesthetic & minimalistic</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Build a proper color coding system</td>
</tr>
<tr>
<td>Color contrast is not good enough and cause</td>
<td>8. Aesthetic & minimalistic</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Improve the accessibility issues</td>
</tr>
<tr>
<td>Light green to highlight the 4 metrics as default</td>
<td>8. Aesthetic & minimalistic</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Improve the accessibility issues</td>
</tr>
<tr>
<td>There is not enough color contrast between</td>
<td>8. Aesthetic & minimalistic</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Improve the accessibility issues</td>
</tr>
<tr>
<td>Not clear and enough white space between</td>
<td>8. Aesthetic & minimalistic</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Add white space</td>
</tr>
<tr>
<td>No "breathing space" around them</td>
<td>6. Recognition over recall</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Add more white space</td>
</tr>
<tr>
<td>White space is not used to create symmetry</td>
<td>6. Recognition over recall</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Add more white space</td>
</tr>
<tr>
<td>Items have not been grouped into logical zone</td>
<td>6. Recognition over recall</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Add more white space</td>
</tr>
<tr>
<td>There all full of icons and buttons on the same</td>
<td>6. Recognition over recall</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Group and category the icons</td>
</tr>
<tr>
<td>No visual difference indicates the different level</td>
<td>6. Recognition over recall</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Group and category the icons</td>
</tr>
<tr>
<td>The item option on the top bar is not very self</td>
<td>2. User control & freedom</td>
<td>3 = Major issue (important to fix)</td>
<td>Add tables to icon when necessary</td>
</tr>
<tr>
<td>All the icons are in the same block/grey color</td>
<td>2. User control & freedom</td>
<td>3 = Major issue (important to fix)</td>
<td>Add tables to icon when necessary</td>
</tr>
<tr>
<td>No instruction provided, but there will be some</td>
<td>2. User control & freedom</td>
<td>2 = Minor issue (fix as time allows)</td>
<td>Group and category the icons</td>
</tr>
<tr>
<td>Does not label all the icons and buttons</td>
<td>2. User control & freedom</td>
<td>1 = Cosmetic only (low priority)</td>
<td>Add tables to icon when necessary</td>
</tr>
<tr>
<td>Unity-build environment looks real</td>
<td>2. User control & freedom</td>
<td>1 = Cosmetic only (low priority)</td>
<td>Add tables to icon when necessary</td>
</tr>
<tr>
<td>The Undo button is not clear, just as an arrow</td>
<td>3. Real-world mapping</td>
<td>3 = Major issue (important to fix)</td>
<td>Fix the undo and redo function</td>
</tr>
<tr>
<td>Users can delete an item they placed in the sc</td>
<td>3. Real-world mapping</td>
<td>3 = Major issue (important to fix)</td>
<td>Fix the undo and redo function</td>
</tr>
<tr>
<td>All the buttons are placed on the same screen</td>
<td>3. Real-world mapping</td>
<td>3 = Major issue (important to fix)</td>
<td>Fix the undo and redo function</td>
</tr>
<tr>
<td>Users can only redo for one step of movement</td>
<td>3. Real-world mapping</td>
<td>3 = Major issue (important to fix)</td>
<td>Fix the undo and redo function</td>
</tr>
</tbody>
</table>
APPENDIX
- If the system supports both novice and expert use, novice users will need time to be educated on more functions.
- Screen are crowded
- 1. Flexibility
- 2. Flexibility
- 3. Flexibility
<table>
<thead>
<tr>
<th>Rank</th>
<th>Issue Description</th>
<th>Proposed Solution</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Minor issue (fix is time allowing)</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>2</td>
<td>Minor issue (fix is time allowing)</td>
<td>Add tutorials up front</td>
</tr>
<tr>
<td>3</td>
<td>Major issue (important to fix)</td>
<td>Add more white space</td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://deepblue.lib.umich.edu/bitstream/handle/2027.42/172229/Ge%20and%20Shao%20Practicum.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 8295, "olmocr-version": "0.1.53", "pdf-total-pages": 39, "total-fallback-pages": 0, "total-input-tokens": 58095, "total-output-tokens": 9892, "length": "2e13", "weborganizer": {"__label__adult": 0.0017566680908203125, "__label__art_design": 0.0390625, "__label__crime_law": 0.0019216537475585935, "__label__education_jobs": 0.032623291015625, "__label__entertainment": 0.0019817352294921875, "__label__fashion_beauty": 0.0013666152954101562, "__label__finance_business": 0.00255584716796875, "__label__food_dining": 0.001728057861328125, "__label__games": 0.196044921875, "__label__hardware": 0.00460052490234375, "__label__health": 0.0019121170043945312, "__label__history": 0.00439453125, "__label__home_hobbies": 0.00115203857421875, "__label__industrial": 0.00267791748046875, "__label__literature": 0.0018014907836914065, "__label__politics": 0.001743316650390625, "__label__religion": 0.002117156982421875, "__label__science_tech": 0.253173828125, "__label__social_life": 0.0005860328674316406, "__label__software": 0.0293731689453125, "__label__software_dev": 0.411865234375, "__label__sports_fitness": 0.002010345458984375, "__label__transportation": 0.0023746490478515625, "__label__travel": 0.0012359619140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 37800, 0.03278]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 37800, 0.12712]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 37800, 0.90502]], "google_gemma-3-12b-it_contains_pii": [[0, 123, false], [123, 350, null], [350, 885, null], [885, 3018, null], [3018, 4888, null], [4888, 6524, null], [6524, 8599, null], [8599, 9590, null], [9590, 11532, null], [11532, 12547, null], [12547, 13718, null], [13718, 14869, null], [14869, 18506, null], [18506, 18900, null], [18900, 19593, null], [19593, 20101, null], [20101, 20712, null], [20712, 21174, null], [21174, 21667, null], [21667, 22089, null], [22089, 22674, null], [22674, 23600, null], [23600, 24843, null], [24843, 25554, null], [25554, 25594, null], [25594, 26294, null], [26294, 26334, null], [26334, 26953, null], [26953, 27312, null], [27312, 27519, null], [27519, 28831, null], [28831, 29900, null], [29900, 31798, null], [31798, 32505, null], [32505, 33003, null], [33003, 37296, null], [37296, 37800, null], [37800, 37800, null], [37800, 37800, null]], "google_gemma-3-12b-it_is_public_document": [[0, 123, true], [123, 350, null], [350, 885, null], [885, 3018, null], [3018, 4888, null], [4888, 6524, null], [6524, 8599, null], [8599, 9590, null], [9590, 11532, null], [11532, 12547, null], [12547, 13718, null], [13718, 14869, null], [14869, 18506, null], [18506, 18900, null], [18900, 19593, null], [19593, 20101, null], [20101, 20712, null], [20712, 21174, null], [21174, 21667, null], [21667, 22089, null], [22089, 22674, null], [22674, 23600, null], [23600, 24843, null], [24843, 25554, null], [25554, 25594, null], [25594, 26294, null], [26294, 26334, null], [26334, 26953, null], [26953, 27312, null], [27312, 27519, null], [27519, 28831, null], [28831, 29900, null], [29900, 31798, null], [31798, 32505, null], [32505, 33003, null], [33003, 37296, null], [37296, 37800, null], [37800, 37800, null], [37800, 37800, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 37800, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 37800, null]], "pdf_page_numbers": [[0, 123, 1], [123, 350, 2], [350, 885, 3], [885, 3018, 4], [3018, 4888, 5], [4888, 6524, 6], [6524, 8599, 7], [8599, 9590, 8], [9590, 11532, 9], [11532, 12547, 10], [12547, 13718, 11], [13718, 14869, 12], [14869, 18506, 13], [18506, 18900, 14], [18900, 19593, 15], [19593, 20101, 16], [20101, 20712, 17], [20712, 21174, 18], [21174, 21667, 19], [21667, 22089, 20], [22089, 22674, 21], [22674, 23600, 22], [23600, 24843, 23], [24843, 25554, 24], [25554, 25594, 25], [25594, 26294, 26], [26294, 26334, 27], [26334, 26953, 28], [26953, 27312, 29], [27312, 27519, 30], [27519, 28831, 31], [28831, 29900, 32], [29900, 31798, 33], [31798, 32505, 34], [32505, 33003, 35], [33003, 37296, 36], [37296, 37800, 37], [37800, 37800, 38], [37800, 37800, 39]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 37800, 0.21622]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
98cd75dbd88a686b0724d188b3aa3eb95a2f7865
|
MECHANIZING STRUCTURAL INDUCTION
PART I: FORMAL SYSTEM
Raymond AUBIN
Department of Computer Science, Concordia University, Montréal, Québec, H3G 1M8, Canada*
Communicated by M. Nivat
Received March 1977
Revised March 1978
Abstract. Inductive methods are basic to program proving and this paper presents the formal part of a theorem-proving system for automating mildly complex proofs by structural induction. Its features are motivated by the pragmatics of proof finding. Its syntax includes a typed language and an induction rule using a lexicographic ordering based on a substructure ordering. The domain of interpretation is a many-sorted word algebra generated by the empty set. The carriers of the algebra are ordered and functions are defined by k-recursion over them. Finally, the soundness and the weak completeness of the system are proved. The main quality of the language is its system of types and its correspondingly general induction rule.
1. Introduction
In general, proving properties of programs requires an inductive argument of one sort or other. In this context, the study of methods for mechanizing proofs by induction is of considerable interest. Any theorem-proving system breaks at some point into (1) a formal system and (2) proof finding methods, though both aspects largely influence each other. This paper expounds the formal part of a theorem-prover which automates mildly complex proofs by structural induction. It can be thought of as a generalization of number theory; but its features are primarily motivated by the design of tolerably efficient automatic proof-finding methods described in a second part [2]. A thorough exposition of the whole system can be found in Aubin [1].
Induction on the structure of data is used in this system for proving facts about recursive functions. In general terms, suppose that set $S$ is ordered and every non-empty subset of $S$ has a minimal element; then, to prove the property $P(f(c))$, for all $c$ in $S$, it suffices to show that for all $a$ in $S$, $P(f(b))$, for all $b$ less than $a$ in $S$, implies $P(f(a))$. Structural induction is often understood in practice as using a substructure ordering (see [6, 11]). Theorem-proving programs using such an inductive method were written by Brotz [5] for number theory and by Boyer and Moore [4] for a theory of lists (see also [14]).
* Present address: Recherches Bell-Northern, Ottawa, Ontario, K1Y 4H7, Canada.
The present formal system is an improvement over previous work by
(1) its typed language and
(2) its general induction rule using a lexicographic ordering based on the sub-
structure ordering induced by the type definitions.
Besides, the formalization is pushed to a greater detail.
After an exposition of the syntax and semantics of the system, I prove its soundness
and weak completeness. The general presentation is inspired from Robbin [17] and
Milner, Morris and Newey [13]. A final discussion justifies the choice of some of the
features of this system.
2. Syntax
Logicians are very concrete about the formal syntax of a language. They give a
number of primitive symbols and then define the set of admissible strings of concrete
symbols. I will in general, be more abstract without confusion. On the other hand, I
will make use of abbreviations whereby metalinguistic names are used in place of
syntactic constructs.
2.1. Syntactic constructs
2.1.1. Type constants
We have an infinite list of primitive constructs $t_1, t_2, \ldots$ called type constants.
Type constants will be given names. We use the metavariables $\sigma, \tau$, maybe with
indices, to vary over type constants. An expression like $\sigma^*$ stands for the list
$\sigma_1, \ldots, \sigma_n$ ($0 \leq n$) of type constants. The length of the list is denoted by $\text{length} (\sigma^*)$
but can usually be inferred from the context.
2.1.2. Variables
We have an infinite list of primitive constructs $v_1, v_2, \ldots$ called variable tokens. A
variable of type $\tau$ is defined thus: if $v_i$ is a variable token and $\tau$, a type constant, then
$v_i : \tau$ is a variable of type $\tau$.
Variables will normally be abbreviated by names. We use $x, y, z$ to vary over
variables and $x^*, y^*, z^*$ will denote lists of distinct variables.
2.1.3. Constructor constants
We have an infinite list of primitive constructs $c_1, c_2, \ldots$ called constructor tokens.
If $c_i$ is a constructor token and $\sigma^*, \tau$ are type constants, then $c_i : \sigma^* \rightarrow \tau$ is a constructor
constant of type $\sigma^* \rightarrow \tau$.
The arity of a constructor constant $c_i : \sigma^* \rightarrow \tau$ is equal to $\text{length} (\sigma^*)$. We use names
to abbreviate constructor constants and we use the metavariable $c$ to range over
them.
2.1.4. Defined function constants
This section is analogous to the previous one. We have an infinite list of primitive constructs \( f_1, f_2, \ldots \) called defined function tokens; if \( f_i \) is a defined function token and \( \sigma^*, \tau \) are type constants, then \( f_i : \sigma^* \rightarrow \tau \) is a defined function constant of type \( \sigma^* \rightarrow \tau \).
Constructor and defined function constants form the class of function constants. The metavariables \( f, g, h \) are used to vary over defined function constants and over function constants; the context will make clear which is meant.
2.1.5. Terms
The class of terms of type \( \tau \) is inductively defined thus:
1. If \( x \) is a variable of type \( \tau \), then \( x \) is a term of type \( \tau \).
2. If \( c \) is a constructor constant of type \( \sigma^* \rightarrow \tau \) and \( t^* \) are terms of types \( \sigma^* \) respectively, then \( c(t^*) \) is a term of type \( \tau \).
3. If \( f \) is a defined function constant of type \( \sigma^* \rightarrow \tau \) and \( t^* \) are terms of types \( \sigma^* \) respectively, then \( f(t^*) \) is a term of type \( \tau \).
4. A construct is a term only as required by (1), (2) and (3).
A term which is not a variable will be called a function application (or sometimes more simply, an application). In the following text, I will freely infix function constants; the computer program makes use of a different concrete syntax. As already seen above, the metavariables \( s, t, u \) and \( w \) are used to vary over terms. An expression like \( f(t^*) \) denotes the function application \( f(t_1, \ldots, t_n) \) \( (n = \text{arity}(f)) \). An expression like \( t[s/x] \) denotes the term resulting from replacing all occurrences of \( x \) by \( s \) in \( t \); \( t[s^*/x^*] \) denotes \( t[s_1/x_1] \cdots [s_n/x_n] \).
2.2. Introduction of syntactic constructs
Potentially, we have a countable number of type constants, variables, constructor constants, defined function constants. However, each of the constructs used in the system has to be previously introduced (or defined, or distinguished, or declared, these are all synonymous as far as I am concerned.) This introduction is done in a hierarchical manner and serves also the purpose of giving names to the constructs in question. From now on, I will not distinguish between a syntactic construct and its name. This section is really part of the metalanguage.
A type definition is generated by the following (abstract) BNF grammar:
\[
\langle \text{type definition} \rangle ::= \langle \text{head} \rangle \langle \text{body} \rangle
\]
\[
\langle \text{head} \rangle ::= \langle \text{type constant} \rangle
\]
\[
\langle \text{body} \rangle ::= \{\langle \text{component} \rangle \}
\]
\[
\langle \text{component} \rangle ::= \langle \text{constructor constant} \rangle \{\langle \text{type constant} \rangle \}
\]
where the defined type constant is in the head of the definition.
Such a definition is admissible if and only if its syntactic constructs other than the type and constructor constants being defined have been previously introduced. In the text, I will use the concrete representation, e.g.
\[ \text{true:} \mid \text{false:} \rightarrow \text{bool} \]
\[ \text{zero:} \mid \text{succ:} \text{nat} \rightarrow \text{nat} \]
\[ \text{nil:} \mid \text{cons:} \text{nat, list} \rightarrow \text{list} \]
\[ \text{atom:} \text{nat} \mid \text{consx:} \text{sexpr, sexpr} \rightarrow \text{sexpr} \]
\[ \text{nulltree:} \mid \text{tip:} \text{nat} \mid \text{node:} \text{tree, nat, tree} \rightarrow \text{tree} . \]
A type constant is said to be reflexive if it occurs in the body of its definition. (This term borrowed from Milner, Morris and Newey [13] is preferred to inductive or recursive.) I will come back to why mutually reflexive type constants are not permitted under the present syntax. We consider that type constants are named by the words, e.g., bool, nat, etc., as well as by the whole type definitions.
The type of a constructor constant is immediate from the type definition, e.g. \( \rightarrow \text{bool} \) for true; \( \rightarrow \text{nat} \), \( \rightarrow \text{list} \) for cons; etc. In practice, I will often omit the parentheses in terms like true ( ) when it can be done without confusion. By analogy with type constants, we say that a constructor constant \( c_i: \sigma^* \rightarrow \tau \) is reflective if \( \tau \) occurs in \( \sigma^* \).
An argument of \( c_i: \sigma^* \rightarrow \tau \) occurring in the position of \( \tau \) in \( \sigma^* \) is called a reflexion argument. An immediate predecessor of a list \( c_1(x_1^*), \ldots, c_n(x_n^*) \) is a list
\[ c_1(x_1^*), \ldots, c_{i-1}(x_{i-1}^*), \ x_{i,j}, \ s_{i+1}, \ldots, s_n, \]
such that \( x_{i,j} \) is a reflexion argument of \( c_i(x_i^*) \) and \( s_k (i + 1 \leq k \leq n) \) is any term.
Variables are not recursive and need not be hierarchically introduced. We say that we declared them: for example, \( [a \mid b]: \text{bool}, [m \mid n]: \text{nat}, [j \mid k \mid l]: \text{list} , \text{etc.} \)
Finally, defined function constants are introduced by stages with the help of definitions by cases (see [6, 11]). Here are some concrete examples:
\[
a \Rightarrow b : \text{bool} \leftarrow
\]
\[
\text{cases } a \ [\text{true } \Leftarrow b] \\
\text{false } \Leftarrow \text{true}
\]
\[
a \land b : \text{bool } \Leftarrow
\]
\[
(a \Rightarrow (b \Rightarrow \text{false})) \Rightarrow \text{false}
\]
\[
m = n : \text{bool } \Leftarrow
\]
\[
\text{cases } m[\text{zero } \Leftarrow \text{cases } n[\text{zero } \Leftarrow \text{true}] \\
\text{suc}(n_1) \Leftarrow \text{false}] \\
\text{suc}(m_1) \Leftarrow \text{cases } n[\text{zero } \Leftarrow \text{false}] \\
\text{suc}(n_1) \Leftarrow m_1 = n_1]
\]
They introduce the function constants \(\Rightarrow, \& \) and \(=\) for terms of type \(\text{nat}\). As usual, the arguments of \(\Rightarrow\) are called \(\text{antecedent}\) and \(\text{consequent}\) respectively; the arguments of \(\&\) are called \(\text{conjuncts}\). The computer program makes use of a different concrete syntax.
The abstract syntax of a definition by cases is characterized by the following BNF grammar:
\[
\begin{align*}
\langle \text{definition by cases} \rangle &::= \langle \text{head} \rangle \langle \text{body} \rangle \\
\langle \text{head} \rangle &::= \langle \text{heading} \rangle \langle \text{type constant} \rangle \\
\langle \text{heading} \rangle &::= \langle \text{defined function constant} \rangle \{ \langle \text{variable} \rangle \} \\
\langle \text{body} \rangle &::= \langle \text{empty} \rangle | \langle \text{case expression} \rangle \\
\langle \text{case expression} \rangle &::= \langle \text{term} \rangle | \langle \text{case variable} \rangle \{ \langle \text{case clause} \rangle \} \\
\langle \text{case variable} \rangle &::= \langle \text{variable} \rangle \\
\langle \text{case clause} \rangle &::= \langle \text{pattern} \rangle \langle \text{case expression} \rangle \\
\langle \text{pattern} \rangle &::= \langle \text{constructor constant} \rangle \{ \langle \text{variable} \rangle \}
\end{align*}
\]
When the body is empty, then we say that the function constant is \text{vacuously defined}. The \text{recursion arguments} of a function constant are the arguments in the position of the case variables in the head of its definition.
Admissible definitions are as follows: All type constants, variables, and function constants apart from the one being defined, must have been previously introduced. Patterns must be well-typed and their variables, distinct.
Now consider the body of a definition as a rooted tree whose nonterminal and terminal vertices are labelled with case variables and terms respectively, and whose arcs are labelled with patterns. Let a \text{bundle tied by a case variable} \(x\) be the set of patterns labelling the arcs directed away from the vertex labelled by \(x\). Then the following additional admissibility conditions must be fulfilled:
1. \text{On case variables:} they must occur in the heading and be distinct on any one path to a terminal vertex.
2. \text{On patterns:} the constructor constants of the patterns in the bundle tied by a variable \(x\) must be precisely the constructor constants for the type of \(x\).
3. \text{On terms:} the variables of any terms \(t\) must occur in the heading or in the patterns on the path to \(t\), but not as case variables on this path; furthermore, if the function constant being defined occurs in \(t\), its recursion arguments, properly ordered, must be an immediate predecessor of the patterns labelling the path to \(t\).
2.3. \text{Inference rules}
This section expounds the legitimate inferences which can be made in one atomic step. Each one is given as a list of \text{hypotheses} separated from a \text{conclusion} by a line; hypotheses and conclusions are terms. If we can also infer the conjunction of the
hypotheses from the conclusion, we write a double line. We then say that the rule is \textit{inverible}. \textit{Axioms} are inference rules with an empty list of hypotheses.
2.3.1. \textit{Truth}
\[
\begin{array}{c}
\mbox{true ( )}
\end{array}
\]
2.3.2. \textit{Specialization}
\[
\frac{u}{u[t/x]}
\]
2.3.3. \textit{Definition by k-recursion}
Definition by \textit{k-recursion} is defined by means of a mapping from definitions by cases to sets of inference rules. For each term \(t\) labelling a terminal vertex in the body of a definition by cases, we have the inference rule:
\[
\frac{w[f(s^*)[u^*/z^*]/x]}{w[t[u^*/z^*]/x]}
\]
where \(f(s^*)\) is the heading of the definition by cases, with each case variable occurring in it and labelling a vertex on the path to \(t\) replaced by the pattern labelling the arc directed away from it on this path, and where \(z^*\) is the list of distinct variables in \(f(s^*)\).
In particular, we have:
1. For the function constant \(\Rightarrow\):
\[
\frac{w[true \Rightarrow s/x]}{w[s/x]}
\]
\[
\frac{w[false \Rightarrow s/x]}{w[true/x]}
\]
2. For the function constant \&:
\[
\frac{w[s \& t/x]}{w[(s \Rightarrow (t \Rightarrow false)) \Rightarrow false/x]}
\]
3. For a polymorphic equality function constant of type \(\tau, \tau \rightarrow \text{bool}\), for every pair of constructor constants \(c_1, c_2\) for type \(\tau\):
\[
\frac{w[c_1(t^*) = c_2(s^*)/x]}{w[false/x]}
\]
if \(c_1\) is different from \(c_2\), and
\[
\frac{w[c_1(t^*) = c_2(s^*)/x]}{w[t_1 = s_1 \& \cdots \& t_n = s_n/x]}
\]
if \(c_1\) is identical to \(c_2\).
2.3.4. Modus ponens
\[
\frac{s \quad s \Rightarrow t}{t}
\]
2.3.5. Substitutivity of equality
\[u[x/z] \land y = x \Rightarrow u[y/z]\]
2.3.6. Induction
Let \( p \) be the number of ways the constructor constants for the types of the variables \( z^* \) can occur in this order.
Let \( u_i (1 \leq i \leq p) \) be implications of the form:
\[
u[s_i^1/z^*] \land \cdots \land u[s_i^m/z^*] \Rightarrow u[c_{i,1}(x_i^*), \ldots, c_{i,n}(x_i^*)/z^*]
\]
where \( s_i^j (1 \leq j \leq m_i) \) are precisely the immediate predecessors of \( c_{i,1}(x_i^*), \ldots, c_{i,n}(x_i^*) \). (The variables distinct from \( z^* \) in all occurrences of \( u \) in the antecedent are also implicitly replaced by distinct metavariables over types.)
Then the induction rule can be simply stated as
\[
\frac{u_1 \cdots u_p}{u}
\]
The variables \( z^* \) are called induction variables.
For example, double induction on the variables \( m \) and \( n \) of type nat is:
\[
\begin{align*}
u[\text{zero}/m][\text{zero}/n] & \Rightarrow u[\text{zero}/m][\text{succ}(n_1)/n] \\
u[m_1/m][s_1/n] & \Rightarrow u[\text{succ}(m_1)/m][\text{zero}/n] \\
u[m_1/m][s_2/n] \land u[\text{succ}(m_1)/m][n_1/n] & \Rightarrow u[\text{succ}(m_1)/m][\text{succ}(n_1)/n]
\end{align*}
\]
where \( s_1 \) and \( s_2 \) are any terms.
2.4. Deductions and proofs
A deduction of a term \( t \) from a finite set of terms \( S \) is a finite acyclic directed graph, with a set of terms \( T \), including \( t \) and the elements of \( S \), as set of vertices, with a set of arcs \( A \), and such that:
(1) If the terms \( u_1, \ldots, u_n \) all in \( T \), are the initial vertices of \( n \) arcs in \( A \) directed toward a term \( u \) in \( T \), then \( u \) is an immediate consequence of \( u_1, \ldots, u_n \) by virtue of an inference rule.
(2) The terms in \( S \) have no arcs directed toward them; \( t \) has zero or more arcs directed toward it; other terms in \( T \) have at least one arc directed toward them.
(3) The terms in \( S \) have zero or more arcs directed away from them; the term \( t \) has no arcs directed away from it; and the other terms in \( T \) have at least one arc directed away from them.
The term \( t \) is called the conclusion of the deduction; the terms in \( S \), the hypotheses. The degenerate deduction of \( t \) is the deduction of \( t \) from the singleton of \( t \). A deduction which is a subgraph of another deduction \( D \) is called a subdeduction of \( D \).
A proof of a term \( t \) is a deduction of \( t \) from the empty set of hypotheses; the conclusion of a proof is called a theorem. In effect, the conclusion of a deduction need not be a theorem nor need the hypotheses. For example,
\[
\begin{align*}
\text{false} & \equiv \text{true} \\
\text{false} \Rightarrow \text{false} & \equiv \text{true} \\
\text{true} & \equiv \text{true} \\
(a \Rightarrow \text{false}) & \equiv \text{true}
\end{align*}
\]
is the deduction of \( (a \Rightarrow \text{false}) = \text{true} \) form from the singleton of false.
3. Semantics
Our formal syntactic constructs are intended to denote some objects. I will first study the domain of interpretation of the constructs, and then describe this interpretation precisely. The technical background can be found in [16, 9].
3.1. Induction
We actually want our domain of interpretation to have more structure than being just a collection of sets and we impose an algebraic structure on it. More specifically, our domain is a many-sorted word algebra generated by the empty set. Such an algebra \( M = [(S); (c)] \) consists of a family \( (S) \) of \( k \) sets \( (1 \leq k) \) called carriers and a collection of \( n \)-ary \( (0 \leq n) \) functions from \( n \) sets in \( (S) \) to a set in \( (S) \) called constructors. A constructor which maps into a carrier \( S \) is said to be a constructor of \( S \).
The elements of \( M \) are precisely those obtained by applying the constructors in \( (c) \); they are given the name of structures. A constructor \( c \) from \( S^* \) to \( S \) such that \( S \) is not a member of \( S^* \) is called a constant constructor with respect to \( S \).
Finally, such algebras have the property of being totally free from any special identity relation, that is, no nontrivial relations of the form \( s_1 = s_2 \) hold in it, where \( s_1 \) and \( s_2 \) are distinct elements of the algebra. This is the unique factorization property. It
Mechanizing structural induction: formal system
says in our case that two structures of $M$ are identical if and only if they have been constructed by the same constructor from identical structures.
For $s$ and $t$ in any carrier $S$, we say that $s$ is an immediate substructure of $t$ in $S$ if and only if $t$ is the result of applying a constructor to $s$ and possibly some other structures. The reflexive and transitive closure of $S$ with the immediate substructure relation is the ordered set $[S; \leq]$, where $\leq$ denotes the substructure relation. More specifically, for every $s$ and $t$ in $S$, $s \leq t$ if and only if $s = t$ or $s \leq t'$, where $t'$ is an immediate substructure of $t$. As usual, I will write $s < t$ (read: 's is a proper structure of t') in place of $s \leq t$ and $s \neq t$.
A structure $s$ is minimal in $[S; \leq]$ if it has no proper substructures in $S$. The minimal elements of $[S; \leq]$ are precisely the structures constructed by applying the constant constructors with respect to $S$.
**Fact 1.** Every nonempty subset of $[S; \leq]$ has a minimal element (the minimum condition).
**Proof.** This holds since any element $s$ of $S$ has a finite number of substructures by construction.
Note however, that not all carriers $[S; \leq]$ are partly well-ordered since we have e.g., for tree structures infinitely many minimal elements: nulltree, tip(zero), tip(succ(zero)), . . . .
Now we define the strict lexicographic ordering $<_L$ on $S^*$, where $S^*$ is the product of not necessarily distinct carriers of $M$, the usual way; for all $s^*$ and $t^*$ in $S^*$, $s^* <_L t^*$ if and only if $s_i = t_i$ and $\cdots$ and $s_{i-1} = t_{i-1}$ and $s_i < t_i$, for some $i$ ($1 \leq i \leq n$). The ordered set $[S^*; \leq_L]$ is the reflexive closure of $[S^*; <_L]$, i.e., $s^* \leq_L t^*$ if and only if $s^* <_L t^*$ or $s^* = t^*$.
**Fact 2.** The ordered set $[S^*; \leq_L]$ satisfies the minimum condition.
**Proof.** This holds since $[S; \leq]$ satisfies the minimum condition for each $S$ in $S^*$.
We can now assert that the principle of structural induction holds for the ordered set $[S^*; \leq_L]$, that is:
If, for all $t^*$ in $S^*$, $P(s^*)$ implies $P(t^*)$, for all $s^*$ in $S^*$ such that $s^* <_L t^*$, then $P(t^*)$, for all $t^*$ in $S^*$.
We say that $s^*$ is an immediate predecessor of $t^*$ in $[S^*; \leq_L]$ if $s^* <_L t^*$ and there is no other element $r^*$ in $S^*$ for which $s^* \leq_L r^* \leq_L t^*$. The principle of structural induction can be reformulated in an equivalent, though apparently stronger, way by replacing '$s^* <_L t^*$' by '$s^*$ is an immediate predecessor of $t^*$'.
3.2. k-recursive functions
This section studies a class of functions over the carriers of the algebra H.
A function \( f \) from \( S^* \times T^* \) to \( S \), such that \( S^* \), \( T^* \) and \( S \) are carriers of \( M \), is said to be defined by k-recursion if and only if for all lists of \( k \) constructors \( c^* \) of \( S^* \) respectively, \( f(c_1(x_1^*), \ldots, c_k(x_k^*), y^*) \) is explicitly defined using only:
1. The variables \( x_1^*, \ldots, x_k^*, y^* \),
2. the functions \( \lambda y^* \cdot f(z^*, y^*), \) where \( z^* \) is an immediate predecessor of \( c_1(x_1^*), \ldots, c_k(x_k^* \) in \( [S^*; \leq_L] \),
3. previously defined functions.
Note that an explicit definition is finite. In a sense, this definition scheme says too much and too little. It says too much because, insofar as Peter’s results for number theory [15] are applicable to this system, definitions by k-recursion are reducible to a normal form which does not look like the above definition scheme. But this reduction is a bit artificial and in this system, I wish to deal with definitions by k-recursion as people would naturally write them. But then, the above scheme says too little since it does not cater for course-of-values and mutual recursion. The reasons behind it are essentially pragmatic and I will come back to them.
We inductively define the class of k-recursive functions thus:
1. constructors are k-recursive functions,
2. if \( f \) is a function defined by k-recursion from k-recursive functions, then \( f \) is a k-recursive function,
3. a function is k-recursive only as required by (1) and (2).
**Fact 3.** There exists a unique function \( f \) from \( S^* \times T^* \) to \( S \) which satisfies a given definition by k-recursion.
**Proof.** The proof by induction on the class of k-recursive functions and on \([S^*; \leq_L]\) divides into two parts. We consider all lists \( c^* \) of constructors of \( S^* \) respectively.
*Existence.* For all \( x^* \) in appropriate carriers, all \( y^* \) in \( T^* \), by induction hypothesis, we have that
1. there exists a \( z \) in \( S \) such that \( f(z^*, y^*) = z \) for all \( z^* \) immediately preceding \( c_1(x_1^*), \ldots, c_k(x_k^*) \) in \( [S^*; \leq_L] \) and for all \( y^* \) in \( T^* \) and
2. for any previously defined function \( g \), there exists a \( z \) in an appropriate carrier such that \( g(y^*) = z \) for all \( y^* \) in appropriate carriers.
But \( f(c_1(x_1^*), \ldots, c_k(x_k^*), y^*) \) is explicitly defined in terms of these functions only and of constructors. Hence, there exists a \( z \) in \( S \) such that for all \( x^* \) in appropriate carriers, for all \( y^* \) in \( T^* \), \( f(c_1(x_1^*), \ldots, c_k(x_k^*), y^*) \).
*Uniqueness.* Suppose some function \( f' \) also satisfies the definition by k-recursion of \( f \) for all \( x^* \) in appropriate carriers and for all \( y^* \) in \( T^* \), then by induction hypothesis, we have that \( f'(z^*, y^*) = f(z^*, y^*) \) for all \( z^* \) immediately preceding
Mechanizing structural induction: formal system
339
c1(x^*_1), \ldots, c_k(x^*_k) in [S^*; \leq_L] and for all y^* in T^*. Hence,
f'(c_1(x^*_1), \ldots, c_k(x^*_k), y^*) = f(c_1(x^*_1), \ldots, c_k(x^*_k), y^*)
for all x^* in appropriate carriers and for all y^* in T^*.
In conclusion, there exists a unique z in S such that f(x^*) = z for all x^* in S^* \times T^*; so, there exists a unique function which satisfies a given definition by k-recursion.
3.3. Interpretation
Now that we have a reasonably clear picture of what our domain of interpretation looks like, we can give the intended meaning of our syntactic constructs. Since this section, and the following ones, will mention both syntactic constructs and objects in our domain, the latter will be underlined. Identity between elements of the domain will be written as $=$.
An interpretation is a triple $(C, M, V)$ of semantic functions, respectively called classification, model, and valuation. These functions map syntactic constructs into semantic objects.
We define the semantic function $C$ (classification) for type constants thus: $C$ assigns a carrier $S$ to each type constant $\sigma$.
In particular, we have that $C(\text{bool})$ is $\text{BOOL}$, the set of truthvalues.
The semantic functions $M$ (model) and $V$ (valuation) for other syntactic constructs in the language are mutually defined:
1. $M$ assigns a constructor $c$ from $S^*$ to $S$ to each constructor constant $c$ of type $\sigma^* \rightarrow \tau$ where $C(\sigma_i)$ is $S_i$ and $C(\tau)$ is $S$.
2. To each function constant $f$ of type $\sigma^* \rightarrow \tau$ defined by cases, $M$ assigns a function $f$ from $S^*$ to $S$ defined by k-recursion, where $C(\sigma_i)$ is $S_i$ and $C(\tau)$ is $S$.
If $f$ is vacuously defined, then $f$ is any $k$-recursive function from $S^*$ to $S$. Otherwise the definition of $f$ by $k$-recursion is formed of the following of clauses: for all terms $t$ labelling terminal vertices in the definition body of $f$,
$$V(f(x^*)[z^*/s^*]) = V(t) \text{ with } M(f) = f$$
where $f(x^*)$ is the heading of the definition head of $f; z^*$ is the list of case variables labelling the vertices on the path to $t; and s^*$ are the patterns tied to these variables on this path.
3. $V$ assigns an element of $S$ to each variable of type $\sigma$ such that $C(\sigma)$ is $S$.
4. $V(f(t^*)) = M(f)(V(t_1), \ldots, V(t_n))$.
5. $M$ is a model and $V$, a valuation only as required by (1), (2), (3) and (4).
In particular, we have that $M(\text{true})$ is $\text{true}$ and $M(\text{false})$ is $\text{false};$ the meanings of the function constants $\Rightarrow, \&$, and $=$ are the functions respectively defined by:
$$\begin{align*}
\text{true}(\ ) & \Rightarrow b = b \\
\text{false}(\ ) & \Rightarrow b = \text{true}(\ )
\end{align*}$$
\[ a \land b = (a \Rightarrow (b \Rightarrow \text{false}(\text{)))) \Rightarrow \text{false}(\text{)} \]
\[ c_1(x^*) = c_2(v^*) = \text{false}(\text{)}, \quad \text{if } c_1 \text{ is different from } c_2. \]
\[ c_1(x^*) = c_2(y^*) = x_1 = y_1 \land \ldots \land x_n = y_n, \quad \text{otherwise.} \]
With the help of the semantic functions \( C, M, \) and \( V, \) we can obtain a value (i.e. a structure) for any term in our language. For the moment, we will focus our interest on boolean terms. Let \( B = [(\text{BOOL}, S); (\text{true}, \text{false}, c)] \) be a many-sorted algebra. We say that a term \( t \) of type \( \text{bool} \) is valid in \( B \) if and only if \( V(t) = \text{true}(\text{)} \) for all values of its variables and vacuously defined function constants.
Before closing this section, there remains a point to be clarified. We have seen, for example, that the meaning of \( \Rightarrow \) of type \( \text{bool} \times \text{bool} \) is the function \( \Rightarrow \) from \( \text{BOOL} \times \text{BOOL} \) to \( \text{BOOL} \). However, one can legitimately ask whether the function \( \Rightarrow \) carries the same information as implication. The question arises because we have a logic of terms only. We first need some definitions. For all functions \( f \) from \( S^* \) to \( \text{BOOL} \) with \( S_i \) different from \( \text{BOOL} \) for some \( S_i \) of \( S^* \), we define the relation \( P[f] \) such that \( P[f](x^*) \) if and only if \( f(x^*) = \text{true}(\text{)} \); such functions \( f \) are called \textit{predicates}. Similarly, for all functions \( f \) from \( \text{BOOL}^* \) to \( \text{BOOL} \), we define the composition of sentential connectives ('implies', 'and', etc.) \( Q[f] \) such that \( Q[f](P[g_1](x_1^*), \ldots, P[g_n](x_n^*)) \) if and only if \( f(g_1(x_1^*), \ldots, g_n(x_n^*)) = \text{true}(\text{)} \); such functions \( f \) are called \textit{connectives}.
\textbf{Fact 4.} \textit{The interpretation respects truth.}
\textbf{Proof.} We have that \( P[\text{true}] \) is the true relation since \( \text{true}(\text{)} = \text{true}(\text{)}. \)
\textbf{Fact 5.} \textit{The interpretation respects falsity.}
\textbf{Proof.} We have that \( P[\text{false}] \) is the false relation since \( \text{false}(\text{)} \neq \text{true}(\text{)}. \)
\textbf{Fact 6.} \textit{The interpretation respects implication.}
\textbf{Proof.} We want to show that \( Q[\Rightarrow] \) is the sentential connective 'implies'. This is immediate from the fact that truth and falsity are respected by the interpretation. For example, \( (\text{true}(\text{)} \Rightarrow \text{false}(\text{))) = \text{false}(\text{)} \) if and only if the true relation does not imply the false relation.
\textbf{Fact 7.} \textit{The interpretation respects conjunction.}
\textbf{Proof.} This is immediate from the previous results.
\textbf{Fact 8.} \textit{The interpretation respects equality.}
Proof. This is the most interesting case. We want to show that \((x = y) = \text{true}(())\) if and only if \(x = y\) for all \(x\) and \(y\) in a carrier \(S\); in other words, \(P[=]\) is the identity relation. The proof is by induction on the family \((S)\) of carriers as hierarchically introduced by the type definitions, and on the ordered sets \([S; \leq_1]\). Suppose \(c^*\) are precisely the constructors of \(S\) and consider all pairs of constructors \(c_1\) and \(c_2\). We have that
\[
(c_1(x^*) = c_2(y^*)) = \text{true}() \iff (x_1 = y_2 \land \cdots \land x_n = y_n) = \text{true}().
\]
But by induction hypothesis, equality is respected for previously introduced carriers and for elements of \(S\) preceding \(c_1(x^*)\) and \(c_2(y^*)\). So, we have \(x_1 = y_1\) and \(\cdots\) and \(x_n = y_n\), since conjunction is respected. We finally get \(c_1(x^*) = c_2(y^*)\) because of the unique factorization property of identity. In conclusion, our interpretation respects equality.
4. Soundness
The least property which a formal system must have if we want to give any substance to our claim of proving theorems is soundness, that is, we want to make sure that the terms provable in the system are indeed valid.
Fact 9. If a boolean term \(t\) is a theorem, then \(t\) is valid.
Proof. The demonstration is by induction on the structure of proofs. We must show that for each rule of inference, if the hypotheses are valid, then the conclusion is also valid.
Truth. We have that \(V(\text{true}()) = M(\text{true})(()) = \text{true}().\)
Specialization. Since \(u\) is valid, it is \(\text{true}()\) for all values assigned to its vacuously defined function constants and variables. In particular, it is \(\text{true}()\) for \(V(t)\) assigned to \(x\) for all values of the vacuously defined function constants and of the variables in \(t\). Hence, \(u[t/x]\) is valid.
Definition by \(k\)-recursion. By the definition of \(M\) and \(V\), the inference rules constituting the definition by \(k\)-recursion of a defined function constant \(f\) and the clauses of the definition by \(k\)-recursion of \(M(f)\) correspond precisely. So, for any constituent of the definition of \(f\),
\[
\frac{w[f(s^*)/x]}{w[t/x]}
\]
if and only if \(V(f(s^*)) = V(t)\). But, the latter identity holds since we have shown that functions defined by \(k\)-recursion are well-defined. Finally, since the identity relation is substitutive, we have that \(w[f(s^*)/x]\) is valid if and only if \(w[t/x]\) is valid.
Modus ponens. Assume that $s$ and $s \Rightarrow t$ are valid. Then we have that $V(s) = \text{true}(\cdot)$, and $V(s) = \text{true}(\cdot)$ implies $V(t) = \text{true}(\cdot)$, since the interpretation respects implication. So, we can deduce that $V(t) = \text{true}(\cdot)$ and hence, that $t$ is valid.
Substitutivity of equality. Since implication, conjunction, and equality are respected by the interpretation, this axiom is valid if and only if $V(u[x/z]) = \text{true}(\cdot)$ whenever $V(u[y/z]) = \text{true}(\cdot)$ and $y = x$. But, this is precisely equivalent to the substitution principle for the identity relation which holds in our domain.
Induction. Two facts should clear from the start:
(1) a list of terms of types $\tau^*$ is an immediate predecessor of another list of terms (in the sense of Section 2.2) if and only if the list of values of the first terms immediately precedes the list of values of the second terms in $[C(\tau_1), \ldots, C(\tau_n); \preceq_{\text{L}}]$ (in the sense of Section 3.1);
(2) $c_1^*, \ldots, c_m^*$ are precisely the lists of constructor constants for the types $\tau^*$ if and only if the values of the terms $c_{1,1}(x_1^*), \ldots, c_{1,n_1}(x_{1,n_1}), \ldots, c_{m,1}(x_{m,1}), \ldots, c_{m,n_m}(x_{m,n_m})$, for all values of the variables, are precisely the elements of $[C(\tau_1), \ldots, C(\tau_n); \preceq_{\text{L}}]$.
Now assume that each $u_i$ ($1 \leq i \leq p$) in the induction rule is valid. Then, for each of them, we have that:
$$V(u[s_i^*/z^*]) = \text{true}(\cdot) \quad \text{and} \quad V(u[s_i^*/z^*]) = \text{true}(\cdot)$$
implies
$$V(u[c_1(x_1^*), \ldots, c_n(x_n^*)/z^*]) = \text{true}(\cdot),$$
under the provisos on $c_i$ and $s_i^*$ given in Section 2.3. But because of the two facts above, and by means of the principle of structural induction, we can deduce that $V(u) = \text{true}(\cdot)$ and hence, that $u$ is valid.
This completes the proof.
5. Weak completeness
The incompleteness result of number theory extends to this formal system despite its limited form of quantification (i.e. an implicit outermost universal quantifier for all variables.) It is, however, weakly complete in the sense that every valid term without variables and vacuously defined function constants is a theorem.
Fact 10. If terms $t$ and $s$ do not contain any variables and vacuously defined function constants, then $s = t$ whenever $V(s) = V(t)$.
Proof. The proof is by induction on the class of terms. If $t$ or $s$ are variables, then the theorem holds vacuously. Let $t$ be $f_1(t^*)$ and $s$ be $f_2(s^*)$; by induction hypothesis, we have that $t_i = s_i$ whenever $V(t_i) = V(s_i)$. If both $f_1$ and $f_2$ are constructor constants, then by the unique factorization property of equality, we can deduce that $f_1(t^*) = f_2(s^*)$ whenever $V(f_1(t^*)) = V(f_2(s^*))$. If at least one of $f_1$ or $f_2$ is a (nonvacuously)
defined function constant, then by the uniqueness of functions defined by \( k \)-recursion, we also have that \( f_1(t^*) = f_2(s^*) \) whenever \( V(f_1(t^*)) = V(f_2(s^*)) \). This completes the proof.
As a matter of fact, the converse also holds. This justifies what will be called \textit{evaluation}, that is, the repeated application of the \( k \)-recursive definition rule to a term \( t \) without variables and vacuously defined function constants, until it cannot be applied any more. When \( t \) contains variables or vacuously defined function constants, we talk of \textit{symbolic evaluation}.
The weak completeness theorem is a corollary of the above proposition.
\textbf{Fact 11.} Every valid term without variables and vacuously defined function constants is a theorem.
\textbf{Proof.} In other words, we want to show that if \( V(t) = \text{true}() \), then \( t \) is a theorem. Assume \( V(t) = \text{true}() \); then by Fact 10, \( t = \text{true}() \). But this is equivalent to \( t \Rightarrow \text{true}() \) and \( \text{true}() \Rightarrow t \); hence, by modus ponens, \( \text{true}() \) and \( t \) are inter-deducible. In conclusion, \( t \) is a theorem.
6. Discussion
One objective of this formal system was to start from a small base in order to achieve a great degree of uniformity as regards, e.g., induction. However, as it stands, the result is not amenable to automatic proof-finding. The level of the system has to be raised by introducing more connectives (or, not, cond) and by deriving some inference rules. The latter include various forms of substitutivity for equality and a weakening rule, i.e., from \( t \), infer \( s \Rightarrow t \). Other rules are actually theorems; they are equalities used to put a term in normal form, i.e., a conjunction of implications whose antecedents and consequents are conjunctions and disjunctions respectively. These normalization rules have been inspired from Ketonen's dialect \cite{12} of Gentzen's sequent calculus \cite{10}. Proofs can then be carried out more easily.
The main feature of this system, that is, its typed language, is of great pragmatic importance. By considering abstract structures independently of their concrete representations, it is easier to prevent and detect meaningless constructions (by static type checking) and possible to obtain simpler expressions and proofs. The lack of separation between abstract data types and their representations was a serious source of difficulty for Boyer and Moore \cite{4} when going from lists to more complex types.
The natural counterpart to type definitions is the definition of functions by cases. Case expressions are less prone to error than the conditional expressions exploited
by Boyer and Moore [4]. More importantly, because they are used by matching, they allow recursion arguments to be of a type containing infinitely many minimal elements (e.g. type tree in Section 2.2); conditionals do not so easily.
Besides the positive features, one must have noticed some of the restrictions of this system. All of them aim at simplifying the search for proofs. As a result, the power of expression of the language may suffer, but hopefully, the effects will not be so important for the class of problems considered. The expression of mutually reflexive types has been barred because no rules or strategies have been studied for them. Course-of-values and mutual k-recursion are excluded for similar reasons; nevertheless k-recursion from several bases is included though not explicitly in the scheme of Section 3.2. Dealing with general recursive functions would require an even more radical change to the strategy since the analogy between recursion and structural induction would be lost; partialness would also be introduced.
Finally, this language has no quantifiers. This cuts down an important source of complexity, but in this case, it also brings some limitations (while it does not in resolution, for example). In effect, one can think of the boolean terms as first-order formulas with outermost universal quantifiers only, except for the non-induction variables in the induction hypotheses which are existentially quantified. Thus the specialization of variables is restricted; this reduces the search space considerably, and does not appear to be too limiting to serve our purposes.
Two recent works have also had the goal of improving over Boyer and Moore [4]. Cartwright’s system [7,8] includes axiomatically defined structures constrained to belong to the same sets as denoted by our type constants. However, axiomatic definitions allow membership to a set to be discussed within the formal language and consequently, yield a more powerful induction rule. Moreover, Cartwright deals with general recursive functions by the addition of an undefined value. Boyer and Moore [3] also improved on their earlier work. Their new system is even more powerful than Cartwright’s since structures can be defined axiomatically without any constraints. On the other hand, the system can be extended with any total function.
This increased power of Cartwright’s, and Boyer and Moore’s systems has a price: since well-typedness is not a syntactic feature, it has to be dynamically proved as opposed to statically checked as in my system. Moreover, in the case of Boyer and Moore, one has to show that a set admits induction before using this rule on it and also that a function is total before introducing it in the system. In my system, admissibility to induction and totality are syntactic features and consequently, can be statically checked.
7. Conclusions
The formal system presented in this paper sets up the basis of a theorem-proving system whose search strategy is described in a subsequent paper (see [2]). Thus the
claim of proving theorems can be substantiated formally. The pragmatics of proof-finding was the prime motivation for many aspects of the system, in particular, its typed language. Some extensions are worth studying (richer domain than word algebra, general recursive functions), but not independently of the problem of finding proofs in such an improved system.
Acknowledgment
This work was carried out at the School of Computer Science and Artificial Intelligence, University of Edinburgh. I am especially grateful to my directors of studies, Robin Milner and Rod Burstall. I was supported by the Commonwealth Scholarship Commission and the Conseil national de recherches du Canada.
References
|
{"Source-Url": "https://core.ac.uk/download/pdf/82764304.pdf", "len_cl100k_base": 12296, "olmocr-version": "0.1.53", "pdf-total-pages": 17, "total-fallback-pages": 0, "total-input-tokens": 38902, "total-output-tokens": 14387, "length": "2e13", "weborganizer": {"__label__adult": 0.0004611015319824219, "__label__art_design": 0.00064849853515625, "__label__crime_law": 0.0005311965942382812, "__label__education_jobs": 0.0029773712158203125, "__label__entertainment": 0.00018358230590820312, "__label__fashion_beauty": 0.00025272369384765625, "__label__finance_business": 0.0003974437713623047, "__label__food_dining": 0.0007748603820800781, "__label__games": 0.001140594482421875, "__label__hardware": 0.0013971328735351562, "__label__health": 0.00106048583984375, "__label__history": 0.0004963874816894531, "__label__home_hobbies": 0.00023567676544189453, "__label__industrial": 0.0008821487426757812, "__label__literature": 0.0015048980712890625, "__label__politics": 0.00044918060302734375, "__label__religion": 0.0009403228759765624, "__label__science_tech": 0.232177734375, "__label__social_life": 0.0001819133758544922, "__label__software": 0.00833892822265625, "__label__software_dev": 0.74365234375, "__label__sports_fitness": 0.0003800392150878906, "__label__transportation": 0.0009512901306152344, "__label__travel": 0.00022685527801513672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45677, 0.02122]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45677, 0.6542]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45677, 0.85074]], "google_gemma-3-12b-it_contains_pii": [[0, 2444, false], [2444, 4785, null], [4785, 7798, null], [7798, 10671, null], [10671, 13843, null], [13843, 15439, null], [15439, 17014, null], [17014, 19916, null], [19916, 22602, null], [22602, 25665, null], [25665, 28498, null], [28498, 31461, null], [31461, 33980, null], [33980, 36893, null], [36893, 39639, null], [39639, 42689, null], [42689, 45677, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2444, true], [2444, 4785, null], [4785, 7798, null], [7798, 10671, null], [10671, 13843, null], [13843, 15439, null], [15439, 17014, null], [17014, 19916, null], [19916, 22602, null], [22602, 25665, null], [25665, 28498, null], [28498, 31461, null], [31461, 33980, null], [33980, 36893, null], [36893, 39639, null], [39639, 42689, null], [42689, 45677, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45677, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45677, null]], "pdf_page_numbers": [[0, 2444, 1], [2444, 4785, 2], [4785, 7798, 3], [7798, 10671, 4], [10671, 13843, 5], [13843, 15439, 6], [15439, 17014, 7], [17014, 19916, 8], [19916, 22602, 9], [22602, 25665, 10], [25665, 28498, 11], [28498, 31461, 12], [31461, 33980, 13], [33980, 36893, 14], [36893, 39639, 15], [39639, 42689, 16], [42689, 45677, 17]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45677, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-05
|
2024-12-05
|
a148da4585f2554ef96c10b0431fcef52235dd37
|
[REMOVED]
|
{"Source-Url": "http://lib.dr.iastate.edu/cgi/viewcontent.cgi?article=1177&context=cs_techreports", "len_cl100k_base": 11723, "olmocr-version": "0.1.53", "pdf-total-pages": 27, "total-fallback-pages": 0, "total-input-tokens": 64561, "total-output-tokens": 15904, "length": "2e13", "weborganizer": {"__label__adult": 0.0003402233123779297, "__label__art_design": 0.0002627372741699219, "__label__crime_law": 0.000255584716796875, "__label__education_jobs": 0.0008788108825683594, "__label__entertainment": 4.4405460357666016e-05, "__label__fashion_beauty": 0.00014984607696533203, "__label__finance_business": 0.0001329183578491211, "__label__food_dining": 0.00028324127197265625, "__label__games": 0.0004856586456298828, "__label__hardware": 0.0005202293395996094, "__label__health": 0.0003223419189453125, "__label__history": 0.0001652240753173828, "__label__home_hobbies": 6.854534149169922e-05, "__label__industrial": 0.00023603439331054688, "__label__literature": 0.00024187564849853516, "__label__politics": 0.00020897388458251953, "__label__religion": 0.0004317760467529297, "__label__science_tech": 0.003307342529296875, "__label__social_life": 7.164478302001953e-05, "__label__software": 0.0032749176025390625, "__label__software_dev": 0.9873046875, "__label__sports_fitness": 0.0002815723419189453, "__label__transportation": 0.0004055500030517578, "__label__travel": 0.00017726421356201172}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 63705, 0.02456]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 63705, 0.64875]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 63705, 0.8589]], "google_gemma-3-12b-it_contains_pii": [[0, 827, false], [827, 2039, null], [2039, 4428, null], [4428, 7740, null], [7740, 10760, null], [10760, 13909, null], [13909, 15959, null], [15959, 19069, null], [19069, 20674, null], [20674, 22986, null], [22986, 24668, null], [24668, 28038, null], [28038, 30827, null], [30827, 33508, null], [33508, 35674, null], [35674, 37637, null], [37637, 40021, null], [40021, 41798, null], [41798, 43670, null], [43670, 44107, null], [44107, 45840, null], [45840, 49298, null], [49298, 52404, null], [52404, 55345, null], [55345, 58336, null], [58336, 61623, null], [61623, 63705, null]], "google_gemma-3-12b-it_is_public_document": [[0, 827, true], [827, 2039, null], [2039, 4428, null], [4428, 7740, null], [7740, 10760, null], [10760, 13909, null], [13909, 15959, null], [15959, 19069, null], [19069, 20674, null], [20674, 22986, null], [22986, 24668, null], [24668, 28038, null], [28038, 30827, null], [30827, 33508, null], [33508, 35674, null], [35674, 37637, null], [37637, 40021, null], [40021, 41798, null], [41798, 43670, null], [43670, 44107, null], [44107, 45840, null], [45840, 49298, null], [49298, 52404, null], [52404, 55345, null], [55345, 58336, null], [58336, 61623, null], [61623, 63705, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 63705, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 63705, null]], "pdf_page_numbers": [[0, 827, 1], [827, 2039, 2], [2039, 4428, 3], [4428, 7740, 4], [7740, 10760, 5], [10760, 13909, 6], [13909, 15959, 7], [15959, 19069, 8], [19069, 20674, 9], [20674, 22986, 10], [22986, 24668, 11], [24668, 28038, 12], [28038, 30827, 13], [30827, 33508, 14], [33508, 35674, 15], [35674, 37637, 16], [37637, 40021, 17], [40021, 41798, 18], [41798, 43670, 19], [43670, 44107, 20], [44107, 45840, 21], [45840, 49298, 22], [49298, 52404, 23], [52404, 55345, 24], [55345, 58336, 25], [58336, 61623, 26], [61623, 63705, 27]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 63705, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
d5e05e173c344caaac587d3d3eaf9ee502e53fc6
|
Methodology for VNF Benchmarking Automation
draft-rosa-bmwg-vnfbench-04
Abstract
This document describes a common methodology for the automated benchmarking of Virtualized Network Functions (VNFs) executed on general-purpose hardware. Specific cases of automated benchmarking methodologies for particular VNFs can be derived from this document. Two open source reference implementations are reported as running code embodiments of the proposed, automated benchmarking methodology.
Status of This Memo
This Internet-Draft is submitted in full conformance with the provisions of BCP 78 and BCP 79.
Internet-Drafts are working documents of the Internet Engineering Task Force (IETF). Note that other groups may also distribute working documents as Internet-Drafts. The list of current Internet-Drafts is at https://datatracker.ietf.org/drafts/current/.
Internet-Drafts are draft documents valid for a maximum of six months and may be updated, replaced, or obsoleted by other documents at any time. It is inappropriate to use Internet-Drafts as reference material or to cite them other than as "work in progress."
This Internet-Draft will expire on December 26, 2019.
Copyright Notice
Copyright (c) 2019 IETF Trust and the persons identified as the document authors. All rights reserved.
This document is subject to BCP 78 and the IETF Trust’s Legal Provisions Relating to IETF Documents (https://trustee.ietf.org/license-info) in effect on the date of publication of this document. Please review these documents carefully, as they describe your rights and restrictions with respect
to this document. Code Components extracted from this document must include Simplified BSD License text as described in Section 4.e of the Trust Legal Provisions and are provided without warranty as described in the Simplified BSD License.
Table of Contents
1. Introduction ............................................. 3
2. Terminology ............................................. 4
3. Scope .................................................. 4
4. Considerations ......................................... 4
4.1. VNF Testing Methods ................................. 5
4.2. Benchmarking Procedures ............................. 5
4.2.1. Phase I: Deployment ............................... 6
4.2.2. Phase II: Configuration ............................ 6
4.2.3. Phase III: Execution .............................. 6
4.2.4. Phase IV: Report .................................. 7
5. Generic VNF Benchmarking Architectural Framework ..... 7
5.1. Deployment Scenarios ................................. 10
6. Methodology ............................................. 10
6.1. VNF Benchmarking Descriptor (VNF-BD) ............... 12
6.1.1. Descriptor Headers ................................ 12
6.1.2. Target Information ................................. 12
6.1.3. Experiments ....................................... 12
6.1.4. Environment ....................................... 12
6.1.5. Scenario .......................................... 13
6.1.6. Proceedings ...................................... 14
6.2. VNF Performance Profile (VNF-PP) .................... 14
6.2.1. Execution Environment .............................. 14
6.2.2. Measurement Results ............................... 15
6.3. Procedures ........................................... 16
6.3.1. Pre-Execution ..................................... 16
6.3.2. Automated Execution ............................... 17
6.3.3. Post-Execution .................................... 18
6.4. Particular Cases ..................................... 18
6.4.1. Capacity .......................................... 18
6.4.2. Isolation ......................................... 19
6.4.3. Failure Handling .................................. 19
6.4.4. Elasticity and Flexibility ......................... 19
6.4.5. Handling Configurations ........................... 19
6.4.6. White Box VNF .................................... 19
7. Open Source Reference Implementations ................. 20
7.1. Gym ................................................ 20
7.2. tng-bench .......................................... 21
8. Security Considerations ................................ 22
9. IANA Considerations ................................... 22
10. Acknowledgement ....................................... 22
11. References ........................................... 22
11.1. Normative References ........................................... 22
11.2. Informative References ......................................... 23
Authors’ Addresses ....................................................... 24
1. Introduction
The Benchmarking Methodology Working Group (BMWG) already presented considerations for benchmarking of VNFs and their infrastructure in [RFC8172]. Similar to the motivation given in [RFC8172], the following aspects justify the need for VNF benchmarking: (i) pre-deployment infrastructure dimensioning to realize associated VNF performance profiles; (ii) comparison factor with physical network functions; (iii) and output results for analytical VNF development.
Even if many methodologies already described by the BMWG, e.g., self-contained black-box benchmarking, can be applied to VNF benchmarking scenarios, further considerations have to be made. This is, on the one hand, because VNFs, which are software components, do not have strict and clear execution boundaries and depend on underlying virtualization environment parameters as well as management and orchestration decisions [ETS14a]. On the other hand, can and should the flexible, software-based nature of VNFs be exploited to fully automate the entire benchmarking procedure end-to-end. This is an inherent need to align VNF benchmarking with the agile methods enabled by the concept of Network Functions Virtualization (NFV) [ETS14e]. More specifically it allows: (i) the development of agile performance-focused DevOps methodologies for Continuous Integration and Delivery (CI/CD) of VNFs; (ii) the creation of on-demand VNF test descriptors for upcoming execution environments; (iii) the path for precise-analytics of automated catalogues of VNF performance profiles; (iv) and run-time mechanisms to assist VNF lifecycle orchestration/management workflows, e.g., automated resource dimensioning based on benchmarking insights.
This document describes basic methodologies and guidelines to fully automate VNF benchmarking procedures, without limiting the automated process to a specific benchmark or infrastructure. After presenting initial considerations, the document first describes a generic architectural framework to setup automated benchmarking experiments. Second, the automation methodology is discussed, with a particular focus on experiment and procedure description approaches to support reproducibility of the automated benchmarks, a key challenge in VNF benchmarking. Finally, two independent, open-source reference implementations are presented. The document addresses state-of-the-art work on VNF benchmarking from scientific publications and current developments in other standardization bodies (e.g., [ETS14c] and [RFC8204]) wherever possible.
2. Terminology
Common benchmarking terminology contained in this document is derived from [RFC1242]. The reader is assumed to be familiar with the terminology as defined in the European Telecommunications Standards Institute (ETSI) NFV document [ETS14b]. Some of these terms, and others commonly used in this document, are defined below.
NFV: Network Function Virtualization - the principle of separating network functions from the hardware they run on by using virtual hardware abstraction.
VNF: Virtualized Network Function - a software-based network function. A VNF can be either represented by a single entity or be composed by a set of smaller, interconnected software components, called VNF components (VNFCs) [ETS14d]. Those VNFs are also called composed VNFs.
VNFC: Virtualized Network Function Component - a software component that implements (parts of) the VNF functionality. A VNF can consist of a single VNFC or multiple, interconnected VNFCs [ETS14d]
VNFD: Virtualised Network Function Descriptor - configuration template that describes a VNF in terms of its deployment and operational behaviour, and is used in the process of VNF on-boarding and managing the life cycle of a VNF instance.
NS: Network Service - a collection of interconnected VNFs forming an end-to-end service. The interconnection is often done using chaining of functions.
3. Scope
This document assumes VNFs as black boxes when defining their benchmarking methodologies. White box approaches are assumed and analysed as a particular case under the proper considerations of internal VNF instrumentation, later discussed in this document.
This document outlines a methodology for VNF benchmarking, specifically addressing its automation.
4. Considerations
VNF benchmarking considerations are defined in [RFC8172]. Additionally, VNF pre-deployment testing considerations are well explored in [ETS14c].
4.1. VNF Testing Methods
Following ETSI’s model in [ETS14c], we distinguish three methods for VNF evaluation:
Benchmarking: Where parameters (e.g., CPU, memory, storage) are provided and the corresponding performance metrics (e.g., latency, throughput) are obtained. Note, such evaluations might create multiple reports, for example, with minimal latency or maximum throughput results.
Verification: Both parameters and performance metrics are provided and a stimulus verifies if the given association is correct or not.
Dimensioning: Performance metrics are provided and the corresponding parameters obtained. Note, multiple deployments may be required, or if possible, underlying allocated resources need to be dynamically altered.
Note: Verification and Dimensioning can be reduced to Benchmarking. Therefore, we focus on Benchmarking in the rest of the document.
4.2. Benchmarking Procedures
A (automated) benchmarking procedure can be divided into three sub-procedures:
Trial: Is a single process or iteration to obtain VNF performance metrics from benchmarking measurements. A Test should always run multiple Trials to get statistical confidence about the obtained measurements.
Test: Defines unique structural and functional parameters (e.g., configurations, resource assignment) for benchmarked components to perform one or multiple Trials. Each Test must be executed following a particular benchmarking scenario composed by a Method. Proper measures must be taken to ensure statistical validity (e.g., independence across Trials of generated load patterns).
Method: Consists of one or more Tests to benchmark a VNF. A Method can explicitly list ranges of parameter values for the configuration of a benchmarking scenario and its components. Each value of such a range is to be realized in a Test. I.e., Methods can define parameter studies.
In general, automated VNF benchmarking Tests must capture relevant causes of performance variability. To dissect a VNF benchmarking
Test, in the sections that follow different benchmarking phases are categorized defining generic operations that may be automated. When automating a VNF benchmarking methodology, all the influencing aspects on the performance of a VNF must be carefully analyzed and comprehensively reported, in each phase of the overall benchmarking process.
4.2.1. Phase I: Deployment
The placement (i.e., assignment and allocation of resources) and the interconnection, physical and/or virtual, of network function(s) and benchmarking components can be realized by orchestration platforms (e.g., OpenStack, Kubernetes, Open Source MANO). In automated manners, the realization of a benchmarking testbed/scenario through those means usually rely on network service templates (e.g., TOSCA, Heat, YANG). Such descriptors have to capture all relevant details of the execution environment to allow the benchmarking framework to correctly instantiate the SUT as well as helper functions required for a Test.
4.2.2. Phase II: Configuration
The configuration of benchmarking components and VNFs (e.g., populate routing table, load PCAP source files in source of traffic stimulus) to execute the Test settings can be realized by programming interfaces in an automated way. In the scope of NFV, there might exist management interfaces to control a VNF during a benchmarking Test. Likewise, infrastructure or orchestration components can establish the proper configuration of an execution environment to realize all the capabilities enabling the description of the benchmarking Test. Each configuration registry, its deployment timestamp and target, must all be contained in the VNF benchmarking report.
4.2.3. Phase III: Execution
In the execution of a benchmarking Test, the VNF configuration can be programmed to be changed by itself or by a VNF management platform. It means that during a Trial execution, particular behaviors of a VNF can be automatically triggered, e.g., auto-scaling of its internal components. Those must be captured in the detailed procedures of the VNF execution and its performance report. I.e., the execution of a Trial can determine arrangements of internal states inside a VNF, which can interfere in observed benchmarking metrics. For instance, in a particular benchmarking case where the monitoring measurements of the VNF and/or execution environment are available for extraction, Tests should be run to verify if the monitoring of the VNF and/or execution environment can impact the VNF performance metrics.
4.2.4. Phase IV: Report
The report of a VNF benchmarking Method might contain generic metrics (e.g., CPU and memory consumption) and VNF-specific traffic processing metrics (e.g., transactions or throughput), which can be stored and processed in generic or specific ways (e.g., by statistics or machine learning algorithms). If automated procedures are applied over the generation of a benchmarking report, those must be detailed in the report itself, jointly with their input raw measurements and output processed data. I.e., any algorithm used in the generation of processed metrics must be disclosed in the report.
5. Generic VNF Benchmarking Architectural Framework
A generic VNF benchmarking architectural framework, shown in Figure 1, establishes the disposal of essential components and control interfaces, explained below, that enable the automation of VNF benchmarking methodologies.
Figure 1: Generic VNF Benchmarking Setup
Virtualized Network Function (VNF) -- consists of one or more software components, so called VNF components (VNFC), adequate for performing a network function according to allocated virtual resources and satisfied requirements in an execution environment. A VNF can demand particular configurations for benchmarking specifications, demonstrating variable performance based on available virtual resources/parameters and configured enhancements targeting specific technologies (e.g., NUMA, SR-IOV, CPU-Pinning).
Execution Environment -- defines a virtualized and controlled composition of capabilities necessary for the execution of a VNF. An execution environment stands as a general purpose level of virtualization with abstracted resources available for one or more VNFs. It can also define specific technology habilitation, incurring in viable settings for enhancing the performance of VNFs.
Agent -- executes active stimulus using probers, i.e., benchmarking tools, to benchmark and collect network and system performance metrics. A single Agent can perform localized benchmarks in execution environments (e.g., stress tests on CPU, memory, disk I/O) or can generate stimulus traffic and the other end be the VNF itself where, for example, one-way latency is evaluated. The interaction among distributed Agents enable the generation and collection of end-to-end metrics (e.g., frame loss rate, latency) measured from stimulus traffic flowing through a VNF. An Agent can be defined by a physical or virtual network function.
Prober -- defines an abstraction layer for a software or hardware tool able to generate stimulus traffic to a VNF or perform stress tests on execution environments. Probers might be specific or generic to an execution environment or a VNF. For an Agent, a Prober must provide programmable interfaces for its life cycle management, e.g., configuration of operational parameters, execution of stimulus, parsing of extracted metrics, and debugging options. Specific Probers might be developed to abstract and to realize the description of particular VNF benchmarking methodologies.
Monitor -- when possible is instantiated inside the System Under Test, VNF and/or infrastructure (e.g., as a plug-in process in a virtualized execution environment), to perform the passive monitoring, using Listeners, for the extraction of metrics while Agents' stimuli takes place. Monitors observe particular properties according to the execution environment and VNFs capabilities, i.e., exposed passive monitoring interfaces. Multiple Listeners can be executed at once in synchrony with a Prober’ stimulus on a SUT. A Monitor can be defined as a virtualized network function.
Listener -- defines one or more software interfaces for the extraction of metrics monitored in a target VNF and/or execution environment. A Listener must provide programmable interfaces for its life cycle management workflows, e.g., configuration of operational parameters, execution of passive monitoring captures, parsing of extracted metrics, and debugging options. Varied methods of passive performance monitoring might be implemented as a Listener, depending on the interfaces exposed by the VNF and/or execution environment.
Manager -- performs (i) the discovery of available Agents/Monitors and their respective features (i.e., available Probers/Listeners and execution environment capabilities), (ii) the coordination and synchronization of activities of Agents and Monitors to perform a benchmarking Test, (iii) the collection, processing and aggregation of all VNF benchmarking measurements that correlates the VNF stimuli and the, possible, SUT monitored metrics. A Manager executes the main configuration, operation, and management actions to deliver the VNF benchmarking report. A Manager can be defined as a physical or virtualized network function.
5.1. Deployment Scenarios
A deployment scenario realizes the actual instantiation of physical and/or virtual components of a Generic VNF Benchmarking Architectural Framework needed to habilitate the execution of an automated VNF benchmarking methodology. The following considerations hold for a deployment scenario:
- Not all components are mandatory for a Test, possible to be disposed in varied settings.
- Components can be composed in a single entity and be defined as black or white boxes. For instance, Manager and Agents could jointly define one hardware/software entity to perform a VNF benchmarking Test and present measurement results.
- Monitor can be defined by multiple instances of software components, each addressing a VNF or execution environment.
- Agents can be disposed in varied topology setups, included the possibility of multiple input and output ports of a VNF being directly connected each in one Agent.
- All benchmarking components defined in a deployment scenario must perform the synchronization of clocks.
6. Methodology
Portability is an intrinsic characteristic of VNFs and allows them to be deployed in multiple environments. This enables various benchmarking setups in varied deployment scenarios. A VNF benchmarking methodology must be described in a clear and objective manner following four basic principles:
- Comparability: Output of Tests shall be simple to understand and process, in a human-readable format, coherent, and easily reusable (e.g., inputs for analytic applications).
· Repeatability: A Test setup shall be comprehensively defined through a flexible design model that can be interpreted and executed by the testing platform repeatedly but supporting customization.
· Configurability: Open interfaces and extensible messaging models shall be available between benchmarking components for flexible composition of Test descriptors and platform configurations.
· Interoperability: Tests shall be ported to different environments using lightweight components.
```
+--------+ | |
| | | Automated |
| VNF-BD |--(defines)--->| Benchmarking |
| | | Methodology |
+--------+ |______________|
```
Figure 2: VNF benchmarking process inputs and outputs
As shown in Figure 2, the outcome of an automated VNF benchmarking methodology, must be captured in a VNF Benchmarking Report (VNF-BR), consisting of two parts:
VNF Benchmarking Descriptor (VNF-BD) -- contains all required definitions and requirements to deploy, configure, execute, and reproduce VNF benchmarking tests. VNF-BDs are defined by the developer of a benchmarking methodology and serve as input to the benchmarking process, before being included in the generated VNF-BR.
VNF Performance Profile (VNF-PP) -- contains all measured metrics resulting from the execution of a benchmarking. Additionally, it might also contain additional recordings of configuration parameters used during the execution of the benchmarking scenario to facilitate comparability of VNF-BRs.
A VNF-BR correlates structural and functional parameters of VNF-BD with extracted VNF benchmarking metrics of the obtained VNF-PP. The content of each part of a VNF-BR is described in the following sections.
6.1. VNF Benchmarking Descriptor (VNF-BD)
VNF Benchmarking Descriptor (VNF-BD) -- an artifact that specifies a Method of how to measure a VNF Performance Profile. The specification includes structural and functional instructions and variable parameters at different abstraction levels (e.g., topology of the deployment scenario, benchmarking target metrics, parameters of benchmarking components). A VNF-BD may be specific to a VNF or applicable to several VNF types. It can be used to elaborate a VNF benchmark deployment scenario aiming at the extraction of particular VNF performance metrics.
The following items define the VNF-BD contents.
6.1.1. Descriptor Headers
The definition of parameters concerning the descriptor file, e.g., its version, identifier, name, author and description.
6.1.2. Target Information
General information addressing the target VNF(s) the VNF-BD is applicable, with references to any specific characteristics, i.e., the VNF type, model, version/release, author, vendor, architectural components, among any other particular features.
6.1.3. Experiments
The specification of the number of executions for Trials, Tests and Method. The execution of a VNF-BD corresponds to the execution of the specified Method.
6.1.4. Environment
The details referring to the name, description, and information associated with the interfaces needed for the orchestration, if necessary, of the specified VNF-BD scenario. I.e., it refers to a
specific interface that receives the VNF-BD scenario information and converts it to the template needed for an orchestration platform. In this case, the means to the Manager component interface such orchestration platform must be provided, as well as its outcome orchestration status information (e.g., management interfaces of deployed components).
6.1.5. Scenario
This section contains all information needed to describe the deployment of all involved functional components mandatory for the execution of the benchmarking Tests addressed by the VNF-BD.
6.1.5.1. Nodes
Information about each component in a benchmarking setup (see Section 5). It contains the identification, name, image, role (i.e., agent, monitor, sut), connection-points and resource requirements (i.e., allocation of cpu, memory, disk).
The lifecycle specification of a node lists all the workflows that must be realized on it during a Test. For instance, main workflows include: create, start, stop, delete. Particular workflows can be specified containing the required parameters and implementation. Those details must reflect the actions taken on or by a node that might affect the VNF performance profile.
6.1.5.2. Links
Links contain information about the data plane links interconnecting the components of a benchmarking setup. Links refer to two or more connection-points of a node. A link might refer to be part of a network. Depending on the link type, the network might be implemented as a layer 2 mesh, or as directional-oriented traffic forwarding flow entries. Links also detain resource requirements, specifying the minimum bandwidth, latency, and frame loss rate for the execution of benchmarking Tests.
6.1.5.3. Policies
Involves the definition of execution environment policies to run the Tests. Policies might specify the (anti-)affinity placement rules for each component in the topology, min/max allocation of resources, and specific enabling technologies (e.g., DPDK, SR-IOV, PCIe) needed for each component.
6.1.6. Proceedings
This information is utilized by the Manager component to execute the benchmarking Tests. It consists of agent(s) and monitor(s) settings, detailing their prober(s)/listener(s) specification and running parameters.
Agents: Defines a list containing the Agent(s) needed for the VNF-BD tests. The information of each Agent contains its host environment, making reference to a node specified in the VNF-BD scenario (Section 6.1.5). In addition, each Agent also is defined with the the configured toolset of the Prober(s) and their running parameters fulfilled (e.g., stimulus workload, traffic format/trace, configurations to enable hardware capabilities, if existent). In each Prober, it is also detailed the output metrics to be extracted from it when running the benchmarking Tests.
Monitors: Defines a list containing the Monitor(s) needed for the VNF-BD tests. The information of each Monitor contains its host environment, making reference to a node specified in the VNF-BD scenario (Section 6.1.5) and detailing the placement settings of it (e.g., internal or external with the target VNF and/or execution environment). In addition, each Monitor also is defined with the the configured toolset of the Listener(s) and their running parameters fulfilled (e.g., tap interfaces, period of monitoring, interval among the measurements). In each Listener, it is also detailed the output metrics to be extracted from it when running the benchmarking Tests.
6.2. VNF Performance Profile (VNF-PP)
VNF Performance Profile (VNF-PP) -- defines a mapping between resources allocated to a VNF (e.g., CPU, memory) as well as assigned configurations (e.g., routing table used by the VNF) and the VNF performance metrics (e.g., throughput, latency, CPU, memory) obtained in a benchmarking Test conducted using a VNF-BD. Logically, packet processing metrics are presented in a specific format addressing statistical significance (e.g., median, standard deviation, percentiles) where a correspondence among VNF parameters and the delivery of a measured VNF performance exists.
The following items define the VNF-PP contents.
6.2.1. Execution Environment
Execution environment information has to be included in every VNF-PP and is required to describe the environment on which a benchmark Test was actually executed.
Ideally, any person who has a VNF-BD and its complementing VNF-PP with its execution environment information available, must be able to reproduce the same deployment scenario and VNF benchmarking Tests to obtain identical VNF-PP measurement results.
If not already defined by the VNF-BD deployment scenario requirements (Section 6.1.5), for each component in the deployment scenario of the VNF benchmarking setup, the following topics must be detailed:
**Hardware Specs:** Contains any information associated with the underlying hardware capabilities offered and used by the component during the benchmarking Tests. Examples of such specification include allocated CPU architecture, connected NIC specs, allocated memory DIMM, etc. In addition, any information concerning details of resource isolation must also be described in this part of the VNF-PP.
**Software Specs:** Contains any information associated with the software apparatus offered and used during the benchmarking Tests. Examples include versions of operating systems, kernels, hypervisors, container image versions, etc.
Optionally, a VNF-PP execution environment might contain references to an orchestration description document (e.g., HEAT template) to clarify technological aspects of the execution environment and any specific parameters that it might contain for the VNF-PP.
### 6.2.2. Measurement Results
Measurement results concern the extracted metrics, output of benchmarking procedures, classified into:
**VNF Processing/Active Metrics:** Concerns metrics explicitly defined by or extracted from direct interactions of Agents with a VNF. Those can be defined as generic metric related to network packet processing (e.g., throughput, latency) or metrics specific to a particular VNF (e.g., HTTP confirmed transactions, DNS replies).
**VNF Monitored/Passive Metrics:** Concerns the Monitors’ metrics captured from a VNF execution, classified according to the virtualization level (e.g., baremetal, VM, container) and technology domain (e.g., related to CPU, memory, disk) from where they were obtained.
Depending on the configuration of the benchmarking setup and the planned use cases for the resulting VNF-PPs, measurement results can be stored as raw data, e.g., time series data about CPU utilization of the VNF during a throughput benchmark. In the case of VNFs
composed of multiple VNFCs, those resulting data should be represented as vectors, capturing the behavior of each VNFC, if available from the used monitoring systems. Alternatively, more compact representation formats can be used, e.g., statistical information about a series of latency measurements, including averages and standard deviations. The exact output format to be used is defined in the complementing VNF-BD (Section 6.1).
The representation format of a VNF-PP must be easily translated to address the combined set of classified items in the 3x3 Matrix Coverage defined in [RFC8172].
6.3. Procedures
The methodology for VNF Benchmarking Automation encompasses the process defined in Figure 2, i.e., the procedures that translate a VNF-BD into a VNF-PP composing a VNF-BR by the means of the components specified in Figure 1. This section details the sequence of events that realize such process.
6.3.1. Pre-Execution
Before the execution of benchmarking Tests, some procedures must be performed:
1. A VNF-BD must be defined to be later instantiated into a deployment scenario and have executed its Tests. Such a description must contain all the structural and functional settings defined in Section 6.1. At the end of this step, the complete Method of benchmarking the target VNF is defined.
2. The VNF target image must be prepared to be benchmarked, having all its capabilities fully described. In addition all the probers and listeners defined in the VNF-BD must be implemented to realize the benchmark Tests. At the end of this step, the complete set of components of the benchmarking VNF-BD deployment scenario is defined.
3. The environment needed for a VNF-BD must be defined to realize its deployment scenario, in an automated or manual method. This step might count on the instantiation of orchestration platforms and the composition of specific topology descriptors needed by those platforms to realize the VNF-BD deployment scenario. At the end of this step, the whole environment needed to instantiate the components of a VNF-BD deployment scenario is defined.
6.3.2. Automated Execution
Satisfied all the pre-execution procedures, the automated execution of the Tests specified by the VNF-BD follow:
1. Upon the parsing of a VNF-BD, the Manager must detect the VNF-BD variable input field (e.g., list of resources values) and compose the all the permutations of parameters. For each permutation, the Manager must elaborate a VNF-BD instance. Each VNF-BD instance defines a Test, and it will have its deployment scenario instantiated accordingly. I.e., the Manager must interface an orchestration platform to realize the automated instantiation of each deployment scenario defined by a VNF-BD instance (i.e., a Test). The Manager must iterate through all the VNF-BD instances to finish the whole set of Tests defined by all the permutations of the VNF-BD input fields.
2. Given a VNF-BD instance, the Manager, using the VNF-BD environment settings, must interface an orchestrator platform requesting the deployment of a scenario to realize a Test. To perform such step, The Manager might interface a management function responsible to properly parse the deployment scenario specifications into the orchestration platform interface format.
3. An orchestration platform must deploy the scenario requested by the Manager, assuring the requirements and policies specified on it. In addition, the orchestration platform must acknowledge the deployed scenario to the Manager specifying the management interfaces of the VNF and the other components in the running instances for the benchmarking Test.
4. Agent(s) and Monitor(s) (if existing) and the target VNF must be configured by the Manager according to the components settings defined in the VNF-BD instance. After this step, the whole VNF-BD Test will be ready to be executed.
5. Manager must interface Agent(s) and Monitor(s) (if existing) via management interfaces to require the execution of the benchmarking probers (and listeners, if existing), and retrieve expected metrics captured during or at the end of each Trial. I.e., for a single Test, according to the VNF-BD execution settings, the Manager must guarantee that one or more Trials realize the required measurements to characterize the performance behavior of a VNF.
6. Output measurements from each obtained benchmarking Test, and its possible Trials, must be collected by the Manager, until all the Tests are finished. In the execution settings of the parsed
VNF-BD, the Manager must check the Method repetition, and perform the whole set of VNF-BD Tests (i.e., since step 1), until all methods specified are finished.
7. Collected all measurements from the VNF-BD (Trials, Tests and Methods) execution, the intended metrics, as described in the VNF-BD, must be parsed, extracted and combined to create the corresponding VNF-PP. The combination of used VNF-BD and generated VNF-PP compose the resulting VNF benchmark report (VNF-BR).
6.3.3. Post-Execution
After the process of a VNF-BD execution, some automated procedures, not necessarily mandatory, can be performed to improve the quality and utility of a VNF-BR:
1. Archive the raw output contained in the VNF-PP, perform statistical analysis on it, or train machine learning models with the collected data.
2. Evaluate the analysis output to the detection of any possible cause-effect factors and/or intrinsic correlations in the VNF-BR (e.g., outliers).
3. Review the input VNF-BD and modify it to realize the proper extraction of the target VNF metrics based on the performed research. Iterate in the previous steps until composing a stable and representative VNF-BR.
6.4. Particular Cases
As described in [RFC8172], VNF benchmarking might require to change and adapt existing benchmarking methodologies. More specifically, the following cases need to be considered.
6.4.1. Capacity
VNFs are usually deployed inside containers or VMs to build an abstraction layer between physical resources and the resources available to the VNF. According to [RFC8172], it may be more representative to design experiments in a way that the VMs hosting the VNFs are operating at maximum of 50% utilization and split the workload among several VMs, to mitigate side effects of overloaded VMs. Those cases are supported by the presented automation methodologies through VNF-BDs that enable direct control over the resource assignments and topology layouts used for a benchmarking experiment.
6.4.2. Isolation
One of the main challenges of NFV is to create isolation between VNFs. Benchmarking the quality of this isolation behavior can be achieved by Agents that take the role of a noisy neighbor, generating a particular workload in synchrony with a benchmarking procedure over a VNF. Adjustments of the Agent’s noisy workload, frequency, virtualization level, among others, must be detailed in the VNF- BD.
6.4.3. Failure Handling
Hardware and software components will fail or have errors and thus trigger healing actions of the benchmarked VNFs (self-healing). Benchmarking procedures must also capture the dynamics of this VNF behavior, e.g., if a container or VM restarts because the VNF software crashed. This results in offline periods that must be captured in the benchmarking reports, introducing additional metrics, e.g., max. time-to-heal. The presented concept, with a flexible VNF-PP structure to record arbitrary metrics, enables automation of this case.
6.4.4. Elasticity and Flexibility
Having software based network functions and the possibility of a VNF to be composed by multiple components (VNFCs), internal events of the VNF might trigger changes in VNF behavior, e.g., activating functionalities associated with elasticity such as automated scaling. These state changes and triggers (e.g. the VNF’s scaling state) must be captured in the benchmarking results (VNF-PP) to provide a detailed characterization of the VNF’s performance behavior in different states.
6.4.5. Handling Configurations
As described in [RFC8172], does the sheer number of test conditions and configuration combinations create a challenge for VNF benchmarking. As suggested, machine readable output formats, as they are presented in this document, will allow automated benchmarking procedures to optimize the tested configurations. Approaches for this are, e.g., machine learning-based configuration space sub-sampling methods, such as [Peu-c].
6.4.6. White Box VNF
A benchmarking setup must be able to define scenarios with and without monitoring components inside the VNFs and/or the hosting container or VM. If no monitoring solution is available from within the VNFs, the benchmark is following the black-box concept. If, in
contrast, those additional sources of information from within the VNF are available, VNF-PPs must be able to handle these additional VNF performance metrics.
7. Open Source Reference Implementations
Currently, technical motivating factors in favor of the automation of VNF benchmarking methodologies comprise: (i) the facility to run high-fidelity and commodity traffic generators by software; (ii) the existent means to construct synthetic traffic workloads purely by software (e.g., handcrafted pcap files); (iii) the increasing availability of datasets containing actual sources of production traffic able to be reproduced in benchmarking tests; (iv) the existence of a myriad of automating tools and open interfaces to programmatically manage VNFs; (v) the varied set of orchestration platforms enabling the allocation of resources and instantiation of VNFs through automated machineries based on well-defined templates; (vi) the ability to utilize a large tool set of software components to compose pipelines that mathematically analyze benchmarking metrics in automated ways.
In simple terms, network softwarization enables automation. There are two open source reference implementations that are build to automate benchmarking of Virtualized Network Functions (VNFs).
7.1. Gym
The software, named Gym, is a framework for automated benchmarking of Virtualized Network Functions (VNFs). It was coded following the initial ideas presented in a 2015 scientific paper entitled "VBaaS: VNF Benchmark-as-a-Service" [Rosa-a]. Later, the evolved design and prototyping ideas were presented at IETF/IRTF meetings seeking impact into NFVRG and BMWG.
Gym was built to receive high-level test descriptors and execute them to extract VNFs profiles, containing measurements of performance metrics - especially to associate resources allocation (e.g., vCPU) with packet processing metrics (e.g., throughput) of VNFs. From the original research ideas [Rosa-a], such output profiles might be used by orchestrator functions to perform VNF lifecycle tasks (e.g., deployment, maintenance, tear-down).
In [Rosa-b] Gym was utilized to benchmark a decomposed IP Multimedia Subsystem VNF. And in [Rosa-c], a virtual switch (Open vSwitch – OVS) was the target VNF of Gym for the analysis of VNF benchmarking automation. Such articles validated Gym as a prominent open source reference implementation for VNF benchmarking tests. Such articles
set important contributions as discussion of the lessons learned and the overall NFV performance testing landscape, included automation.
Gym stands as one open source reference implementation that realizes the VNF benchmarking methodologies presented in this document. Gym is released as open source tool under Apache 2.0 license [gym].
7.2. tng-bench
Another software that focuses on implementing a framework to benchmark VNFs is the "5GTANGO VNF/NS Benchmarking Framework" also called "tng-bench" (previously "son-profile") and was developed as part of the two European Union H2020 projects SONATA NFV and 5GTANGO [tango]. Its initial ideas were presented in [Peu-a] and the system design of the end-to-end prototype was presented in [Peu-b].
Tng-bench aims to be a framework for the end-to-end automation of VNF benchmarking processes. Its goal is to automate the benchmarking process in such a way that VNF-PPs can be generated without further human interaction. This enables the integration of VNF benchmarking into continuous integration and continuous delivery (CI/CD) pipelines so that new VNF-PPs are generated on-the-fly for every new software version of a VNF. Those automatically generated VNF-PPs can then be bundled with the VNFs and serve as inputs for orchestration systems, fitting to the original research ideas presented in [Rosa-a] and [Peu-a].
Following the same high-level VNF testing purposes as Gym, namely: Comparability, repeatability, configurability, and interoperability, tng-bench specifically aims to explore description approaches for VNF benchmarking experiments. In [Peu-b] a prototype specification for VNF-BDs is presented which not only allows to specify generic, abstract VNF benchmarking experiments, it also allows to describe sets of parameter configurations to be tested during the benchmarking process, allowing the system to automatically execute complex parameter studies on the SUT, e.g., testing a VNF’s performance under different CPU, memory, or software configurations.
Tng-bench was used to perform a set of initial benchmarking experiments using different VNFs, like a Squid proxy, an Nginx load balancer, and a Socat TCP relay in [Peu-b]. Those VNFs have not only been benchmarked in isolation, but also in combined setups in which up to three VNFs were chained one after each other. These experiments were used to test tng-bench for scenarios in which composed VNFs, consisting of multiple VNF components (VNFCs), have to be benchmarked. The presented results highlight the need to benchmark composed VNFs in end-to-end scenarios rather than only...
benchmark each individual component in isolation, to produce meaningful VNF-PPs for the complete VNF.
Tng-bench is actively developed and released as open source tool under Apache 2.0 license [tng-bench].
8. Security Considerations
Benchmarking tests described in this document are limited to the performance characterization of VNFs in a lab environment with isolated network.
The benchmarking network topology will be an independent test setup and MUST NOT be connected to devices that may forward the test traffic into a production network, or misroute traffic to the test management network.
Special capabilities SHOULD NOT exist in the VNF benchmarking deployment scenario specifically for benchmarking purposes. Any implications for network security arising from the VNF benchmarking deployment scenario SHOULD be identical in the lab and in production networks.
9. IANA Considerations
This document does not require any IANA actions.
10. Acknowledgement
The authors would like to thank the support of Ericsson Research, Brazil. Parts of this work have received funding from the European Union’s Horizon 2020 research and innovation programme under grant agreement No. H2020-ICT-2016-2 761493 (5GTANGO: https://5gtango.eu).
11. References
11.1. Normative References
11.2. Informative References
Authors’ Addresses
Raphael Vicente Rosa (editor)
University of Campinas
Av. Albert Einstein, 400
Campinas, Sao Paulo 13083-852
Brazil
Email: rvrosa@dca.unicamp.br
URI: https://intrig.dca.unicamp.br/raphaelvrosa/
|
{"Source-Url": "https://tools.ietf.org/pdf/draft-rosa-bmwg-vnfbench-04.pdf", "len_cl100k_base": 9238, "olmocr-version": "0.1.49", "pdf-total-pages": 25, "total-fallback-pages": 0, "total-input-tokens": 50109, "total-output-tokens": 11102, "length": "2e13", "weborganizer": {"__label__adult": 0.0003981590270996094, "__label__art_design": 0.00042510032653808594, "__label__crime_law": 0.00037932395935058594, "__label__education_jobs": 0.0009660720825195312, "__label__entertainment": 0.0002219676971435547, "__label__fashion_beauty": 0.00020396709442138672, "__label__finance_business": 0.0008120536804199219, "__label__food_dining": 0.0003058910369873047, "__label__games": 0.0007548332214355469, "__label__hardware": 0.004299163818359375, "__label__health": 0.0004782676696777344, "__label__history": 0.0006623268127441406, "__label__home_hobbies": 0.0001266002655029297, "__label__industrial": 0.000823974609375, "__label__literature": 0.0004067420959472656, "__label__politics": 0.0003943443298339844, "__label__religion": 0.0004634857177734375, "__label__science_tech": 0.34765625, "__label__social_life": 0.00013315677642822266, "__label__software": 0.054168701171875, "__label__software_dev": 0.58447265625, "__label__sports_fitness": 0.00032401084899902344, "__label__transportation": 0.0006785392761230469, "__label__travel": 0.00030350685119628906}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 47217, 0.0408]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 47217, 0.5479]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 47217, 0.85534]], "google_gemma-3-12b-it_contains_pii": [[0, 1589, false], [1589, 4392, null], [4392, 7165, null], [7165, 9058, null], [9058, 11051, null], [11051, 13574, null], [13574, 14470, null], [14470, 15407, null], [15407, 17732, null], [17732, 19894, null], [19894, 21138, null], [21138, 23106, null], [23106, 25116, null], [25116, 27442, null], [27442, 29791, null], [29791, 31883, null], [31883, 34302, null], [34302, 36283, null], [36283, 38523, null], [38523, 40953, null], [40953, 43563, null], [43563, 45198, null], [45198, 45812, null], [45812, 47217, null], [47217, 47217, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1589, true], [1589, 4392, null], [4392, 7165, null], [7165, 9058, null], [9058, 11051, null], [11051, 13574, null], [13574, 14470, null], [14470, 15407, null], [15407, 17732, null], [17732, 19894, null], [19894, 21138, null], [21138, 23106, null], [23106, 25116, null], [25116, 27442, null], [27442, 29791, null], [29791, 31883, null], [31883, 34302, null], [34302, 36283, null], [36283, 38523, null], [38523, 40953, null], [40953, 43563, null], [43563, 45198, null], [45198, 45812, null], [45812, 47217, null], [47217, 47217, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 47217, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 47217, null]], "pdf_page_numbers": [[0, 1589, 1], [1589, 4392, 2], [4392, 7165, 3], [7165, 9058, 4], [9058, 11051, 5], [11051, 13574, 6], [13574, 14470, 7], [14470, 15407, 8], [15407, 17732, 9], [17732, 19894, 10], [19894, 21138, 11], [21138, 23106, 12], [23106, 25116, 13], [25116, 27442, 14], [27442, 29791, 15], [29791, 31883, 16], [31883, 34302, 17], [34302, 36283, 18], [36283, 38523, 19], [38523, 40953, 20], [40953, 43563, 21], [43563, 45198, 22], [45198, 45812, 23], [45812, 47217, 24], [47217, 47217, 25]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 47217, 0.01176]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
f5d23e16fc0de5f1a2c8074a3e5c0e1b30394148
|
AGENT: Automatic Generation of Experimental Protocol Runtime
Gwendal Le Moulec, Ferran Argelaguet, Valérie Gouranton, Arnaud Blouin, Bruno Arnaldi
To cite this version:
HAL Id: hal-01613873
https://hal.archives-ouvertes.fr/hal-01613873
Submitted on 10 Oct 2017
HAL is a multi-disciplinary open access archive for the deposit and dissemination of scientific research documents, whether they are published or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers.
L’archive ouverte pluridisciplinaire HAL, est destinée au dépôt et à la diffusion de documents scientifiques de niveau recherche, publiés ou non, émanant des établissements d’enseignement et de recherche français ou étrangers, des laboratoires publics ou privés.
Abstract
Due to the nature of Virtual Reality (VR) research, conducting experiments in order to validate the researcher’s hypotheses is a must. However, the development of such experiments is a tedious and time-consuming task. In this work, we propose to make this task easier, more intuitive and faster with a method able to describe and generate the most tedious components of VR experiments. The main objective is to let experiment designers focus on their core tasks: designing, conducting, and reporting experiments. To that end, we propose the use of Domain-Specific Languages (DSLs) to ease the description and generation of VR experiments. An analysis of published VR experiments is used to identify the main properties that characterize VR experiments. This allowed us to design AGENT (Automatic Generation of Experimental Protocol runtime), a DSL for specifying and generating experimental protocol runtimes. We demonstrated the feasibility of our approach by using AGENT on two experiments published in the VRST’16 proceedings.
1 Introduction
One of the focus of Virtual Reality (VR) researchers is the analysis of how humans behave [27], perceive [15] and interact [2] in VR environments. This research is bounded to the design of user studies in order to validate the researcher’s hypotheses. In particular, experiments in VR aim at studying the effects of a system, application, interface, algorithm, etc. on system or users. Indeed, according to Andrew Colman [4], “experimental methods [...] allow rigorous examination of causal effects”. For example, Latoschick et al. [17] designed a fake-mirror system that consists of a screen displaying the picture of an avatar imitating the movements of the user. They conducted an experiment to study the effect of the avatar nature (more or less realistic) on the feeling the users had they were standing before a real mirror.
Experiments must conform to some requirements, such as defining experimental conditions, dependent and independent variables, and the experimental protocol [8]. Research works were conducted to: guide experiment design in VR and augmented reality [10, 16, 14]; help evaluating specific concepts such as presence [23, 25], acceptability [5], or collaboration [13, 20]. Yet, experiment designers still have to develop the experimental VR application, which is a tedious, repetitive, and time-consuming task.
In this work, we propose AGENT (Automatic Generation of Experimental Protocol runtime) to ease the development of experimental VR applications. AGENT automatically generates experimental protocol runtimes letting experiment designers focus on their core tasks: designing, conducting, and reporting experiments. AGENT is based on the increasingly used Software Engineering concept of Domain-Specific Language (DSL) [31, 9, 21]. DSLs ease software production by using software languages designed to tackle specific problems. DSLs are indeed designed to have key-words, notations, and syntaxes familiar to the domain experts. DSLs should remain small, simple, and easy to use. Their design should be adapted to the organizational process of the final users [32]. By fulfilling these criteria, DSLs allow to leverage specific domain expertise of various stakeholders involved in the development of software systems [10, 12, 14].
After an experimental protocol designed within an AGENT model, this last is compiled into runnable code. The runnable code is then integrated into an already existing VR project, provided by the experiment designer.
The paper is structured as follows. Section 2 presents the state of the art of VR experiment design, the efforts made to ease the task of experiment designers, and their limits. In Section 3, an analysis of several existing and reported VR experiments is presented to characterize VR experiments. Based on this analysis, the proposed approach is detailed in Section 4. Section 5 reports and discusses the usage of our approach on two use cases. Finally, Section 6 concludes this work and presents future works.
2 State of the Art
2.1 Basics of Experimentation
Designing experiments is based on a rigorous set of principles to follow [8]. According to Andrew Colman [4], an experiment is “a research method whose defining features are manipulation of an independent variable or variables and control of extraneous variables that might influence the dependent variable”. An independent variable is “a variable that is varied by the experimenter independently of the extraneous variables”. A dependent variable is “a variable that is potentially liable to be influenced by one or more independent variables”. The main idea behind experiments is to assess what causality relations exist between different events or facts [4], i.e., the potential effect independent variables have on dependent variables. Dependent variables correspond to the data collected during experiments and can be qualitative or quantitative data [8]. Asserting the existence of an apparent causal relation between independent and dependent variables, i.e., ensure internal validity, is a necessary step [26]. Generalizing results observed on small populations, i.e., ensure external validity, requires the use of statistical methods [23, 17].
2.2 VR Experiment Design
Those general principles are applicable in every domain where experiments are used. In Computer Science, domains related to human-centered design need experiments to validate their approaches. Human-centered design indeed often implies human-computer interactions: the influence of the design properties on user-experience should be validated. Gabbard proposed guidelines and methods for designing human-centered applications and experiments [10]. Other works focus on augmented reality applications design and evaluation [16] [14].
If the classic method consists in running experiments where a population of participants uses the interfaces to evaluate, other approaches have been proposed. Stanney et al. use heuristics to guide and evaluate VR interfaces design [29]. Tromp et al. propose a usability inspection method [30], i.e., a simulation of the use of an application to find users need.
In human-centered design and more specifically in VR, some specific interface characteristics are evaluated. They are often qualitative aspects, which are not easy to evaluate because of their subjectivity [8]. Research have been done to propose standard questionnaires. Cognitive loading induced by systems can be evaluated thanks to the NASA-TLX questionnaire [12]. The Situation Present Assessment Method (SPAM) can be used to evaluate presence [6], so as other methods [25] [25] [53]. Brooke proposed an acceptability questionnaire [3]. Evaluation of collaboration was studied too: Hornbaek proposed metrics based on communication (e.g., number of uttered words per person, number of questions asked to collaborators, number of interruptions) [13]. Meier et al. completed these metrics by considering other aspects of collaboration (e.g., coordination or motivation of each actor) [20].
2.3 Easing Experiment Design
If these works focus on guiding experiment designers, implementing experimental protocols to be integrated into running applications is a manual, time-consuming and tedious task. Tools dedicated to facilitate this task exist. Field et al. proposed IBM SPSS Statistics [7], a tool for performing statistical analyses of data. Another example of such tools is the R project [4]. Software solutions for designing experimental conditions (e.g., variables, populations), and registering results can be used, e.g., EdLab [4] or Go-Lab [8], but they are more useful for other domains than VR (mostly biology, physics, or chemistry). VR could benefit of some tools referenced by the National Heritage Language Resource Center (NHRLC, California [8]) that are more human-centered. More interestingly, the framework EVE was specifically designed to ease experiment setup and implementation in Virtual Environments [11]. EVE focuses on automating data gathering and analysis but does not handle experimental protocol generation. No other solutions dedicated to VR exist.
In overall, the existing solutions are limited to experiment conditions modeling and data management. There is no code generation and the model are in general not meant to be processed by programs. Furthermore, protocol definition is often limited or nonexistent. The consequence we observed ourselves is that researchers end-up by developing their own limited and ad hoc solutions. There are no libraries or projects that generate running code for VR experiments.
2.4 Model-Driven Engineering and Domain-Specific Languages
Software industry faces the constant increase of systems complexity. Modelling aims at mastering this complexity through the Model-Driven Engineering (MDE) domain [24]. In MDE, models focus on specific problems for a specific audience to ease the software development process. MDE tools help software engineers in developing and tooling languages that are designed to answer specific problems; such languages are called domain-specific languages (DSL) [1]). DSLs provide a bridge between the problem space in which domain experts (experiment designers in our case) work and the implementation space. Developed DSLs usually come with associated tools such as editors, code generators, simulators.
3 VR Evaluations: a Preliminary Analysis
In this section we study recent research papers to draw up a precise map of the concepts related to VR experiment design. The goal is to identify the properties that characterize experiments in VR.
We have studied 15 papers and posters from the VRST’16 proceedings [1] where experiments are conducted on various topics: displays, latency, training, presence, human behavior simulation, haptics, tracking, cinematic VR, distance perception, and 3D user interfaces. We focused on experiment design: mathematical and statistical analysis of data is not in the scope of this paper (but in future works). Obviously, the set of identified properties - obtained empirically - can not cover all VR experiments. Though, we consider that recent VRST papers are representative enough. Hence, the drawn properties cover a large scope of VR experiments.
The first observation we made is that designing an experiment can be divided into two main tasks: (1) experimental conditions and variable design, and (2) protocol design. We reported our analysis on two mind-maps, respectively for the concept of variable and the concept of protocol (see Figures 1 and 2). This allowed us to quickly obtain a structure of concepts specific to VR experiments. Figures 1 and 2 summarize the main concepts we identified. Section 3.1 discusses experimental conditions and variable design. Section 3.2 discusses protocol design.
3.1 Variables
Two types of variables exist: dependent and independent variables. Dependent variables can be quantitative: physiological constants, e.g., blood pressure, time for performing a task, performance of the subject, accuracy of a method. They can also be subjective feelings, e.g., how the subject appreciated a task, how comfortable it was. Questionnaires like the ones presented in Section 2 can be used to record these qualitative measures. Hence, data can come from various sources: mainly physiological sensors, software measurements, and forms. As a result, two first properties can be drawn up to characterize VR experiments:
P1: dependent variables can be of different types (integer, float, boolean, mark, customized types, etc.)
P2: dependent variables correspond to three types of data sources: sensors, software measurements, and forms.
Independent variables correspond to what is under evaluation or comparison: metaphors, navigation, interaction
or rendering techniques, hardware setups, algorithms, environmental conditions, etc. Hence, independent variables correspond to software or hardware features developed or studied by the experiment designers. In experiments, two usages are possible for independent variables:
- comparison, e.g., several metaphors are compared to determine which one is the most appreciated,
- determining the effect of a single condition, e.g., one specific environmental condition is activated and then deactivated to determine the effect induced by its presence.
Independent variables can then be of two types: boolean (compare presence / absence) and enumeration (comparison of several conditions). The possible values of independent variables are called “levels”. Two more properties can then be added:
P3: two types are possible for independent variables: boolean and enumeration.
P4: independent variables and their levels correspond to software or hardware features that can vary.
All possible levels are not necessarily presented to each participant of an experiment. In some cases, several groups of participants - exposed to different conditions - are necessary. For example, to evaluate the effect of a navigation technique on cybersickness, two groups could be made: one group of subjects exposed to the navigation technique under evaluation and one control group, exposed to a known navigation technique that does not induce abnormal cybersickness. Conditions that are evaluated on all participants of a study are called “within-subject factors”, whereas conditions that differ from one group to another are called “between-subject factors”. One more property can be drawn up:
P5: between-subject factors imply to make several groups, each of them corresponding to a distinct protocol.
3.2 Protocol
The protocol is the process that participants follow during a session. We consider that it begins when the participants start to use the VR experimental application, i.e., we consider the protocol starts after preliminary phases during which the participants have to read and sign a consent form and are associated to identifiers, for anonymity reasons. If there are between-subject factors and hence several groups, each group is associated to a different protocol, with the only difference being at the level of the between-subject factors. This is the statement of property P6:
P6: the protocols of each group differ only at the level of between-subject factors.
The part of the protocol on which we focus is often separated into two phases: (1) an acclimatization and / or calibration phase and (2) a data acquisition phase. The acclimatization phase role is to train the participants to the use of the VR application: they should be used to the different conditions they will experiment. During the acclimatization phase, participants repeat several times the different conditions, very often in a randomized order. During this phase, it is possible to adapt the number of repetitions to the participants. A calibration phase with similar characteristics can be performed, e.g., if some sensors must be calibrated.
The data acquisition phase role is to record data, and hence to evaluate the influence of the independent variables on the dependent variables. Participants repeat also several times the different conditions in a randomized order. The number of repetitions is generally greater than in acclimatization phase and must be the same for each participant. A last property can be added:
P7: in acclimatization and calibration phases, the subject perform tasks but no data is collected.
4 Approach
The properties that characterized VR experiments are now used to propose an approach for easing their design and production.
4.1 Overview
The proposed approach allows to design VR experiments with the use of a DSL we designed based on the properties identified in Section 3. This DSL is called AGENT (Automatic Generation of Experimental Protocol). Models produced with this DSL are compiled into code to be integrated into VR projects (e.g., Unity 3D projects). Figure 3 depicts the processing chain of the approach.
The use of AGENT produces an AGENT model that is then compiled into runnable code integrable into a VR project. An AGENT model is composed of two parts: an experimental conditions model and a protocol model. It is up to the experiment designer to provide to AGENT all the VR
components that are not directly related to the experiment (i.e., 3D models, metaphors, interactions, etc.).
The remaining of Section 4 is organized as follows. Section 4.2 introduces an illustrative example as a basis for the detailed explanation of the approach. Section 4.3 presents the experimental conditions model structure. Section 4.4 presents the protocol model structure. Section 4.5 ends the presentation of the approach by presenting the compilation and integration steps.
4.2 Illustrative Example
Consider a VR experiment of which independent variables are:
- $I_b$, a boolean variable (between-subject factor),
- $I_e$ with two levels: $L_1$ and $L_2$ (within-subject factor).
The dependent variables are:
- $D_q$, answers to a questionnaire, in the form of Likert-scale marks, for evaluating the task regarding independent variables possible values,
- $D_s$, speed of execution of the task.
The protocol is as follows:
1. acclimatization phase: the subject executes the task $2 \times 4$ times, i.e., 4 times each condition among the condition set $C_b$ or $C_{\neg b}$, depending on the group (see Equations (1) and (2)), no data being recorded,
2. data acquisition: the subject executes the task $2 \times 32$ times, i.e., 32 times each condition among $C_b$ or $C_{\neg b}$, with $D_s$ being recorded,
3. subjective evaluation: the subject answers the questionnaire.
The two groups, respectively exposed to the conditions $C_b$ and $C_{\neg b}$ are called $G_b$ and $G_{\neg b}$.
4.3 Experimental Conditions Model
The experimental conditions model is the part of an AGENT model that describes the independent and dependent variables. Figure 4 depicts the concepts of this DSL in the form of a UML class diagram. Figure 5 shows the experimental conditions model designed using AGENT that corresponds to the example of Section 4.2.
An experimental conditions model has a tree-like structure. The tree is composed of three mandatory nodes: (1) the root that defines the name of the model, and its two child nodes; (2) the “independent variables” node; (3) the “dependent variables” node. The independent and dependent variables are respectively to be defined under the nodes (2) and (3), as their child nodes.
According to **P3**, there are two types of independent variables: boolean and enumeration variables. Enumeration variables are constituted of possible levels, each level being defined under the node corresponding to their variable (e.g., see Figure 5).
There are two types of dependent variables: objective and subjective variables. Objective variables are data collected from software or hardware resources (physiological sensors and software measurements of **P2**) and can be of various types (e.g., boolean, integer, enumeration, float, customized types, etc.), according to **P1**. The linkage of objective dependent variables to their data source is managed by the integration module (see Section 4.5), not by the experimental conditions model, where only the names of the variables can be provided (e.g., $D_s$). Subjective variables are questions asked to participants and their answers, gathered into special forms designed by the experimenters (see **P2**). In the experimental conditions model, the experiment designer can define forms with an identifier (e.g., $D_q$) and a hyperlink allowing to access the form. In the remaining of the paper, all the leaves of an experimental conditions model (i.e., boolean independent variables, variable levels, questionnaires, and objective dependent variables) will be called **features**.
### 4.4 Protocol Model
#### 4.4.1 Description
Figure 6 depicts the concepts that are presents in protocol models in the form of a class UML diagram. It shows that AGENT allows to define experimental protocols as lists. Figure 7 shows such a list, that contains three elements separated by arrows. Some elements are composed, e.g., the second element in Figure 7 is composed of Condition1, Condition2, and Acclim. Figure 7 shows the protocol model designed using AGENT that corresponds to the group $G_b$ of the example presented in Section 4.2. The protocol of group $G_{-b}$ is the same, but feature $I_b$ is not present (set to false). Note that between-subject and within-subject factors are implicitly defined in AGENT. The distinction is made if several groups (hence several protocol models) exist: variables corresponding to between-subject factors are the ones that vary from a protocol model to another. Properties **P5** and **P6** are then satisfied.
A protocol model is a states list with five types of state: (1) start state (green disk on Figure 7), end state (red disk), simple state (yellow rectangle), random-loop state (purple rectangle), and customized-loop state (orange rectangle, see Figure 11). The core idea behind protocol models is that each phase of the experiment (simple, random-loop, and customized-loop states) corresponds to the selection of a subset of the features defined by an experimental conditions model. Let’s consider the protocol given the example of Section 4.2. First, the subject goes through an acclimatization phase where he has to perform the task 8 times, covering 2 conditions that are combinations of the independent variables possible values. Second, he does the same thing but with 64 repetitions, and with data being recorded, i.e., considering the effect of the independent variables on the dependent variable $D_s$. Third, he completes the questionnaire corresponding to the set of dependent variables identified by $D_q$. Hence, each step corresponds to the selection of several features from the experimental conditions model of Figure 5. For each step of a protocol model, the selected features are listed under the “Features” label (see Figure 7). For example, in the simple state SubjectiveEval, there is only one feature selected: $D_q$.
The case of loop states (random-loop and customized-loop) is more complex. A loop state models the repetition of a task under different conditions. The number of repetitions for each condition, i.e., the multiplicity (see Figure 6), is indicated at the top-right corner of each loop state (see Figure 7). Conditions are modeled as blue rectangles linked to the loop state that cover them. Conditions make references to features, so as loop states do. If a feature is held by the loop state itself, then it means that this feature is active for all repetitions and conditions. For example, in the DataAcq state corresponding to the step (2) of the illustrative proto-
col, data is recorded whatever the current condition. The between-subject factor $I_b$ is also set to true for the group $G_b$ in all cases. Hence, the feature $D_s$ is held by the random-loop state (as so as $I_b$ for $G_b$). If a feature is held by a condition, then it means that the feature is active only for repetitions where the condition is active.
Random-loop states allow to model repetitions where conditions come in a random order. The multiplicity is an integer (see Figure 3) that represents the number of times each condition will be repeated. Customized-loop states allow to model other kinds of repetitions, e.g., deterministic or based on the participants choice. Sometimes experiment designers indeed propose phases where participants can repeat conditions on demand [19]. To handle this case, the multiplicity of customized-loop states is not an integer but an interval (notation “$n..N$”), limited (notation “$n..N$”), or unlimited (notation “$n..+$”).
Note that differentiating acclimatization and data acquisition phases is illustrated here: acclimatization phases are loop states where data recording is deactivated (no dependent variable in the feature list of the loop state). Data acquisition phases are on the contrary loop states (in general random-loop states) where data recording is activated. In our approach, acclimatization and calibration phases are represented the same way: extraneous calibrations of any kinds are not managed by AGENT. $P7$ is then satisfied.
4.4.2 Discussion
The choice of modeling protocols as lists comes from the preliminary study (see Section 3). Lists are sufficient because of the nature of VR experiments: protocols do not allow alternatives. However, when there are between-subject variables, the protocol varies from one group to another. In our approach, the experiment designer simply has to make one protocol model per group. The only variations between the different protocols are at the level of the features corresponding to between-subject variables. That is why the concepts of between-subject and within-subject variables do not appear explicitly in AGENT.
Other variations may appear at the task level. The subject could indeed have the choice to execute some actions in the order he wants. For example, consider a task consisting in selecting multiple objects in the Virtual Environment, the subject could chose in which order he selects the objects. However, these variations are at the level of the use-case and do not correspond to variations of the protocol in itself. Variations in the use-case are not explicit in the protocol model. The $P7$ condition means that the transition is triggered randomly. Final states are marked by a cross.
4.5 Code Generation and Integration
After an experiment protocol was modeled, runnable code can be generated through the use of the AGENT compiler. The generated runnable code can be integrated into the VR project through the AGENT integration module. The runnable code is characterized in Section 4.5.1. The transformation operations that allow to compile AGENT models to runnable code are precised in Section 4.5.2. The integration module is presented in Section 4.5.3.
4.5.1 Generated Runnable Code Characterization
As Figure 3 shows, the generated runnable code can be characterized by a runtime model. The runtime model is a state machine. For example, the runtime model generated from the example of Section 4.2 (group $G_b$) is represented in Figure 8.
On the figure, the rounded rectangle is a state containing itself a state machine. Conditions triggering a transition are indicated between brackets. Actions resulting from the triggering of a transition follow the slash. The variable $t nb$ is the number of executed trials. The variable $f$ is the set of selected features. The $r$ condition means that the transition is triggered randomly. Final states are marked by a cross.
4.5.2 Compilation: from AGENT Model to Runnable Code
Figure 8 already gives the intuition of the transformation algorithm (from protocol model to runtime model). The formal algorithm will not be given for the sake of simplicity and concision. We will only give the intuition of it.
Transformation of Start, End, and Simple States. The transformation operator applied to the start, end, and simple states is the identity: they are respectively transformed to initial, final, and standard states of the runtime model.
Transformation of Transitions. Two possibilities exist:
1. the origin state of the transition is a start, end, or simple state. In that case, the transformation operator is the identity.
2. the origin state of the transition is a loop state. In that case, the generated transition is conditional: the condition for going through the generated transition is that the number of loops defined in the loop state where ran.
In all cases, the generated transitions must trigger events: the deselection of the features held by the origin state and the selection of the features held by the target state.
Transformation of Loop States. Loop states are transformed to sub-state-machines. Each condition is transformed to a state. The sub-state-machine must loop on each of these states a number of time conform to the multiplicity of the loop state. Obviously features held by the conditions must be selected or deselected adequately.
4.5.3 Code Integration
The integration module is composed of 3 libraries that the experiment designer has to use in order to integrate properly the generated runnable code to the VR project. This section presents conceptually these libraries. Concrete usage of them is presented in Section 5.
**Feature Binding Library** The experiment designer must bind the experimental conditions model features to runtime features (e.g., metaphors, interactions, virtual objects, etc.), that he provides (see Figure 5). For example, the feature $L_1$ represented in Figure 4 could be bound to a virtual object (runtime feature). The selection (resp. deselection) of $L_1$ in the runtime model would make the virtual object appear (resp. disappear). Conceptually, the feature binding library is a map that links experimental conditions model features to runtime features, with two functions to implement for specifying what happens at each selection / deselection of a feature. Objective dependent variables are associated to their data source (e.g., a field in a class, the output of a measurement tool, etc.), that can be of various types. Property $P_1$, $P_2$, and $P_4$ are then satisfied.
**Condition Sequencing Library** This library provides several algorithms for sequencing the conditions in the case of loop states: random with constant seed, random with several algorithms for sequencing the conditions in the case of loop states: random with constant seed, random with time-based seed, deterministic with fixed number of loops, controlled by the user, etc.
**Trial Completion Management Library** Trial completion is managed by the runtime model at the experiment level, i.e., loop conditions are changed after each trial completion. However, trial completion must be detected and the resulting effects on the Virtual Environment must be triggered. Consider for example a task consisting in going from a departure point $D$ to an arrival point $A$. Trial completion should be detected when the arrival point $A$ is reached and the triggered effect would be to make the avatar automatically return to the departure point $D$, for starting a new trial with other conditions. The experiment designer can use the trial completion management library to add conditions and effects corresponding to trial completion to the transitions of the runtime model.
4.6 Properties Fulfilling
Our approach satisfies the properties listed in Section 3:
- $P_1$: the type of an experimental conditions model feature is the type of its bound runtime feature, which is freely determined by the experiment designer (see Section 4.5.3).
- $P_2$: Questionnaire dependent variables are bound to forms thanks to an hyperlink (see Figures 4 and 5). ValueSource dependent variables are bound to data sources which nature is determined by the experiment designer.
- $P_3$: the boolean and enumeration types are defined (Figure 4).
- $P_4$: binding experimental conditions model features to runtime features is ensured (see Section 4.5.3).
- $P_5$ and $P_6$: between and within subject factors are implicitly defined (see Section 4.4).
- $P_7$: acclimatization phases are loop states where data recording is deactivated (see Section 4.4).
4.7 Implementation
AGENT was developed using DSL Tool[1] a Visual Studio 2014 extension for creating DSLs. The AGENT compiler has been developed in C#. Once an AGENT model designed by an experiment designer, code can be automatically generated from this model by the compiler. The generated code consists of XML files that implement the state machine structure of the runtime model. It comes along with pre-coded C# classes and an interpreter, provided with AGENT, that implements the dynamic aspect of the runtime model. The generated classes and the interpreter are meant to be used with Unity 3D (we discuss adaptation of AGENT for other VR platforms in Section 5.3). The integration module is a Unity library, presented in more details in Section 5.1.
5 Creating an Experiment Using AGENT
In this section, we explain step by step the usage of AGENT to produce an experiment. Section 5.2 presents the use of AGENT on two real use-cases reported in the ACM VRST 2016 proceedings [1]. We end this section with a discussion (Section 5.3).
5.1 Usage
The usage of AGENT is composed of three main steps: modeling, code generation, and code integration.
5.1.1 Modeling
In our implementation, the experimental conditions model and the protocol model are made using AGENT, developed as Visual Studio extensions. To produce one of the models, the experiment designer has first to create a new Visual Studio project with the appropriate model type. He can then create the model by drag-and-dropping the different components (e.g., experimental conditions model features, protocol model states, transitions, etc.) on a conception area. The text fields and features lists can be edited directly on the created components. Figures 6 and 7 show examples (screen captures) of models built using the AGENT DSL within Visual Studio. Once the models are conceived they are saved into XML files that are the input data for the code generation step.
5.1.2 Code Generation
The compiler takes as entry the XML files and generates an output XML file that represents the structure of the state machine. The output XML makes reference to pre-coded C# classes and are provided with AGENT. These classes are responsible of transitions implementation.
5.1.3 Code Integration
All the integration is done in Unity at the level of one provided prefab with three child nodes: one for each library defined in Section 4.5.3. They are each composed of Unity scripts that have to be inherited to produce new scripts to attach to the nodes of the provided prefab.
**Feature Binding Library** Figure 9 shows an example of feature binding in Unity, based on the example of Section 4.2. This library contains several scripts, each of them allowing to bind a feature to a special kind of Unity resource (e.g., GameObject, script, field, etc.). Each of these script define at least two fields: one for specifying the feature name, and another for specifying the Unity resource it is bound to runtime features, with two functions to implement for specifying what happens at each selection / deselection of a feature. Objective dependent variables are associated to their data source (e.g., a field in a class, the output of a measurement tool, etc.), that can be of various types. Property $P_1$, $P_2$, and $P_4$ are then satisfied.
https://www.visualstudio.com
They also define two methods to be implemented by the experiment designer, for managing feature selection and de-selection. To bind features to external data sources (e.g., physiological sensors), the experiment designer can bind the desired features to a Unity script which reads the external data.
Condition Sequencing Library This library is composed of two scripts, corresponding to the two types of loop states. They allow to associate a loop state to sequencing algorithms we provide. The customized-loop script allows in particular to detect user requests to either end the loop or switch conditions.
Trial Completion Management Library This library is composed of one script that defines two functions to implement, for specifying the trial completion condition and the trial completion effect. A field allows to reference the protocol model state it is bound to.
5.2 Use-cases
We used our approach on two experiments. The first use-case is an experiment we reported [18]. The AGENT model was made, the code was generated, and then integrated to the Unity project of the associated VR application. (obviously, the former code parts that were responsible of the protocol runtime were removed). The refactored experiment is fully functional.
The second use-case was the experiment reported by Mossel et al. [22]. In this experiment, Mossel et al. compare two segmentation and selection techniques (Raycast and CutPlane). They evaluate their effects on user efficiency in function of the difficulty of the selection task. The AGENT model was made and the code was generated. Section 5.2.1 presents the models we made from this work (Figures 10 and 11). Section 5.2.2 presents the code integration process for producing the complete experiment.
5.2.1 Modeling
Figure 10 shows the experimental conditions model made with AGENT, from the work of Mossel et al. In the presentation of their experiment, Mossel et al. give clearly the independent variables “The participants had to use both Raycast and [...] CutPlane [...] in combination with all three
Figure 10: experimental conditions model from the experiment of Mossel et al. [22].
Figure 11: protocol model from the experiment of Mossel et al. [22].
scenarios”. The three scenarios each correspond to a level of difficulty: selecting a Fully visible, Partially occluded, or Fully occluded object. Hence, there are two enumeration variables (Vis and Sel on Figure 10) with respectively two and three values: Raycast, CutPlane; and visible, partOccl, fulOccl. The dependent variables are then explicitly given by Mossel et al. The “Objective Performance Measures” are: TaskDuration, WalkDistance, SegmentationMiss, SelectionMiss. The “Subjective Performance Measures” are gathered in a post-questionnaire we identified by postQ in Figure 10.
Figure 11 shows the protocol model. The phases are: “training phase, […] experiment, and […] a post-questionnaire”. The three phases are represented with the three states of the protocol model in Figure 11: Training, Experiment, PostQuestionnaire. PostQuestionnaire is a simple state because the participant only has to answer to the questions. The Experiment state is a random-loop of multiplicity 1 with six conditions combining the values of the two independent variables (see Figure 11). The justification can be found in two sentences from Mossel et al.: “The participants had to use both Raycast and CutPlane in combination with all three scenarios. That results in total in six different tasks which the participants perform in random order”. Training corresponds to an acclimatization phase. Mossel et al. give this description: “[Participants] were freely interacting in a test environment, which comprised a simple Unity3D scene with some artificial virtual objects that could be segmented and selected and where objects’ visibility ranged from visible to fully occluded. As soon as the user reported to feel confident, the experiment stage […] started”. Hence, Training is a customized-loop state with unlimited multiplicity (0...*). All visibility conditions are presents in the Virtual Environment (visible, partOccl, fulOccl). The user can switch between the two selection techniques, which explains the two conditions TrainingC1 and TrainingC2 in Figure 11.
5.2.2 Code Integration
With the feature binding library, the experiment designers can bind the independent variables to the Unity components that manage them. In the state Training, the three visibility conditions are selected at the same time. It just means that they coexist at the same time in the test environment. The objective independent variables (TaskDuration, WalkDistance, SegmentationMiss, SelectionMiss) are to be bound to numeric calculated fields (i.e., fields in Unity scripts) that are updated automatically by the VR application and that correspond to the task duration, the walk distance, the number of inappropriate segmentation attempts, and the number of inappropriate selection attempts, for each trial.
With the condition sequencing library, the experiments designers can choose the implementation they want for the random-loop state. They can also make the Training loop state end by detecting the user request, performed on the UI. Switching between the conditions TrainingC1 and TrainingC2 is also made by detecting a user request.
With the trial completion management library, the experiment designers can precise the trial end condition: the user performed the segmentation and selection task. It can be for example detected through a Unity script. The action to perform to begin the new trial is to reset the position of the user to the start position.
5.3 Discussion
AGENT is made to work with Unity. However it is possible to adapt it to other VR platforms (e.g., CRYENGINE, Unreal, etc.). The modeling part of AGENT does not need to be modified. We estimate that the compiler needs to be partially re-implemented. The integration module needs to be totally re-implemented. Nevertheless we estimate that the induced effort is minimal. These re-developed components are indeed reusable and they remain small.
The compiler needs only to translate the protocol model to a state machine. Estimating the effort for implementing The integration module is more difficult because it highly depends on the target platform. However, if we base our estimation on the implementation, the only task is to develop a dozen of classes, each one containing no more than ten lines of fields and functions definitions.
Furthermore, producing an experiment with our implementation can be done in few hours. To integrate the code, some functions must be implemented (see Section 5.1.3). We estimate that five lines of code for each of them is a maximum.
6 Conclusion and Future Works
In this paper, we presented an approach for the automatic generation of experimental protocol runtime. We conducted a study on fifteen experiments reported in the VRST’16 proceedings [1], to determine the properties our approach should satisfy. Seven properties could be drawn up. These properties define the main concepts our approach has to take into consideration: independent and dependent variables; between and within subject factors; acclimatization, calibration, and data acquisition phases of the protocol. They also highlight the diversity of the independent and dependent variables in experiments: variables can be software or hardware features, measurements or subjective analysis, data can be produced by very specific devices, e.g., for measuring physiological constants.
We designed an approach conform to these properties. We then introduced the AGENT DSL, that generates the experimental protocol runtimes. More particularly, AGENT allows to write experimental conditions models and protocol models. These models are then compiled into runnable code, for integration in a VR project.
We demonstrated the feasibility of our approach by using AGENT on two reported experiments. One of them was completely rebuilt and for the other one we generated the code. The 15 experiments reported in the VRST’16 proceedings 11 can be generated with the usage of AGENT.
In future works, we have the intention to submit AGENT to a user-study to evaluate its efficiency over manual implementation. We also plan to evaluate its replicability with engines different from Unity. Moreover, we plan to extend this work to the statistical analysis step, by performing it automatically after the experiment was conducted. Finally, we plan to investigate further the automatic production of VR applications. In other domains than experiments, the production of VR applications is indeed done manually, without code or concept reuse. In particular, we plan to propose an approach for automatically generating VR applications for training.
References
|
{"Source-Url": "https://hal.archives-ouvertes.fr/hal-01613873/file/AGENT_HAL.pdf", "len_cl100k_base": 8962, "olmocr-version": "0.1.49", "pdf-total-pages": 11, "total-fallback-pages": 0, "total-input-tokens": 35205, "total-output-tokens": 10781, "length": "2e13", "weborganizer": {"__label__adult": 0.000396728515625, "__label__art_design": 0.0006299018859863281, "__label__crime_law": 0.00026607513427734375, "__label__education_jobs": 0.00214385986328125, "__label__entertainment": 0.0001131892204284668, "__label__fashion_beauty": 0.0001875162124633789, "__label__finance_business": 0.0002346038818359375, "__label__food_dining": 0.00034689903259277344, "__label__games": 0.0011644363403320312, "__label__hardware": 0.0009937286376953125, "__label__health": 0.0006308555603027344, "__label__history": 0.00040841102600097656, "__label__home_hobbies": 0.0001188516616821289, "__label__industrial": 0.0004012584686279297, "__label__literature": 0.00034236907958984375, "__label__politics": 0.00023114681243896484, "__label__religion": 0.0004382133483886719, "__label__science_tech": 0.0733642578125, "__label__social_life": 0.00013530254364013672, "__label__software": 0.01239776611328125, "__label__software_dev": 0.90380859375, "__label__sports_fitness": 0.0003814697265625, "__label__transportation": 0.0005192756652832031, "__label__travel": 0.0002601146697998047}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48074, 0.03918]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48074, 0.63218]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48074, 0.90527]], "google_gemma-3-12b-it_contains_pii": [[0, 1115, false], [1115, 6366, null], [6366, 12913, null], [12913, 17330, null], [17330, 19567, null], [19567, 23883, null], [23883, 29253, null], [29253, 35864, null], [35864, 38079, null], [38079, 44679, null], [44679, 48074, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1115, true], [1115, 6366, null], [6366, 12913, null], [12913, 17330, null], [17330, 19567, null], [19567, 23883, null], [23883, 29253, null], [29253, 35864, null], [35864, 38079, null], [38079, 44679, null], [44679, 48074, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48074, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48074, null]], "pdf_page_numbers": [[0, 1115, 1], [1115, 6366, 2], [6366, 12913, 3], [12913, 17330, 4], [17330, 19567, 5], [19567, 23883, 6], [23883, 29253, 7], [29253, 35864, 8], [35864, 38079, 9], [38079, 44679, 10], [44679, 48074, 11]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48074, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
8e8e524aeea6a16d5bc182c68ce1b9ab12225630
|
[REMOVED]
|
{"len_cl100k_base": 13176, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 44279, "total-output-tokens": 15657, "length": "2e13", "weborganizer": {"__label__adult": 0.0004622936248779297, "__label__art_design": 0.0003745555877685547, "__label__crime_law": 0.00027561187744140625, "__label__education_jobs": 0.0007500648498535156, "__label__entertainment": 8.440017700195312e-05, "__label__fashion_beauty": 0.00018918514251708984, "__label__finance_business": 0.0001552104949951172, "__label__food_dining": 0.0003292560577392578, "__label__games": 0.0008673667907714844, "__label__hardware": 0.0008950233459472656, "__label__health": 0.00048232078552246094, "__label__history": 0.0001996755599975586, "__label__home_hobbies": 9.16123390197754e-05, "__label__industrial": 0.00029921531677246094, "__label__literature": 0.00027632713317871094, "__label__politics": 0.00023257732391357425, "__label__religion": 0.00044798851013183594, "__label__science_tech": 0.01546478271484375, "__label__social_life": 0.00010347366333007812, "__label__software": 0.005168914794921875, "__label__software_dev": 0.9716796875, "__label__sports_fitness": 0.0003285408020019531, "__label__transportation": 0.0004477500915527344, "__label__travel": 0.00020182132720947263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 62547, 0.04906]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 62547, 0.1729]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 62547, 0.85041]], "google_gemma-3-12b-it_contains_pii": [[0, 5262, false], [5262, 9524, null], [9524, 13882, null], [13882, 21034, null], [21034, 24787, null], [24787, 31599, null], [31599, 38680, null], [38680, 44767, null], [44767, 49030, null], [49030, 55446, null], [55446, 62547, null], [62547, 62547, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5262, true], [5262, 9524, null], [9524, 13882, null], [13882, 21034, null], [21034, 24787, null], [24787, 31599, null], [31599, 38680, null], [38680, 44767, null], [44767, 49030, null], [49030, 55446, null], [55446, 62547, null], [62547, 62547, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 62547, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 62547, null]], "pdf_page_numbers": [[0, 5262, 1], [5262, 9524, 2], [9524, 13882, 3], [13882, 21034, 4], [21034, 24787, 5], [24787, 31599, 6], [31599, 38680, 7], [38680, 44767, 8], [44767, 49030, 9], [49030, 55446, 10], [55446, 62547, 11], [62547, 62547, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 62547, 0.19667]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
de42f71f6700f578fbbae99ef7d24d96b57d86c5
|
An Industrial Case Study on the Automated Detection of Performance Regressions in Heterogeneous Environments
King Chun Foo\textsuperscript{1}, Zhen Ming (Jack) Jiang\textsuperscript{2}, Bram Adams\textsuperscript{3}, Ahmed E. Hassan\textsuperscript{4}, Ying Zou\textsuperscript{5}, Parminder Flora\textsuperscript{6}
BlackBerry\textsuperscript{1,6}, York University\textsuperscript{2}, Polytechnique Montréal\textsuperscript{3}, Queen’s University\textsuperscript{4,5}, Canada
zmjiang@cse.yorku.ca\textsuperscript{2}, bram@polymtl.ca\textsuperscript{3}, ahmed@cs.queensu.ca\textsuperscript{4}, ying.zou@ece.queensu.ca\textsuperscript{5}
Abstract—A key goal of performance testing is the detection of performance degradations (i.e., regressions) compared to previous releases. Prior research has proposed the automation of such analysis through the mining of historical performance data (e.g., CPU and memory usage) from prior test runs. Nevertheless, such research has had limited adoption in practice. Working with a large industrial performance testing lab, we noted that a major hurdle in the adoption of prior work (including our own work) is the incorrect assumption that prior tests are always executed in the same environment (i.e., labs). All too often, tests are performed in heterogeneous environments with each test being run in a possibly different lab with different hardware and software configurations. To make automated performance regression analysis techniques work in industry, we propose to model the global expected behaviour of a system as an ensemble (combination) of individual models, one for each successful previous test run (and hence configuration). The ensemble of models of prior test runs are used to flag performance deviations (e.g., CPU counters showing higher usage) in new tests. The deviations are then aggregated using simple voting or more advanced weighting to determine whether the counters really deviate from the expected behaviour or whether it was simply due to an environment-specific variation. Case studies on two open-source systems and a very large scale industrial application show that our weighting approach outperforms a state-of-the-art environment-agnostic approach. Feedback from practitioners who used our approach over a 4 year period (across several major versions) has been very positive.
I. INTRODUCTION
Performance regressions are regressions (defects) caused by the degradation of system performance compared to prior releases. Many large-scale systems like Facebook, Google and the Blackberry infrastructure, which are used by millions of people worldwide, cannot afford any downtime. A slight performance degradation can lead to a very large increase in operating costs \cite{28}. In fact, many field problems in such systems are performance-related \cite{4}, \cite{35}. Hence, to ensure the quality of these systems, performance regression testing is a required testing procedure in addition to regular, conventional functional regression testing.
Performance regression testing detects performance regressions by measuring the system’s performance in field-like settings \cite{2}, \cite{3}. A performance regression test usually runs from hours to days. During the course of the test run, execution logs and hundreds of performance counters for the running system are recorded. The logs describe the high-level actions performed during each user session, whereas the counters measure metrics like CPU and memory utilization per time interval. After the test is completed, performance analysts need to compare counters against pre-defined thresholds to flag counters that are at alarming levels. The analysts then selectively examine other counters in an attempt to uncover all performance regressions. Analysts commonly use the logs to investigate the rationale for performance regressions.
Such manual detection of performance regressions is inefficient and error-prone due to the large volume of data that is analyzed, the limited knowledge of testers about the tested system, and the time pressure associated with fast release cycles \cite{23}. Hence, in prior research \cite{17}, \cite{23}, \cite{25}, we proposed the automation of such analysis through the mining of historical performance data (e.g., CPU and memory usage) from prior test runs. By building models based on prior successful test runs (either based on the performance counter data or on the execution logs), we are able to classify new test runs as either a pass or a failure with high accuracy. Furthermore, one can also build models to pinpoint the component or node causing the performance regression.
However, such research has had limited adoption in practice. A major hurdle is the incorrect assumption that new tests will always be run in the same environment (e.g., labs with same configurations) as the prior tests. Since labs are a significant investment and typically bought through bids, it is impossible to ensure that all prior tests are run in the same environment. Furthermore, the different hardware and software upgrade cycles of test labs lead to heterogenous lab environments at any moment in time with tests being scheduled in labs based primarily on lab availability. Finally, for long lived systems, prior tests are most likely to have been conducted on different labs than the current ones.
Heterogeneity is a show-stopper from the perspective of industrial adoption of automated performance regression analysis. For example, in an e-commerce system, the system bottleneck may shift from the database to the application server if the database is upgraded with a faster disk. Hence, when trying to adopt one of our previous approaches \cite{17} in an industrial setting, we discovered that our approach performed significantly worse than during our evaluation, which assumed that all tests were conducted in similar environments. Analysis techniques that cannot differentiate between actual
performance regressions and performance differences caused by different environments will lead to incorrect conclusions being drawn about the quality of a system.
In this paper, we make automated performance regression analysis work in practice by building ensembles (i.e., groups) of models, with each model deriving performance rules from a specific prior test (and, hence, configuration). For example, one model might produce a rule for a specific version that indicates that low CPU utilization and high database transaction counts are associated with high throughput, whereas another model for a different version indicates that high database transactions by itself is associated with high throughput. By combining all models (and their associated rules), then trying to assign more weights to those models that were run in the environment most similar to the new test run, we aim to make the detection of performance regressions resilient to heterogeneous environments. The contributions of this paper are as follows:
- We use ensemble learning techniques to detect performance regressions in heterogeneous environments.
- We empirically validate our ensemble-based techniques on two major open source and one large enterprise system. We provide the data used in our open source studies online to encourage other researchers to replicate our studies.
- We show that ensemble techniques achieve higher precision and recall than our state-of-the-art environment-agnostic approach.
II. CURRENT PRACTICE AND RESEARCH
State of Practice. Today, organizations rely on manual (time-consuming and error-prone) approaches for analyzing performance regression tests. Once a performance regression test is completed, performance analysts use domain knowledge and the results of prior test runs to manually look for large deviations of counter values (e.g., higher CPU utilization). If the analysts conclude that the observed deviations represent performance regressions, a defect report is filed.
Organizations currently maintain different lab environments to execute performance tests in parallel. These labs may contain varying hardware configurations, such as different CPUs and disks, and software configurations, such as different operating system architectures (e.g., 32-bit and 64-bit) and database versions. This heterogeneity is partly because of inconsistent upgrade cycles, but mostly in order to simulate the heterogeneous environments in which the system will be deployed. Since performance tests executed with different configurations may exhibit different performance behaviour, not being able to distinguish performance differences caused by heterogeneous configurations from those caused by performance regressions, will cause many false alarms, either delaying software release by several weeks or (in the worst case) reducing the confidence practitioners have in the performance testing process.
Today, CPU centric-benchmarks (e.g., SPEC and RPE2 [33]) are often used to map and compare CPU utilizations between different configurations. However, such an approach provides no support for practitioners to understand the rationale for such regressions and cannot be used to compare other performance counters than CPU (e.g., I/O, threading and memory-related performance counters). Such counters are often more important for enterprise applications than CPU utilization, which is more relevant for high-performance computing applications.
State of Research. Unlike functional regression testing, which has been studied extensively [5], [18], [30], performance regression testing has received very little research interest due to the lack of infrastructure and availability of data. Existing research can be divided into two classes depending on whether the approaches analyze execution logs or performance counters. We limit our discussion to performance counters and refer to our previous work [34] for a discussion of related works on execution logs. Approaches for analyzing or monitoring performance counters can be categorized as either supervised or unsupervised, depending on whether or not the performance counter data is labeled with the test outcome.
Supervised Approaches: Cohen et al. apply supervised machine learning techniques to train classifiers on performance data that is labeled with violations of Service Level Objectives (SLO), as defined by stakeholders in the system’s requirements [13], [14]. Bodik et al. improve Cohen’s work by using logistic regression [8], whereas Zhang et al. extend Cohen’s work to maintain an ensemble of classifiers [37]. When an SLO violation is detected, the most relevant classifier is selected from the ensemble to report the counters that correlate with the particular SLO violation. In [26], Malik et al. presented a wrapper-based supervised approach, which detects performance problems.
These supervised techniques require counters to explicitly exceed certain thresholds (e.g., SLOs). In practice, mapping threshold values to a concrete set of counters is not straightforward. Furthermore, threshold violations represent the worst case scenarios of performance regression. By the time such violations surface, the actual cause of the violations is hard to track back, significantly delaying the next software release.
Unsupervised Approaches: Jiang et al. use pair-wise correlation to detect performance problems [21]. Yilmaz et al. use experimental design techniques to minimize the number of configurations that a system needs to be tested on [36]. Malik et al. use Principal Component Analysis to recover correlations among performance counters in order to identify the subsystems causing performance deviations in a new performance test run [25]. Similarly, Jiang et al. identify correlating counters with Normalized Mutual Information [22]. Bulej et al. cluster the response time counters with the k-means clustering algorithm such that the performance between two test runs is detected by comparing their clusters [12]. Breitgand et al. use statistical modeling to flag performance problems (by flagging when counters exceed manually set thresholds), however their approach does not provide support to investigate the rationale for such problems [10]. In [17], we presented an approach that uses association rule mining to automatically flag counters that expose symptoms of performance regressions.
The above studies use some type of supervised or unsupervised model to automatically detect fine-grained performance degradations in large test data sets. However, they all assume that tests are run on the same hardware and software environ-
ments. A single model derived from prior test runs, conducted with multiple environment configurations, will only be able to capture the correlations that are strong enough to persist across all test runs, and ignore other, weaker, but possibly important correlations. The inability to identify which prior test runs are the most related to a new run risks producing incorrect conclusions about the performance of the system under test.
We explore ensemble-based techniques as a way to deal with heterogeneous environments. We enhance our state-of-the-art association rule mining approach \[17\] with ensemble based techniques and compare the performance of the resulting model to that of the original model on two major open source systems and one large enterprise system. The next section discusses the intuition and overview of our techniques, whereas \[Section IV\] presents our case study results.
III. OUR APPROACH
Ensemble-based models consist of multiple individual classification models. To classify a new instance, the classifications of all the sub-models are combined through voting (bagging \[9\]) or more elaborate composition (stacking \[16\]). The key insight here is that each individual model specializes in one particular area, with the global ensemble model taking into account the decision of all areas.
In the context of performance regression, the ensemble model for a particular release consists of individual models, one for each passed prior test run. Such models summarize for a given test run, and hence for its particular test environment, the major patterns of performance counter values. When a new test run’s performance counters are available, they are matched to the patterns in the individual models to determine deviations between the new test run and the prior test runs. The final decision about whether the new test run has passed or failed then needs to aggregate (in decreasing order of importance) deviations with prior tests having a test environment: identical/similar/different from the new test run.
A naive bagging approach would blindly pick the counters deviating in the majority of the individual models, without distinguishing explicitly between the three groups of models. If, coincidentally, the majority consists of models from groups 1 and 2, the approach will work well. If group 3 dominates, the ensemble model will likely yield the wrong result, unless the new test run violates common behaviour across all test runs. To make the analysis more clever, we also experimented with a stacking approach that gives models of groups 1 and 2 a higher weight than those in group 3. Hence, if a new test run deviates from prior runs with an identical or similar test environment, the major patterns of performance counter values.
A naive bagging approach would blindly pick the counters deviating in the majority of the individual models, without distinguishing explicitly between the three groups of models. If, coincidentally, the majority consists of models from groups 1 and 2, the approach will work well. If group 3 dominates, the ensemble model will likely yield the wrong result, unless the new test run violates common behaviour across all test runs. To make the analysis more clever, we also experimented with a stacking approach that gives models of groups 1 and 2 a higher weight than those in group 3. Hence, if a new test run deviates from prior runs with an identical or similar test environment, those deviations will more likely determine the fate of the new test run.
To evaluate the performance of these two ensemble techniques, we integrated them into the state-of-the-art approach for performance regression analysis that we proposed before \[17\]. Our resulting ensemble approach has 5 phases, as shown in Figure 1. We now discuss each phase of our approach through a running example with four prior tests \(T_1, T_2, T_3, T_4\) and one new test, \(T_5\).
**Phase 1 – Counter Normalization.** First, we must eliminate irregularities in the collected performance data. Irregularities can come from the following sources: (1) \textit{Clock Skew:} Counters captured by different machines tend to have slightly different timestamps due to the large number of machines. (2) \textit{Delay:} There may be a delay in the start or end of counter collection between the machines.
To overcome these irregularities, we extract the portion of counter data that corresponds to the expected duration of a test. Then, we divide the time into equal intervals (e.g., every five seconds). Each interval is represented by a vector containing the medians of all counters in that interval. The size of the interval can be adjusted by the analysts depending on how often the counters are captured. Less interesting execution phases could be aggregated into longer intervals.
**Phase 2 – Counter Discretization.** Our association mining technique (see phase 3) requires categorical data. Therefore, we must discretize the continuous performance counters. We choose to use the Equal Width interval binning (EW) algorithm for our discretization task, because it is relatively easy to implement and performs well in conjunction with machine learning techniques \[15\]. The EW algorithm first sorts the observed values of a counter, then divides the value range into \(k\) equally sized bins. Each counter value is discretized to the bin to which it belongs. Note that EW typically does not lead to uniformly distributed bins.
The width of each bin and the number of bins are determined by \(\text{bin width} = \frac{x_{\text{max}} - x_{\text{min}}}{k} \times \log(u)\), where \(k = \max(1, 2 \times \log(u))\) and \(u\) is the number of unique values of a counter. To determine the bin width, we apply the EW algorithm on all values of a particular counter observed in the entire performance testing repository. For example, the tests in the training set \(T_1, T_2, T_3, T_4\) are first combined to form an aggregated dataset \(T_A\) to determine the bin boundaries.
**Phase 3 – Association Rule Derivation and Violation Detection.** We apply association rule mining to extract a set of association rules for each historical test run in the training set. Each rule set is a model describing the performance behaviour of a prior test. An association rule consists of a premise and a consequent. The rule states that if the premise holds in a new test run, then the consequent will also hold with high probability. Figure 2 shows an example of an association rule that states “if both the arrival rate and the CPU utilization are observed to be at the medium level, throughput should also be at the medium level.”
### Table 1: Counters flagged in \(T_5\) by multiple rule sets.
<table>
<thead>
<tr>
<th>Models</th>
<th>Counters of (T_5) flagged as violation</th>
</tr>
</thead>
<tbody>
<tr>
<td>(R_1)</td>
<td>CPU utilization, throughput</td>
</tr>
<tr>
<td>(R_2)</td>
<td>Memory utilization, throughput</td>
</tr>
<tr>
<td>(R_3)</td>
<td>Memory utilization, throughput</td>
</tr>
<tr>
<td>(R_4)</td>
<td># Database transactions/s</td>
</tr>
</tbody>
</table>
**Fig. 2: Example association rule.**
The probability with which an association rule holds can be characterized by its support and confidence measures. **Support** measures the ratio of times the rule holds, i.e., the counters in the premise and consequent are observed together with the specified values. Low support means that the association rule may have been found simply due to chance. **Confidence** measures the probability that the rule’s premise leads to the consequent, i.e., how often the consequent holds when the premise does. For example, if the rule in Figure 2 has a confidence value close to 1, it means that when arrival rate and CPU utilization are both medium, one will almost always observe medium throughput.
To improve the quality of the association rule set, candidate rules that do not reach the minimum support (0.3) and confidence (0.9) thresholds are pruned. These values are the default values defined in the data mining package that we use [11] (yielding good results in our case studies). Lower thresholds will accept more rules, making it harder for new test runs to satisfy all the rules (higher chance for detecting deviations). Higher thresholds yield less rules and make the rule set easier to match with. Different projects can experiment with different thresholds for optimal results.
We use the confidence of a rule on a new test run’s counter values as an indicator of performance regressions. For example, in Figure 2, a drop in confidence from 0.9 to 0.2 on the new test run’s data would indicate that medium arrival rate and CPU utilization no longer associate with medium throughput in most of the cases. As a result, the throughput counter should be investigated. We measure such confidence changes using the cosine distance between two test runs:
$$\Delta_{\text{confidence}} = 1 - \cosine\_distance(\vec{V}_{\text{history}}, \vec{V}_{\text{new}}),$$
where
$$\vec{V}_{\text{history}} = (\text{Conf}_{\text{history}}, 1 - \text{Conf}_{\text{history}}), \quad \vec{V}_{\text{new}} = (\text{Conf}_{\text{new}}, 1 - \text{Conf}_{\text{new}}),$$
where $\vec{V}_{\text{history}}$ and $\vec{V}_{\text{new}}$ are the vector form of the confidence values $\text{Conf}_{\text{history}}$ and $\text{Conf}_{\text{new}}$ in the historical dataset and the new test run, respectively. Since cosine distance measures the angle between two vectors, we had to convert the scalar confidence values into vector form.
The confidence change values $\Delta_{\text{confidence}}$ range between 0 and 1. A value of 1 means that the confidence of a rule is completely different in the new test run, i.e., the premise holds, but the consequent does not. If the confidence change $\Delta_{\text{confidence}}$ for a rule is higher than a specified threshold, we can conclude that the behaviour described by the rule has changed significantly in the new test run. The counters appearing in the rule’s consequent can then be flagged as a regression. The threshold for confidence change again is customizable by the performance analyst to control the number of flagged counters, based on the available analysis time.
Each model contains performance characteristics that are common across prior test runs as well as behaviours that are specific to the test run and environment used as training data. Table I shows an example of counters flagged in $T_5$ as performance regressions by models $R_1$ to $R_4$. Counters that are flagged by only a few models may be due to differences in environments or other specifics of a particular test run.
**Phase 4 – Combining Violations with Ensemble Algorithms.** We now combine the counters flagged by each individual model in Phase 3 using one of the following two ensemble methods: bagging and stacking. We briefly review these algorithms and present our application of them.
**Bagging** is one of the earliest and simplest ensemble-based algorithms [9], yet in some cases it has been shown to outperform more complex approaches [6]. In bagging, the prediction of each model is combined by a simple majority vote to form the final prediction. Hence, in order for a performance counter to be flagged in our performance report, we require the counter to be flagged by at least half of the models. For example, Table II shows the number of times a counter is flagged for $T_5$ by the 4 models ($R_1$, $R_2$, $R_3$, $R_4$) in Table I. Bagging will report both throughput and memory utilization as performance regressions as they are flagged by at least 2 models.
**Stacking** is a more general ensemble technique that can use any selection process to form a final set of predictions. A simple and effective way to combine the results of individual rule sets is to create a Breiman’s stacked regression [13], which uses
### Table II: # of models $R_1$ to $R_4$ that flagged each counter.
<table>
<thead>
<tr>
<th>Counters flagged as violation</th>
<th># of times flagged</th>
</tr>
</thead>
<tbody>
<tr>
<td>Throughput</td>
<td>3</td>
</tr>
<tr>
<td>Memory utilization</td>
<td>2</td>
</tr>
<tr>
<td>CPU utilization</td>
<td>1</td>
</tr>
<tr>
<td>Database transactions / second</td>
<td>1</td>
</tr>
</tbody>
</table>
### Table III: Test configurations for stacking.
<table>
<thead>
<tr>
<th>Performance Test Repository</th>
<th>New Test</th>
</tr>
</thead>
<tbody>
<tr>
<td>$T_1$</td>
<td>$T_2$</td>
</tr>
<tr>
<td>CPU</td>
<td>2 GHz 2 cores</td>
</tr>
<tr>
<td>Memory</td>
<td>2 GB</td>
</tr>
<tr>
<td>Database Version</td>
<td>2</td>
</tr>
<tr>
<td>Architecture</td>
<td>32 bit</td>
</tr>
</tbody>
</table>
Fig. 1: Overview of our ensemble-based approach.
a linear stacking function \( s \) of the form:
\[
s(\vec{x}) = \sum_i w_i R_i(\vec{x}),
\]
where \( w_i \in [0, 1] \) represents the weight of the violations reported by rule set \( R_i \) (generated from the \( i \)th test run in the repository), and \( \vec{x} \) represents the vector of performance counter values of the new test run. \( R_i(\vec{x}) \) yields a violation vector of 1s and 0s, where a 1 corresponds to a particular counter showing a performance regression in the new test run based on \( R_i \). Hence, \( s(\vec{x}) \) basically is a weighted count of the number of times each counter is flagged across all prior test runs. Bagging would consider all weights \( w_i \) to be 1.
Although performance analysts may specify custom weights best suited for their test repositories, we define the weight of each \( R_i \) model based on the similarity between the environments used for the earlier test runs and the new test run. A prior test run with a very similar environment to the new test run should receive a larger weight. To compare the environments between two test runs, we generate a similarity vector of 1s and 0s to indicate if two test runs share common components in their environment. Which components exactly constitute the environment depends on the concrete software system or deployment, and the degree of detail in which the environment is specified can be chosen as well.
Since it is difficult to determine the relations between the system performance and individual components of the environment, we prefer a simple binary approach to compare environment configurations. For example, Table III shows three environments for \( T_1, T_2, \) and \( T_3 \) (the components shown here are just examples). The similarity vectors for the \( (T_1, T_3) \) pair would be \( (1, 1, 1, 0) \), because both \( T_1 \) and \( T_3 \) share the same versions of CPU, memory and database, and differ only in the operating system version. Likewise, for the \( (T_2, T_3) \) pair, the vector would be \( (1, 0, 0, 1) \). More elaborate similarity vectors could be used to better differentiate between critical and trivial differences in environments, for example tripling the total amount of memory versus adding a small hard disk.
To measure the degree of similarity between the new and a past test run, we use the cartesian length of the similarity vector (\( \sqrt{N} \) with \( N \) the number of 1s in the vector). For example, the lengths of \( (T_1, T_3) \) and \( (T_2, T_3) \) equal 1.7 and 1.4 respectively. The longer the length of a similarity vector, the higher the similarity between prior and new test runs. We can then calculate the weights as \( w_i = \frac{l_j}{\sum_j l_j} \), with \( l_j \) the length of the similarity vector of the \( j \)-th model. As such, all weights sum up to 1. For example, the weight \( w_1 \) for \( T_1 \) is calculated as follows:
\[
w_1 = \frac{[(T_1, T_3)]}{[(T_1, T_3)] + [(T_2, T_3)]} = \frac{1.7}{1.7 + 1.4} = 0.55.
\]
The weight \( w_i \) essentially is a value that describes the relative importance of a model for analyzing a specific, new test run, with the idea that tests having identical or similar environments as the new test run have the largest weights (hence weights need to be re-calculated for each new test run). As such, the weights can be used to produce the set of counters that most commonly violate the expected behaviour from prior test runs. Since the \( w_i \) sum up to 1 and the \( R_i(x_j) \) are either 0 or 1, each element of the \( s(\vec{x}) \) vector will have a value between 0 and 1. Performance counters with \( s(\vec{x}) \) values greater than 0.5 will be included in the resulting set of counters as performance regressions, since they are reported by most of the highly weighted models.
**Phase 5 – Report Generation.** To help performance analysts diagnose performance problems, our approach generates a report like Figure 3. The reports contain important information for developers, such as a list of problematic counters, correlated counters (Figure 3 top), as well as an overview of the periods in which the performance regressions occur (Figure 3 bottom). Time intervals coloured in purple indicate periods during which metrics are part of a violated rule. Performance analysts can further investigate the periods in which the performance regressions are detected (Figure 3 bottom) by clicking on the “Graph” column.
To generate the report, the flagged counters are first ranked by either the number of models flagging the counters (bagging) or the aggregated weights \( s(\vec{x}) \) (stacking). If two counters are ranked the same, they will be further sorted by the level of severity as defined in
\[
\text{Severity} = \frac{\# \text{ time intervals with flagged counter}}{\text{total \# time intervals}}.
\]
Severity represents the fraction of time intervals (cf. phase 1) that contain the violating counter occurrences in the new test. Severity ranges between 0 and 1. If there are only a few intervals where the counter is observed to be problematic, the severity will be close to 0. On the other hand, if the counters are violated many times, severity will have a value close to 1. Each counter is linked to the list of association rules that the counter violates (Figure 3). The rules help the analysts in investigating the performance regressions.
**IV. CASE STUDY**
We conducted a series of case studies on two major open source e-commerce applications (Dell DVD Store and JPet-Store) and a large enterprise system to compare the two ensemble-based techniques to our state-of-the-art association rule mining model [17]. The open source case studies serve two purposes: 1) they provide a replication package for others to replicate our work as we cannot publicly release the industrial data, and 2) they enable us to study our approach in a controlled setting with known injected problems, similar to [36].
In particular, in the Dell DVD Store and JPetStore case studies, we explore whether our ensemble approaches can handle tests with different hardware (Dell DVD Store) and software (JPetStore) environments, respectively. In our industrial case study, we examine whether our ensemble approaches can detect performance regressions in performance tests conducted both in different hardware and software environments, based on a large number of long-running tests.
For the two open source systems, we manually injected faults into our case studies. For this, we followed the popular “Siemens-Programs” approach of seeding bugs [20], which are based on common performance problems. Since we know which faults were injected, we can assess our approach using both precision and recall [21]:
\[
\text{Precision} = \begin{cases}
1 - \frac{m_{\text{false}}}{m_{\text{total}}} & \text{if } m_{\text{total}} > 0 \\
1 & \text{if } m_{\text{total}} = 0
\end{cases}
\]
\[
\text{Recall} = \begin{cases}
\frac{m_{\text{total}} - m_{\text{false}}}{m_{\text{expected}}} & \text{if } m_{\text{expected}} > 0 \\
1 & \text{if } m_{\text{expected}} = 0
\end{cases}
\]
where \( m_{\text{false}} \) is the number of counters that are incorrectly flagged, \( m_{\text{total}} \) is the total number of counters flagged, and \( m_{\text{expected}} \) is the number of counters expected to show performance regressions (including counters that are a side-effect of the injected fault). A high precision means that few of the flagged performance regressions are false alarms. A high recall means that our approach can discover most of the performance regressions in a new test.
For the large enterprise system, we use the existing performance counters collected by the company’s performance analysts for historical test runs as the input of our approach. We compare the results of our approach against the analysts’ reports filed at the time. Since an important motivator of our work is the tendency of analysts to miss problems due to the vast amount of data produced by large industrial systems, we do not blindly use the analysts’ reports as the “gold standard” for precision and recall. Instead, we carefully re-verified the existing test reports with the analysts, who noted any missed problems. For example, using this process, we found 13 problematic counters in the analysis of the first three tests. The differences with the original report of the analysts strengthens our claim that manual analysis practices are not sufficient.
Although we do not know the real number of performance problems in the enterprise system, we calculate the relative recall in terms of the union of true performance regressions identified by the three approaches (original approach and two ensemble versions).
Finally, we use the F-measure to rank the accuracy of the three approaches in all three case studies. The F-measure is the harmonic mean of precision and recall, and outputs a value between 0 and 1. A high F-measure value means that a technique has high precision and high recall. Table IV summarizes the performance of all three approaches in the case studies. Bold entries highlight the best technique for a particular test run.
For each case study, we give a description of the system, methods used for data collection, and analysis of each approach. The replication package for the open source systems can be found online [32].
A. Dell DVD Store
The Dell DVD Store (DS2) application [16] is an open source implementation of an online movie rental website. DS2 consists of a back-end database component, a web application component and load drivers (simulating user traffic). In this case study, we have chosen to use DS2’s JSP distribution with a MySQL database and a Tomcat container.
Data collection: We ran five one-hour performance test runs (\( D_1 \) to \( D_5 \)) with the same standard workload. We varied the CPU and memory capacity of the machine that hosts Tomcat and MySQL to simulate different hardware environments. Table V summarizes the hardware setups and expected problematic counters for this case study. Test run \( D_1 \) represents a test run in which the hardware is running at its full capacity. In test run \( D_2 \), we throttle the CPU to 50% of the full capacity to emulate a slower machine. In test run \( D_3 \), we reduce the memory from 3.5GB to about 1.5GB. Test runs \( D_1, D_2, \) and \( D_3 \) will be used as the test repository for the three approaches.
Test run \( D_4 \) is a replication of \( D_1 \) and is used to show that our approach produces few false positives. In \( D_5 \), we use an injected fault from [24] to cause a performance regression. The injected excessive-database-queries bug simulates the “n+1” pattern [19]. Prior to each case study, we manually derived a list of counters that we expect to exhibit performance regressions because of the injected bug. We use these counters to calculate the recall of our approach.
Analysis of Test Run \( D_4 \): Since \( D_4 \) is run without any injected bugs, ideally, no counter should be flagged. We use \( D_4 \) as a sanity check for the ensemble techniques.
When using our original approach, 4 counters (database CPU utilization, # database I/O writes/s, # orders/minute and the response time counter) were flagged. Upon investigation, we found that the rules of test run \( D_2 \) flagged the first 3 counters: because less processing power was available in \( D_2 \), each request would take longer to complete, resulting in an increased CPU utilization. Also, less requests could be completed, leading to a decrease in # database I/O writes/s and # orders/minute. The violations of the \( D_2 \) model seem to indicate that the behaviour of \( D_1 \) (and hence \( D_1 \)) differs the most from that of \( D_2 \). Since no actual fault was injected into test run \( D_4 \), we concluded that the four flagged counters were
false positives, leading to a precision of 0. Because we do not expect any counter to be flagged, recall is equal to 1, as defined by [Equation 1]. The F-measure of our original approach is 0. Note that the new test run (D₃) actually performs better than the old test runs, i.e., the rules did not flag a regression, but rather a speed-up. Heuristics could be added to our approach to only flag true regressions.
No counter was flagged by either the bagging or stacking approach. This can be explained by the fact that separate models are learned from test runs D₁, D₂, and D₃. In order for a counter to be considered problematic, the counter must be flagged by at least two models (to achieve an aggregated weight of 0.5). Even though three counters (database CPU utilization, database I/O writes, and # orders/minute) were flagged by the model generated from test run D₂, none of these counters could be confirmed by the models generated from test runs D₁ or D₃. The precision, recall and F-measure of our ensemble-based approaches are 1.
**Analysis of Test Run D₅:** In test run D₅, we injected a database-related bug that affects the product browsing logic of the system. Every time a customer performs a search on the website, the same query will be repeated numerous times, causing extra workload for the backend database (MySQL) and application server (Tomcat).
**Test Run D₅ as Training Data:** In this scenario (D₅ in Table IV), we want to evaluate the performance of our ensemble techniques in cases where the new test run and the prior test run share exactly the same environment.
All three approaches flagged two database counters (# disk reads/s and CPU utilization), one Tomcat server related counter (# private bytes), and one application level counter (response time). Upon inspection, we found that the model generated from test run D₃ also flagged Tomcat’s # threads counter. However, in the model generated from test run D₂, the rules that contained # threads as the consequent had premises that were never satisfied in test run D₃. As a result, even though the # threads counter behaved differently in test runs D₂ and D₅, the # threads counter was only flagged by the D₃ model. Since 4 out of 7 counters were flagged, our bagging and stacking approaches achieved a precision of 1 and a recall of 0.57. The F-measure of both ensemble-based approaches is 0.73.
**B. JPetStore**
**JBpetStore** [7] is a re-implementation of Oracle’s original J2EE Pet Store. Since JBpetStore does not ship with a load generator, we use an external web testing tool to record and replay a typical scenario of a user browsing and purchasing items on the site [27].
**Data collection:** In this case study, we conducted three one-hour performance test runs (J₁, J₂, and J₃), all of which share the same hardware environments and workload. J₂ and J₃ use an older version of MySQL (ver. 5.0.1) than test run J₁ (ver. 5.1.45). J₁ and J₂ are used as training data, whereas J₃ is injected with an environment bug in which all caching capacities of MySQL are turned off. Such a bug simulates a typical operator error [29]. Table VI summarizes the environments used in the three test runs and the 6 counters expected to show performance regressions in J₃.
**Analysis of Test Run J₃:** Our original approach detected a decrease in memory usage (# private bytes), and an increase in CPU utilization and # threads in the database. These observations align with the injected fault, as caching is turned off in the database, less (caching) memory is used during the execution of the test. Because of the extra workload of accessing the disk, the database in turn must create more threads to handle the otherwise unchanged workload, increasing CPU
<table>
<thead>
<tr>
<th>Run</th>
<th>Hardware Setup</th>
<th>Fault Description</th>
<th>Expected Problematic Metrics</th>
</tr>
</thead>
<tbody>
<tr>
<td>D₁</td>
<td>CPU = 100%, Memory = 3.5 GB</td>
<td>No fault</td>
<td>No problem should be observed.</td>
</tr>
<tr>
<td>D₂</td>
<td>CPU = 50%, Memory = 3.5 GB</td>
<td>No fault</td>
<td>No problem should be observed.</td>
</tr>
<tr>
<td>D₃</td>
<td>CPU = 100%, Memory = 1.5 GB</td>
<td>No fault</td>
<td>No problem should be observed.</td>
</tr>
<tr>
<td>D₄</td>
<td>Same as Test D₁</td>
<td>No fault</td>
<td>No problem should be observed.</td>
</tr>
<tr>
<td>D₅</td>
<td>Same as Test D₁</td>
<td>Busy loop in browsing logic</td>
<td>1. Increase in CPU utilization, and # disk reads/s in database. 2. Increase in # threads, # private bytes, and CPU util. in Tomcat. 3. Increase in response time and # requests/min in application.</td>
</tr>
</tbody>
</table>
**TABLE V: Summary of test setup for DS2.**
<table>
<thead>
<tr>
<th>Run</th>
<th>Hardware Setup</th>
<th>Fault Description</th>
<th>Expected Problematic Metrics</th>
</tr>
</thead>
<tbody>
<tr>
<td>J₁</td>
<td>MySQL 5.1.45</td>
<td>No fault</td>
<td>No problem should be observed</td>
</tr>
<tr>
<td>J₂</td>
<td>MySQL 5.0.1</td>
<td>No fault</td>
<td>No problem should be observed</td>
</tr>
<tr>
<td>J₃</td>
<td>MySQL 5.0.1</td>
<td>Cache disabled</td>
<td>Increase of database CPU utilization, # threads, # context switches, # private bytes, and # disk reads and writes in bytes/s.</td>
</tr>
</tbody>
</table>
**TABLE VI: Summary of test setup for JPetStore.**
<table>
<thead>
<tr>
<th>Run</th>
<th>Hardware Setup</th>
<th>Fault Description</th>
<th>Expected Problematic Metrics</th>
</tr>
</thead>
<tbody>
<tr>
<td>J₁</td>
<td>MySQL 5.1.45</td>
<td>No fault</td>
<td>No problem should be observed</td>
</tr>
<tr>
<td>J₂</td>
<td>MySQL 5.0.1</td>
<td>No fault</td>
<td>No problem should be observed</td>
</tr>
<tr>
<td>J₃</td>
<td>MySQL 5.0.1</td>
<td>Cache disabled</td>
<td>Increase of database CPU utilization, # threads, # context switches, # private bytes, and # disk reads and writes in bytes/s.</td>
</tr>
</tbody>
</table>
utilization in the process. Our original approach has a precision of 1 and recall of 0.5 (3/6). The F-measure of our original approach is 0.66.
Our ensemble approaches flagged the following three counters: # private bytes, # IO reads/s, and # threads in the database. Hence, our ensemble approaches achieve the same performance as our original approach.
C. A Large Enterprise System
Our third case study is conducted on a large scale distributed enterprise system from our industrial partner. This system is designed to support millions of concurrent requests across several hundreds of machines. For each build of the software, a series of performance regression tests are done to uncover performance regressions.
Data collection: In this case study, we selected thirteen comprehensive (i.e., executing the core functionalities) 8-hour performance regression test runs from the organization’s performance regression test repository. Most of these tests were run in labs with varying hardware specifications, and were conducted for a maintenance release of the system. For each run, over 2,000 counters were collected.
Out of the pool of 13 test runs, 10 test runs historically had received a pass status from the performance analysts (independent of our case study). We use those runs to derive association rule models. We evaluated the performance of the 3 newest test runs ($E_1$, $E_2$, and $E_3$) in the pool and compared our findings with the performance analysts’ assessment at the time (Table VII).
Analysis of Test Run $E_1$: By analyzing the counters flagged by the union of the three approaches for test run $E_1$, we found that 13 counters (out of 2,000!) show true performance regressions. These 13 counters will be used to calculate the relative recall of our approaches for $E_1$.
Our original approach flagged 6 counters, including 2 throughput counters, 2 arrival rate counters, the # private bytes counter of the server process and the # database transactions/s counter. The rules that flagged the counters imply that all throughput and arrival rate counters should be the same under normal circumstances. However, upon investigation, we found that for $E_1$ half of the arrival rates and throughput counters are high while the other half is low, suggesting that the performance regression might be due to a mismatch in the load created by the load generators of Test $E_1$. Our original approach achieves a precision of 1, a recall of 0.46 (6/13) and an F-measure of 0.63.
Our bagging approach flagged 18 counters. The counters flagged included the 4 throughput and arrival rate counters that were flagged by our original approach. Most of the flagged counters are side-effects of the mismatch of the arrival rate counters. For example, the CPU utilization of the system decreased because fewer requests were made due to a drop in one of the arrival rate counters. We verified our findings with a performance analyst, and found that 5 flagged counters were false positives, bringing the precision and relative recall of our bagging approach to 0.72 (13/18) and 1, respectively. The F-measure of our bagging technique is 0.84.
Our stacking approach flagged 13 counters, including the ones flagged by our original approach. Out of the 13 counters flagged, the performance analyst and we identified 2 false positives, bringing both the precision and relative recall of our stacking approach to 0.85 (11 out 13). The F-measure of our stacking approach is 0.92.
Analysis of Test Run $E_2$: Our three approaches detected 15 unique counters with performance regressions in test run $E_2$. These 15 counters will be used to evaluate the relative recall of each of our approaches.
Our original approach flagged 7 counters in total, 1 of which was a false positive. The correct performance regressions flagged included 2 arrival rate and 2 job queue counters, and the # private bytes and # virtual bytes counters of the application process. The resulting precision, recall and F-measure are 0.86, 0.4, and 0.55, respectively.
Our bagging approach flagged 20 counters, 5 of which were false positives. The remaining 15 counters included the 7 counters that were flagged by our original approach. The additional counters reported by our bagging approach were mainly the side-effects of the regression detected in the arrival rate counters. For example, as one of the load generators pushed a higher than the expected load, the extra requests caused the system to read from the disk more often, leading to an increase in the # disk reads/s. The results of these extra requests were written to the disk, causing an increase in the # disk writes/s. Although these side-effects are the result of the higher testing load, they can help analysts investigate the ripple effect of the fault. Hence, side-effects should be considered as true positives. The precision and relative recall of our bagging approach are 0.75 (15/20) and 1, respectively. The F-measure of our original approach is 0.86.
Our stacking approach flagged 14 counters, 1 of which was a false positive. All counters flagged by our original approach were also flagged by our stacking approach. The precision and relative recall of our stacking approach are 0.93 (13/14) and 0.87 (13/15). The F-measure for our stacking approach is 0.90.
Analysis of Test Run $E_3$: There are no true positives that were detected by any of our three approaches.
Our original approach did not flag any rule violation for this test run. Upon inspection of the historical values for the counters reported by the performance analyst, we noticed that the increase of # database transactions/s observed in test run $E_3$ actually fell within the counter’s historical value range. Upon discussing with the Performance Engineering team, we concluded that the increase did not represent a performance
problem, contradictory to the results of the team’s earlier (manual) analysis. In this test run, our original approach of using a historical dataset of prior tests is resistant to fluctuations of counter values. Since no counter was flagged, the precision, relative recall and the F-measure of our original approach are 1.
Our bagging approach flagged 8 counters, all of which were false positives. Two counters flagged by our bagging approach indicated that one of the load generators output service requests at a higher rate (11%) than the other one. The extra service requests led to a slight increase in the # disk reads/s counter. Upon investigation, we do not believe that these two counters represent significant performance regressions. Hence, these counters are considered as false positives, leading to a precision and relative recall of our bagging approach of 0 and 1. The F-measure of our bagging approach is 0.
Since our stacking approach did not flag any counter, the precision and the relative recall of our stacking approach are 1. The F-measure of our stacking approach is 1.
V. DISCUSSION AND LIMITATIONS
As can be seen in Table IV, our stacking approach improves over the performance of our original approach and performs slightly better than our bagging approach. The precision of the three approaches is similar (the averages are a bit skewed because of the zero outliers of our original approach and bagging). Recall-wise, bagging performs the best, since it aggregates the results of individual models by voting, without incorporating the environment information of performance test runs. This recall goes at the expense of a slightly lower precision. Stacking has the same recall values, except for test runs $E_1$ and $E_2$. Our original approach behaves sub-par in significantly heterogeneous environments, i.e., runs $D_{2}^{5}$, $E_1$ and $E_2$. Overall, the combination of high precision and recall makes stacking the best approach (highest F-values), followed by bagging, then by our original approach.
Feedback from Practitioners. Over the past 4 years, the presented approach has been used on a daily basis for the performance analysis of a very large scale enterprise system. Analysts (other than the authors) liked that the ensemble performance analysis of a very large scale enterprise system presented approach has been used on a daily basis for the feedback from practitioners.
Finally, the analysts felt that some type of human intervention will always be needed. In particular, as a system evolves its performance signature might change considerably and hence the analysts should be given the option to remove old tests from the repository. While an ensemble of models can reduce the impact of outdated performance behaviours by spreading the weights across models, the performance of our approach will suffer if we allow the size of the ensemble to grow unbounded. We have developed a sliding window approach that discards tests when they no longer reflect the current system performance. An analyst can also manually remove old tests, if he felt that a test is not representative.
Limitations. We evaluated our work on three systems. These numbers seem low and ideally we would like to perform much larger experiments, yet there are a number of factors to take into account. First, realistic performance tests are complex to design and execute, as they require large and distributed labs with multiple machines, each hosting a different component, and must be run for extended periods of time. For that reason, we analyzed not only open source systems, but also an existing industrial large-scale system. Second, it is hard to get access to performance counter data for large software systems. In that sense, our data is rather unique. Third, we had to compare and discuss the enterprise results with the performance engineering team, as well as explore trends and patterns in the 2,000 collected counters. Fourth, seeding realistic bugs in the open source systems is time-consuming since we chose to implement both programmatic and configuration faults to simulate common mistakes observed in industry [21], [24].
We have made available a replication package to allow other researchers to build and expand on our work [32]. For example, given the many choices for thresholds and algorithms (e.g., similarity of environments or weight of a model), more research is needed to explore the configuration state space. Furthermore, if the behaviour of a new test is radically different from prior test runs, our ensemble approaches will not be accurate. Hence, in the future, other ways to automatically pick the most suitable ensemble of test models from a test repository should be investigated.
VI. CONCLUSION
The heterogeneity of the test environments has limited the widespread adoption in practice of performance regression analysis techniques. In this paper, we propose to use ensemble models (bagging and stacking) to compose individual models of the expected behaviour of prior test runs. The composition tries to take into account those prior test runs with the most closely related test environment. Case studies on two major open source systems and one large enterprise system show that (1) the ensemble techniques outperform our state-of-the-art environment-agnostic approach, and that (2) stacking consistently performs better than bagging in terms of precision and F-measure. Feedback from practitioners has been very positive.
ACKNOWLEDGMENTS
We are grateful to BlackBerry for providing access to the used enterprise system. The findings and opinions expressed in this paper are those of the authors and do not necessarily represent or reflect those of BlackBerry and/or its subsidiaries and affiliates. Moreover, our results do not in any way reflect the quality of BlackBerry’s products.
REFERENCES
[16] Dell dvd store. [online] Available at: http://linux.dell.com/dvdstore/
[27] Neoload. [online] Available at: http://www.neotys.com
|
{"Source-Url": "http://sail.cs.queensu.ca/Downloads/ICSE2015_AnIndustrialCaseStudyOnTheAutomatedDetectionOfPerformanceRegressionsInHeterogeneousEnvironments.pdf", "len_cl100k_base": 12010, "olmocr-version": "0.1.49", "pdf-total-pages": 10, "total-fallback-pages": 0, "total-input-tokens": 35249, "total-output-tokens": 14129, "length": "2e13", "weborganizer": {"__label__adult": 0.0003361701965332031, "__label__art_design": 0.0005764961242675781, "__label__crime_law": 0.00030159950256347656, "__label__education_jobs": 0.0014448165893554688, "__label__entertainment": 0.00012493133544921875, "__label__fashion_beauty": 0.0001690387725830078, "__label__finance_business": 0.0005016326904296875, "__label__food_dining": 0.0002918243408203125, "__label__games": 0.0009613037109375, "__label__hardware": 0.00145721435546875, "__label__health": 0.00035762786865234375, "__label__history": 0.0003688335418701172, "__label__home_hobbies": 0.00013315677642822266, "__label__industrial": 0.0005626678466796875, "__label__literature": 0.00045013427734375, "__label__politics": 0.0001914501190185547, "__label__religion": 0.0003497600555419922, "__label__science_tech": 0.07586669921875, "__label__social_life": 0.0001049041748046875, "__label__software": 0.0191802978515625, "__label__software_dev": 0.8955078125, "__label__sports_fitness": 0.0002343654632568359, "__label__transportation": 0.0004405975341796875, "__label__travel": 0.0001748800277709961}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61036, 0.01752]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61036, 0.20129]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61036, 0.90281]], "google_gemma-3-12b-it_contains_pii": [[0, 5962, false], [5962, 12591, null], [12591, 19672, null], [19672, 25381, null], [25381, 31339, null], [31339, 37260, null], [37260, 42716, null], [42716, 48572, null], [48572, 53315, null], [53315, 61036, null]], "google_gemma-3-12b-it_is_public_document": [[0, 5962, true], [5962, 12591, null], [12591, 19672, null], [19672, 25381, null], [25381, 31339, null], [31339, 37260, null], [37260, 42716, null], [42716, 48572, null], [48572, 53315, null], [53315, 61036, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61036, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61036, null]], "pdf_page_numbers": [[0, 5962, 1], [5962, 12591, 2], [12591, 19672, 3], [19672, 25381, 4], [25381, 31339, 5], [31339, 37260, 6], [37260, 42716, 7], [42716, 48572, 8], [48572, 53315, 9], [53315, 61036, 10]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61036, 0.16822]]}
|
olmocr_science_pdfs
|
2024-11-25
|
2024-11-25
|
37088ba55ae787dcf19b2179639f9cde8fbf88bf
|
[REMOVED]
|
{"Source-Url": "https://hal.science/hal-00650573v1/document", "len_cl100k_base": 13507, "olmocr-version": "0.1.50", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 60193, "total-output-tokens": 18207, "length": "2e13", "weborganizer": {"__label__adult": 0.0004162788391113281, "__label__art_design": 0.0008525848388671875, "__label__crime_law": 0.0006222724914550781, "__label__education_jobs": 0.003353118896484375, "__label__entertainment": 0.00022172927856445312, "__label__fashion_beauty": 0.00026297569274902344, "__label__finance_business": 0.0005674362182617188, "__label__food_dining": 0.0003674030303955078, "__label__games": 0.0006780624389648438, "__label__hardware": 0.0010280609130859375, "__label__health": 0.0006275177001953125, "__label__history": 0.0006747245788574219, "__label__home_hobbies": 0.00014412403106689453, "__label__industrial": 0.0005598068237304688, "__label__literature": 0.0014657974243164062, "__label__politics": 0.0004549026489257813, "__label__religion": 0.0007123947143554688, "__label__science_tech": 0.303466796875, "__label__social_life": 0.00023281574249267575, "__label__software": 0.04718017578125, "__label__software_dev": 0.63525390625, "__label__sports_fitness": 0.00021708011627197263, "__label__transportation": 0.0004851818084716797, "__label__travel": 0.000217437744140625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 76654, 0.03862]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 76654, 0.41525]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 76654, 0.83854]], "google_gemma-3-12b-it_contains_pii": [[0, 976, false], [976, 5864, null], [5864, 9297, null], [9297, 14345, null], [14345, 18832, null], [18832, 25424, null], [25424, 31679, null], [31679, 39139, null], [39139, 44994, null], [44994, 50929, null], [50929, 56833, null], [56833, 62548, null], [62548, 68830, null], [68830, 76654, null], [76654, 76654, null]], "google_gemma-3-12b-it_is_public_document": [[0, 976, true], [976, 5864, null], [5864, 9297, null], [9297, 14345, null], [14345, 18832, null], [18832, 25424, null], [25424, 31679, null], [31679, 39139, null], [39139, 44994, null], [44994, 50929, null], [50929, 56833, null], [56833, 62548, null], [62548, 68830, null], [68830, 76654, null], [76654, 76654, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 76654, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 76654, null]], "pdf_page_numbers": [[0, 976, 1], [976, 5864, 2], [5864, 9297, 3], [9297, 14345, 4], [14345, 18832, 5], [18832, 25424, 6], [25424, 31679, 7], [31679, 39139, 8], [39139, 44994, 9], [44994, 50929, 10], [50929, 56833, 11], [56833, 62548, 12], [62548, 68830, 13], [68830, 76654, 14], [76654, 76654, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 76654, 0.05381]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
2a38f9c5dd3ef02a49823a555b834f98bd2d17b9
|
Model-Driven Software Refactoring
Tom Mens,
University of Mons-Hainaut, Belgium,
tom.mens@umh.ac.be
Gabriele Taentzer, Dirk Müller,
Philipps-Universität Marburg, Germany,
{taentzer, dmueller}@mathematik.uni-marburg.de
Abstract
In this chapter, we explore the emerging research domain of model-driven software refactoring. Program refactoring is a proven technique that aims at improving the quality of source code. Applying refactoring in a model-driven software engineering context raises many new challenges such as how to define, detect and improve model quality, how to preserve model behavior, and so on. Based on a concrete case study with a state-of-the-art model-driven software development tool, AndroMDA, we will explore some of these challenges in more detail. We propose to resolve some of the encountered problems by relying on well-understood techniques of meta-modeling, model transformation and graph transformation.
1. Introduction
In the current research and practice on software engineering, there are two very important lines of research for which tool support is becoming widely available. The first line of research is program refactoring, the second one is model-driven software engineering. To this date, however, the links and potential synergies between these two lines of research have not been sufficiently explored. This will be the main contribution of this chapter.
Model-driven software engineering.
In the realm of software engineering, we are witnessing an increasing momentum towards the use of models for developing software systems. This trend commonly referred to as model-driven software engineering, emphases on models as the primary artifacts in all phases of software development, from requirements analysis over system design to implementation, deployment, verification and validation. This uniform use of models promises to cope with the intrinsic complexity of software-intensive systems by raising the level of abstraction, and by hiding the accidental complexity of the underlying technology as much as possible (Brooks, 1995). The use of models thus opens up new possibilities for creating, analyzing, manipulating and formally reasoning about systems at a high level of abstraction.
To reap all the benefits of model-driven engineering, it is essential to install a sophisticated mechanism of model transformation, that enables a wide range of different automated activities such as translation of models (expressed in different modeling languages), generating code from models, model refinement, model synthesis or model extraction, model restructuring etc. To achieve this, languages, formalisms, techniques and tools that support model transformation are needed. More importantly, their impact on the quality and semantics of models needs to be better understood.
Program refactoring.
Refactoring is a well-known technique to improve the quality of software. Martin Fowler (1999) defines it as “A change made to the internal structure of software to make it easier to understand and cheaper to modify without changing its observable behavior”.
The research topic of refactoring has been studied extensively at the level of programs (i.e., source code). As a result, all major integrated software development environments provide some kind of automated support for program refactoring.
As a simple example of a program refactoring, consider the refactoring Extract Method, one of the more than 60 refactorings proposed by Fowler. Essentially, it is applied to a method in which part of the method body needs to be extracted into a new method that will be called by the original one. The situation before this program refactoring on a piece of
Java source code is shown in Figure 1, the situation after is shown in Figure 2. The code lines that differ between both versions are marked with an asterisk.
```java
protected LectureVO[] handleFindLecture
(java.lang.String title, domain.Weekday day, domain.Time time)
throws java.lang.Exception
* { SearchCriteria c = new SearchCriteria();
* c.setDay(day);
* c.setTitle(title);
* c.setTime(time);
* Collection coll =
* getLectureDao().findLecture(LectureDao.TRANSFORM_LECTUREVO,c);
* LectureVO[] lectures = new LectureVO[coll.size()];
* return (LectureVO[])coll.toArray(lectures); }
```
**Figure 1:** Java source code example before applying the Extract Method program refactoring.
```java
protected LectureVO[] handleFindLecture
(java.lang.String title, domain.Weekday day, domain.Time time)
throws java.lang.Exception
* { SearchCriteria c = this.initialise(title,day,time);
* Collection coll =
* getLectureDao().findLecture(LectureDao.TRANSFORM_LECTUREVO,c);
* LectureVO[] lectures = new LectureVO[coll.size()];
* return (LectureVO[])coll.toArray(lectures); }
* protected SearchCriteria initialise
* (java.lang.String title, domain.Weekday day, domain.Time time)
* throws java.lang.Exception
* { SearchCriteria c = new SearchCriteria();
* c.setDay(day);
* c.setTitle(title);
* c.setTime(time);
* return c; }
```
**Figure 2:** Java example after applying the Extract Method refactoring.
For program refactoring, a wide variety of formalisms has been proposed to gain a deeper understanding, and to allow formal analysis. One of these formalisms is graph transformation theory (Mens et al., 2005). We mention it here explicitly, as we will show later in this chapter how this formalism can be applied to support model refactoring as well. It is, however, not our goal to provide a detailed overview of existing work on program refactoring here. For the interested reader, we refer to a detailed survey of the state-of-the-art in this domain (Mens and Tourwé, 2004).
**Model-driven software refactoring.**
A natural next step seems to explore how the idea of refactoring may be applied in a model-driven software development context. We will refer to this combination as *model-driven software refactoring* and we will explore the ramifications of this synergy in the current chapter. One of the straightforward ways to address refactoring in a model-driven context is by raising refactorings to the level of models, thereby introducing the notion of **model refactoring**, which is a specific kind of model transformation that allows us to improve the structure of the model while preserving its quality characteristics. To the best of our knowledge, Sunyé et al. (2001) were the first to apply the idea of refactoring to models expressed in the Unified Modeling Language (UML).
A simple yet illustrative example of a UML model refactoring is shown in Figure 3. It depicts a class model in which two classes having attributes of the same type have been identified. The model refactoring consists of removing the redundancy by introducing an abstract super class of both classes, and moving up the attribute to this new super class.
**Figure 3:** Example of a model refactoring on UML class diagrams.
The above example may look simple, but it should be seen in a more general context, which makes dealing with model refactorings considerably less trivial. Consider the scenario depicted in Figure 4. It clearly illustrates the potentially high impact a simple refactoring may have on the software system. We assume that a model is built up from many different views, typically using a variety of different diagrammatic notations (e.g., class diagrams, state diagrams, use case diagrams, interaction diagrams, activity diagrams, and many more). We also assume that the model is used to generate code, while certain fragments of the code still need to be implemented manually. Whenever we make a change (in this case, a refactoring) to a single view or diagram in the model (step 1 in Figure 4), it is likely that we need to synchronize all related views, in order to avoid them becoming inconsistent (step 2 in Figure 4) (Grundy et al., 1998). Next, since the model has been changed, part of the code will need to be regenerated (step 3 in Figure 4). Finally, the manually written code that depends on this generated code will need to be adapted as well (step 4 in Figure 4).
**Figure 4:** A scenario for model-driven software refactoring.
2. State-of-the-art in Model Refactoring
At the level of models, research on refactoring is still in its infancy. Little research has been performed on model refactoring, and many open questions remain that are worthy of further investigation. For example, the relation between model refactoring and its effect on the model quality remains a largely unanswered question. From a practical point of view, only very few tools provide integrated support for model refactoring. Also, the types of models for which refactoring is supported is very limited.
In research literature, mainly UML models are considered as suitable candidates for model refactoring (Sunyé et al., 2001) (Astels, 2002) (Boger et al., 2002). In particular, refactoring of class models (e.g., UML class diagrams) has been investigated by various researchers. The advantage of such models is that they provide a representation that is relatively close to the way object-oriented programs are structured. As such, many of the refactorings known from object-oriented programming (Fowler, 1999) can be ported to UML class diagrams as well. For example, the refactoring shown in Figure 1 can also be considered as a class diagram refactoring, since a new method is created that will be visible in a class diagram. Of course, additional techniques are needed in order to ensure traceability and consistency between class diagrams and their corresponding source code when applying class diagram refactorings (Bouden, 2006).
When it comes to reasoning about the behavior preservation properties of class diagram refactorings, however, things become more difficult for various reasons. The main problem is that class diagrams provide an essentially structural description of the software architecture. Hence, behavioral information has to be expressed in a different way, either by resorting to OCL constraints, behavioral models (e.g., state diagrams or interaction diagrams), or by program code.
With respect to refactoring of behavioral models, not much work is available. We are only aware of a few approaches that address the problem of refactoring state diagrams, and try to prove their behavior preservation properties in a formal way. Van Kempen et al. (2005) use a formalism based on CSP to describe statechart refactorings, and show how this formalism can be used to verify that a refactoring effectively preserves behavior. Pretschner and Prenninger (2006) provide a formal
approach for refactoring state machines based on logical predicates and tables. Integrating these ideas into tool support is left for future work. Apart from some limitations imposed by the formalisms used, a more general problem is that there is still no generally accepted formal semantics for (UML) state diagrams. Many different interpretations exist and, obviously, this has an important effect on how the behavior is formally defined.
Though research on model refactoring is still in its infancy, a number of formalisms have already been proposed to understand and explore model refactoring. Most of these approaches suggest expressing model refactoring in a declarative way. Van Der Straeten et al. (2004) propose to use description logics; Van Der Straeten & D’Hondt (2006) suggest the use of a forward-chaining logic reasoning engine to support composite model refactorings. Gheyi et al. (2005) specify model refactorings using Alloy, a formal object-oriented modeling language. They use its formal verification system to specify and prove the soundness of the transformations. Biermann et al. (2006) and Mens et al. (2007) use graph transformation theory as an underlying foundation for specifying model refactoring, and rely on the formal properties to reason about and analyze these refactorings.
An important aspect of refactoring in a model-driven software development context that is typically neglected in research literature is how it interferes with code generation. Most contemporary tools for model-driven software development allow generating a substantial part of the source code automatically from the model, while other parts still need to be specified manually (see Figure 4). This introduces the need to synchronize between models and source code when either one of them changes. How such synchronization can be achieved in presence of an automated refactoring support is a question that has not been addressed in detail in research literature. If a model is being refactored, how should the corresponding source code be modified accordingly? Vice versa, if source code is being refactored, how will the models be affected? These are the kind of questions that will be addressed in this chapter. To this extent, we will report on our experience with AndroMDA, a state-of-the-art tool for model-driven software development based on UML.
3. Motivating example: Model-driven development with AndroMDA
This section presents the model-driven development of a small web application for a simple university calendar. We will develop this calendar in two iteration steps using AndroMDA\(^1\). First the underlying data model is designed and a web application with a default web presentation is generated. Second, application-specific services and the web presentation are developed with AndroMDA. This means that use cases are defined and refined by activity diagrams that can use controllers and services. The development is not hundred percent model-driven, since service and controller bodies have to be coded by hand.
For both iteration steps, we first present the UML model using the AndroMDA profile and then discuss a refactoring step useful in that context.
3.1 Getting started with developing a university calendar using AndroMDA
One of the main tools for model-driven software development is AndroMDA. Its transformation engine is structured by cartridges. A number of pre-defined cartridges is already available realizing the generation of web applications from UML models. We illustrate model-driven software development based on AndroMDA by the example of a very simple university calendar.
In principle, the model-driven development process of AndroMDA is based on use cases. But in this initial example, we start with an even simpler way of using AndroMDA. We just design the underlying data model and AndroMDA generates a complete web application with a default web presentation from that.
A web application generated by AndroMDA has a three-tier architecture consisting of a service layer building up on a data base, controllers using the services defined, and a web presentation. The underlying data model, services and controllers are defined by an UML class diagram. Additionally, visual object classes are modeled, which are used for presenting data to the user, decoupled from the internal data model.
\(^1\) http://galaxy.andromda.org
Figure 5: Data model for a simple university calendar
An example of an AndroMDA class diagram is shown in Figure 5. It depicts a simple data model for a university calendar. We can observe that the basic entities are Rooms that can be occupied for giving a Lecture or a Seminar. Based on this class diagram, AndroMDA can generate a default web interface for managing lectures, seminars and rooms. Users can add and delete instances, change attribute values and perform searches. The webpage for managing lectures is shown in Figure 6.
The UML profiles used in connection with AndroMDA can be considered as a domain-specific language, dedicated to the generation of web applications. This is achieved by giving a specific semantics to UML models by relying on that dedicated UML profiles. They extend the semantics of the UML by introducing specific stereotypes, to which additional constraints and tagged values are attached. For example, the stereotype «Entity» attached to a class is used to represent a data entity to be stored in a database. If, additionally, the «Manageable» stereotype is used, it causes AndroMDA to generate a default web presentation for managing the corresponding entities. The use of such manageable entities has been illustrated in Figure 5.
Due to their compactness, large parts of AndroMDA UML models are used for generating user interfaces. Thus, model refactorings in this context are likely to cause changes in user interfaces as well. Following Fowler (1999) in a strict sense, refactorings should not change the user interface of software, since they are supposed to “preserve the observable behavior”. This strict interpretation of refactoring, however, makes little sense if applied in a model-driven software development context, due to the side-effects that model refactorings may cause on the generated code, especially user interfaces. Thus, Fowler’s definition of refactoring should be interpreted in a more liberal way, in the sense that it should not change the functionality offered by software. Modifications to the usability of the software or to other non-functional properties (such as interoperability, portability, reusability, adaptability and the like) should be allowed, if the goal of these modifications is to improve the software quality.
In the remainder of this section we will show a concrete refactoring on our university calendar case study to clarify what refactoring can mean in the context of model-driven development.
Since «Entity» classes Lecture and Seminar contain several attributes in common (see Figure 5), it would make sense to refactor this data model by adding a new abstract superclass, called Course, and pulling up all common attributes to this new class. The result of this refactoring is shown in Figure 7.

**Figure 7:** Data model for a simple university calendar after having applied the **Pull Up Attribute** refactoring.
Figure 8: Webpage for managing courses
Note that tagged value @andromda.hibernate.inheritance has to be set to interface for restricting the management facilities for courses to searching functionalities only.
When regenerating a web application from the refactored data model in Figure 7, most of the web interface remains unaltered. But a new webpage will appear for managing courses, as shown in Figure 8. Because of the tagged value attached to course, this webpage only offers search functionality, but does not allow the addition or deletion of course instances.
In the example explained in section 3.1, all application code is generated from the model. Thus, refactoring the model alone appears to be sufficient to refactor the whole software application. However, it should be noted that, due to the refactoring applied to the model, the behavior has been changed slightly, since AndroMDA has generated a new kind of webpage.
3.3 Developing application-specific use cases with AndroMDA
In this section, we will consider additional stereotypes and tagged values in the AndroMDA UML profile, but only as far as we need them to develop our example. For a complete overview of all available stereotypes and how to use them we refer to the AndroMDA website.
«Service» is a class stereotype used to specify application-specific services. These services typically use one or more entities that store the data used by the services. For the model-driven development of a web presentation, we extend the model by use cases that are refined by activity diagrams. This model part describes the web presentation and its usage of controllers based on services. The development is not hundred percent model-driven, since service and controller bodies have to be coded by hand.
To illustrate the development of specific web applications we reconsider the university calendar and develop a specific use case diagram for lectures (see Figure 9). Use case Search lectures has two stereotypes being «FrontEndUseCase», which determines the use case to be visible to the user in form of a webpage, and «FrontEndApplication», which defines this use case to be the starting one.
Figure 9: Example of a use case model in AndroMDA
Use case Search lectures is refined by an activity diagram that supports a search activity and the presentation of filtered lectures (see Figure 10). Activity Search lectures is an internal activity that calls the controller method showLectures(). Activity Present lectures has stereotype «FrontEndView» implying that this activity models a webpage. Both activities are connected by two transitions arranged in a
cyclic way. After calling method \texttt{showLectures()} the result is transferred to the webpage by signal \texttt{show}, which has the resulting value object array as parameter. Signal \texttt{search} and its parameters are used to model the web form for filtering the lectures.
\begin{figure}[h]
\centering
\includegraphics[width=0.5\textwidth]{activity_diagram.png}
\caption{Example of an activity diagram specifying the \textit{Search lectures} use case}
\end{figure}
The class model in Figure 5 is again used as data model. To show lectures, a special value object class for lectures is used, which is specified by stereotype «ValueObject» (see Figure 11). This makes sense in terms of encapsulation (think of security, extensibility, etc.) and corresponds to the layered model-view-controller approach. Necessary information of the business layer is packaged into so-called "value objects", which are used for the transfer to the presentation layer. Passing real entity objects to the client may pose a security risk. Do you want the client application to have access to the salary information inside the Lecturer entity?
An attribute \texttt{room} of type \texttt{String} was added to \texttt{LectureVO} in order to allow a connection to the unique \texttt{number} of the \texttt{Room} class. Since value objects are used at the presentation layer, the types used are primitive ones; entity types are not used in that layer. A dependency relation between an entity and a value object is used to generate translation methods from the entity to its corresponding value object. Moreover, search criteria can be defined by a class of stereotype «Criteria».
Method `showLectures()` that is called from activity `Search lectures` in Figure 10, is defined in class `LectureController`, a class that relies on class `LectureService`. This class is stereotyped as «Service» and relies on entities `Lecture` and `Room` (see Figure 12). However, the bodies of service and controller methods cannot be modeled, but have to be coded directly by hand. For example, the implementation of service method `findLecture()` is shown in Figure 1. Because of special naming conventions of AndroMDA it has to be named `handleFindLecture()`. The web application generated by AndroMDA from the complete model given in the previous figures (together with manually written code parts) produces the webpage shown in Figure 13. Please note that the names used as page title, in the search form and for the buttons are generated from the model.
Figure 12: Service and controller classes
Figure 13: Webpage for searching lectures
3.4 Further refactoring of the university calendar
As a second model refactoring\(^2\), we will discuss the renaming of attribute time to starttime based on the model given in Section 3.3. We will argue that this refactoring affects the usability of the generated software. The refactoring is primarily performed on entity class Lecture, but since there is a value object class LectureVO for that entity, the corresponding value class attribute time has to be renamed into starttime, too (see Figure 14). The same is true in SearchCriteria. Thus, the standard refactoring method Rename Attribute becomes domain-specific and affects several classes in this domain-specific context.
\[\text{Figure 14: Value Object and Entity classes after renaming}\]
Since the value object attribute is not used directly in other parts of the model, the model does not have to be updated any further. But the hand-written code (given in Figure 1) is affected, since accessor method setTime() is no longer available after regenerating the code. Thus, it has to be renamed as well, by calling method setStarttime() instead. After
\(^2\) This model refactoring is actually domain-specific, as will be discussed later in this chapter.
having performed this refactoring, the webpage for searching lectures has been changed slightly. As a result, the usability is affected, though not dramatically, since the column named “Time” of the presented table presented has changed into “Starttime” (see Figure 15).
**Figure 15:** Webpage for searching lectures after renaming
Based on the analysis of both model refactorings carried out in this section, we can derive the following important preliminary conclusions:
- Generic model refactorings need to be adapted and refined in order to work properly in a domain-specific modeling language.
- Model refactorings may also affect, and require changes to the handwritten source code.
- Model refactorings may change external qualities as perceived by the user, such as usability aspects.
4. **Challenges in model-driven software refactoring.**
In this section, we will discuss some important challenges in model refactoring that have to do with the relation between model refactoring and model quality. It is not our ambition to solve all these challenges in
the current chapter. In Sections 5 and 6 we will therefore only focus on those challenges that we consider being most urgent and most important and we will exemplify our proposed solution using the case study introduced in the previous section.
**Model quality.**
A first challenge is to provide a precise definition of model quality. A model can have many different non-functional properties or quality characteristics that may be desirable (some examples are: usability, readability, performance and adaptability). It remains an open challenge to identify which qualities are necessary and sufficient for which type of stakeholder, as well as how to specify these qualities formally, and how to relate them to one another. Since the main goal of refactoring is to improve certain aspects of the software quality, we need means to assess this quality at the model level in an objective way. On the one hand, this will allow software modelers to identify which parts of the model contain symptoms of poor quality, and are hence potential candidates for model refactoring. On the other hand, quality assessment techniques can be used to verify to which extent model refactorings actually improve the model quality.
One of the ways to assess model quality is by resorting to what we will call *model smells*. These are the model-level equivalent of *bad smells*, a term originally coined by Kent Beck in (Fowler, 1999) to refer to structures in the code that suggest opportunities for refactoring. Typical model smells have to do with redundancies, ambiguities, inconsistencies, incompleteness, non-adherence to design conventions or standards, abuse of the modeling notation, and so on. A challenge here is to come up with a comprehensive and commonly accepted list of model smells, as well as tool support to detect such smells in an automated way. What is also needed is a good understanding of the relation between model smells and model refactoring, in order to be able to suggest, for any given model smell, appropriate model refactorings that can remove this smell.
A second way to assess and control model quality is by resorting to *model metrics*. In analogy with software metrics (Fenton and Pfleeger, 1997) they are used to measure and quantify desirable aspects of models. It remains an open question, however, how to define model metrics in such a way that they correlate well with external model quality.
characteristics. Another important issue is to explore the relation between model metrics and model refactoring, and in particular to assess to which extent model refactorings affect metric values. These issues have been addressed by (Demeyer et al., 2000) (Du Bois, 2006) (Tahvildari & Kontogiannis, 2004) though mainly at code level.
A final way to improve model quality is by introducing design patterns, which are proven solutions to recurring problems (Gamma et al., 1994). At code level, Kerievsky (2004) explored the relation between refactorings and design patterns. It remains to be seen how similar results may be achieved at the level of models.
Kamthan (2004) provided a quality framework for UML models. It systematically studies the quality goals, how to assess them, as well as techniques for improving the quality, similar to the ones discussed above.
**Model synchronization.**
With respect to model refactoring, one of the key questions is how it actually differs from program refactoring. Can the same ideas, techniques and even tools used for program refactoring be ported to the level of models? If not, what is it precisely that makes them different?
One answer to this question is that models are typically built up from different views, using different types of diagrams, that all need to be kept consistent. This in contrast to programs, that are often (though not always) expressed within a single programming language.³
Perhaps a more important difference is that models are abstract artifacts whose main purpose is to facilitate software development by generating a large portion of the source code that would otherwise need to be written manually. However, 100% full code generation is unfeasible in practice for most application domains. The additional challenge therefore consists in the need to synchronize and maintain consistency between models and their corresponding program code, especially when part of this program code has been specified or modified manually. In the context of model
---
³ Of course, programs also need to be synchronised with related software artefacts such as databases, user interfaces, test suites and so on. Each of these kinds of artefacts may have been expressed using a different language.
transformation, this implies that automated model refactorings (or other transformations) may need to be supplemented with code-level transformations in order to ensure overall consistency. Vice versa, program refactorings may need to be supplemented with model-level transformations to ensure their consistency.
Though no general solutions exist yet, the problem of model synchronization and model consistency maintenance is well known in literature. For example, (Van Gorp et al., 2003) discuss the problem of keeping the UML models consistent with its corresponding program code. (Correa & Werner, 2004) explain how OCL constraints need to be kept in sync when the class diagrams are refactored and vice versa. Egyed (2006) proposes an incremental approach to model consistency checking that scales up to large industrial models. Liu et al. (2002) and Van Der Straeten & D’Hondt (2006) rely on a rule-based approach for detecting and resolving UML model inconsistencies, respectively. Van Der Straeten et al. (2003) bear on the formalism of description logics to achieve the same goal. Mens et al. (2006) propose to resolve inconsistencies in an incremental fashion by relying on the formalism of graph transformation. Grundy et al. (1998) report on how tool support can be provided for managing inconsistencies in a software system composed of multiple views. Goedicke et al. (1999) address the same problem by relying on the formalism of distributed graph transformation.
**Behavior preservation.**
Another important challenge of model refactoring has to do with behavior preservation. By definition, a model refactoring is supposed to preserve the observable behavior of the model it is transforming. In order to achieve this, we need a precise definition of “behavior” in general, and for models in particular. In addition, we need formalisms that allow us to specify behavioral invariants, i.e., properties that need to be preserved by the refactoring. The formalism should then verify which of these invariants are preserved by the model refactoring. Although formal research on behavior preservation is still in its infancy, in Section 2 we already pointed to a few approaches that carried out initial research in this direction. Another approach that is worthwhile mentioning is the work by Gheyi et al. (2005). They suggest specifying model refactorings in Alloy, an object-oriented modeling language used for formal
specification. It can be used to prove semantics-preserving properties of model refactorings.
A more pragmatic way to ensure that the behavior remains preserved by a refactoring is by resorting to testing techniques. Many researchers have looked at how to combine the ideas of testing with model-driven engineering (Brottier et al., 2006) (Mottu et al., 2006). Test-driven development is suggested by the agile methods community as good practice for writing high-quality software. In combination with refactoring, it implies that before and after each refactoring step, tests are executed to ensure that the behavior remains unaltered.
**Domain-specific modeling.**
A final challenge is the need to define model refactorings in domain-specific extensions of the UML (such as AndroMDA), or even in dedicated domain-specific modeling languages. These refactorings should be expressible in a generic yet customizable way. Indeed, given the large number of very diverse domain-specific languages, it is not feasible, nor desirable, to develop dedicated tools for all of them from scratch.
Zhang et al. (2004) therefore proposed a generic model transformation engine and used it to specify refactorings for domain-specific models. Their tool is implemented in the Generic Modeling Environment (GME), a UML-based meta-modeling environment. A model refactoring browser has been implemented as a GME plug-in. Their tool enables the automation and user-defined customization of model refactorings using ECL (Embedded Constraint Language), an extension of the declarative OCL language with imperative constructs to support model transformation. As an example of the expressiveness of their approach, they illustrated how it can be applied to class diagrams, state diagrams and Petri nets. The solution that we will explore later in this chapter is related, in the sense that we will propose a generic approach for UML-based model refactoring based on graph transformation concepts.
In general, the main challenge remains to determine, for a given domain-specific modeling language, which transformations can be considered as meaningful refactorings. On the one hand, they will need to preserve some notion of “behavior” and, on the other hand, they need to improve some quality aspect. These notions of behavior and quality can differ
widely depending on the domain under study. For domains that do not refer to software (e.g., business domains, technical domains, etc.) it is much harder to come to a meaningful definition of behavior, implying that the notion of refactoring would become much harder to define in that context.
**Analyzing model refactorings.**
Even more advanced support for model refactorings can be envisaged if we have a precise means to analyze and understand the relationships between refactorings. This will enable us to build up complex refactorings from simpler ones; to detect whether refactorings are mutually exclusive, in the sense that they are not jointly applicable and to analyze causal dependencies between refactorings. These techniques have been explored in detail by Mens *et al.* (2007), and promise to offer more guidance to the developer on what is the most appropriate refactoring to apply in which context. A short introduction to this line of research will be given in Section 6.
5. Motivating example revisited
In Section 3 two concrete model refactorings have been applied to AndroMDA models: pulling up an attribute into a new superclass and renaming an entity. In this section, we explore some more refactorings for AndroMDA models.\(^4\) We start by considering a set of “standard” model refactorings widely used to restructure class diagrams. As it will turn out, most of these refactorings have side-effects due to constraints imposed by AndroMDA’s code generator. Therefore, these model refactorings need to be customized to take into account more domain-specific information. Next to these “standard” refactorings, we will also discuss entirely new “domain-specific” refactorings for AndroMDA models.
In the following, we will take a slightly broader view, and we discuss three categories of model transformations as follows:
(1) model refactorings that do not affect the user interface at all;
\(^4\) It is not our goal to be complete here.
(2) model refactorings that do affect the user interface with respect to the usability, but that do not affect what the user can do with the application; and
(3) model transformations that also affect the actual behavior/functionality of the application.
The latter category does not contain refactorings in the strict sense of the word, but it is nevertheless useful and necessary to deal with them. For example, it could be the case that what is perceived as a normal refactoring will actually extend the behavior as a side effect of the code generation process.
**Pull up Attribute.**
When pulling up an attribute to a super class, as explained in Section 3.2, the code generator will automatically generate a new webpage corresponding to this super class, with search functionality for each manageable entity. Thus, this model transformation belongs to category (3).
**Rename.**
The refactoring example in Section 3.4 is concerned with renaming an attribute of an entity class. This refactoring affects the user interface, if the entity is manageable. In this case, one of the columns in the table of the webpage has been renamed. Furthermore, in case that the entity class comes along with a value object class that is derived from the entity class, a renaming of an entity attribute has to be accompanied by a renaming of the corresponding attribute in its value object class. If, in addition, this value object attribute is used in some activity diagram, the name has to be adapted there as well. Furthermore, this value object attribute can occur in hand-written code, which implies that renaming has to be performed also in that part of the code.
A similar situation would arise if we renamed the entity class itself, as it would be reflected by a change in the title of the corresponding webpage for manageable entities. In case that the renamed entity class comes along with a value object class whose name is derived from the entity class name (e.g., in Figure 14, “LectureVO” is derived from “Lecture” by suffixing “VO”), renaming has to be accompanied by a renaming of its corresponding value object class. Furthermore, the renaming has to be
propagated as discussed for attributes. In all cases presented, although the user interface changes slightly, the functionality of the application is not affected. Hence, these refactorings belong to category (2).
Similar to entities, use cases can be renamed as well. This might have an effect on activity diagrams, since AndroMDA supports the connection of several activity diagrams via use case names. For example, an end activity of one activity diagram may be named as a use case, which means that the control flow would continue at the start activity of the corresponding activity diagram. In the generated web applications, use cases are listed on the right-hand side of each webpage. Again, a renamed use case would change the usability of the web application, but not its functionality, so the refactoring belongs to category (2).
In summary, we see that renaming in AndroMDA may have a high impact. Due to the fact that the code generator automatically produces new types of elements based on the names of existing elements, a seemingly simple change (in casu renaming) will propagate to many different places. A tool that would implement this model refactoring would therefore need to take these issues into account to ensure that the renaming does not lead to an inconsistent model or code. Furthermore, because the changes affect hand-written code, the refactoring may require a certain amount of user interaction.
Create Value Object.
A domain-specific refactoring for AndroMDA models is the creation of value objects for entities. An example is visually represented in Figure 16. Given a class with stereotype «Entity» (for example, class Lecture), a new class with stereotype «Value Object» is created and the entity class becomes dependent on this new class. The value object class is named after its entity class followed by suffix “VO” (for example, value object class LectureVO). The entity attributes are copied to the value object class, keeping names and types, by default. If internal information should be hidden from the client, the corresponding attribute would not be copied. This refactoring belongs to category (1) and does not affect any other part of the model, since the value object class is only created without being used yet.
Another domain-specific model refactoring is *Merge Services*. It takes two «Service» classes and merges them as well as all their incoming and outgoing dependencies. Consider the following example where both a LectureService and RoomService exist (see Figure 17). If we do not consider remote services and have only one controller class, it does not make sense to have two service classes. Therefore, both should be merged into LectureService. After refactoring, the controller class will have only one outgoing dependency. As a result, the hand-written code for the controller method will be affected. Nevertheless, this restructuring will not modify the external behavior, so users of the generated web application will not notice any change. Hence, this refactoring falls into category (1).
Split Activity.
The front-end of a web application is modeled by use cases and activity diagrams. A refactoring like the splitting of activities into two consecutive ones, linked by a transition, can directly affect the web presentation. If the original activity was a «FrontEndView», the corresponding webpage is split into two pages. If an internal activity was split, this refactoring has to be accompanied by a splitting of the corresponding controller method called. In the first case, the refactoring belongs to category (2), in the second case it belongs to category (1).
Extract Method.
*Extract Method* is a refactoring from the standard catalogue established by Fowler. In the context of model-driven development, and AndroMDA in particular, it can have new effects. Consider the scenario in Figure 19. First, we perform the extract method refactoring to the hand-written code, as illustrated in Figure 2 where a method, called initialise(), is extracted from a given service method handleFindLecture. To reflect this change at model level, we modify the class diagram by adding the extracted method to the class LectureService as well (see Figure 18).
Consequently, the code generator will generate extra code for this method, which requires the manually written code to be adapted to make it consistent again. In particular, method initialise() needs to be renamed into handleInitialise(), because this is the convention used by the code generator: all service methods need to be prefixed with "handle" at source code level. We can use this knowledge to constrain the Extract Method refactoring to make it domain-specific: When extracting a method, the name that the user needs to provide for the extracted method needs to follow the naming conventions imposed by the code generator. Not doing so will cause the precondition of the refactoring to fail.
Figure 18: Changes to the class diagram as a result of applying the Extract Method program refactoring (see Figure 2).
The above scenario is generalized and visualized in Figure 19. It shows how a refactoring at source code level (step 1) may require synchronization of the corresponding model (step 2) which, after regenerating the code (step 3) involves another modification to the handwritten part of the code (step 4). The last step is not needed, if the user obeys the naming convention for the new method as discussed above.
Figure 19: Another scenario of model-driven software refactoring, initiated by a refactoring of the hand-written source code.
6. Specifying and analyzing model refactorings
In Section 5, the important challenge of domain-independent support for model refactoring was discussed. A possible formalism that can be used to specify and also analyze refactorings is the theory of graph transformation (Ehrig et al. 2006). Compared to other approaches it has a number of advantages: it allows one to specify program refactorings and model refactorings for various languages in a uniform and generic way, by representing the software artifact under consideration as a graph, and by specifying the refactorings as graph transformation rules. In addition, one can benefit from the formal properties of graph transformation theory to reason about refactoring in a formal way. For example, properties such as termination, composition, parallel dependencies, and sequential dependencies can be analyzed.
Since the Eclipse Modeling Framework (EMF) has become a key reference for model specification in the world of model-driven development, we rely our approach to model refactoring on EMF model transformation. This approach is presented in Section 6.1. To perform a formal analysis of EMF transformations we translate them to graph transformations.
transformation, which is possible under certain circumstances. In Section 6.2, a conflict and dependency analysis of model refactorings is presented, assuming that the model refactorings are defined by graph transformation rules.
6.1 Technical solution
From a technical point of view, we will discuss how to implement and execute model refactorings. In particular, we will consider how to realize model refactoring within the Eclipse Modeling Framework (EMF). As a prerequisite, a specification of the underlying modeling language is needed, which will be given by a meta-model. Figure 20 shows an EMF model that represents a simplified extract of the AndroMDA meta-model. Figure 21 shows an instance of this EMF model for the entity class Lecture of the simple university calendar.

Mens et al., Model-Driven Software Refactoring
Biermann et al. (2006) explain in detail how EMF model refactoring can be expressed by EMF model transformation. This kind of model transformation is specified by rules and is performed in-place, i.e., the current model is directly changed and not copied. Each transformation rule consists of a left-hand side (LHS), indicating the preconditions of the transformation, a right-hand side (RHS), formulating the post conditions of the transformations, and optional negative application conditions (NAC), defining forbidden structures that prevent application of the transformation rule. Objects that are checked as precondition preserved during a transformation are indicated by colors. Object nodes of the same color present one and the same object in different parts of a rule. While attributes in the LHS may have constant values or rule variables only, they are allowed to carry Java expressions in the RHS, too. The same variable at different places in the rules means the same value at all places. In the following, we use this approach to EMF model transformation for specifying UML model refactorings.
In Figure 22 and Figure 23, two model transformation rules are shown, which both are needed to perform refactoring Create Value Object explained in Figure 16 of Section 5. Rule CreateValueObjectClass is applied once, creating a new value object class and a dependency of the entity class on this new class. A class model with an entity class is needed to create a value object class and a dependency in between. The name of this new value object class is constructed by taking the entity
class name e and adding suffix "vo". This rule is applied only if a value object class of this name has not already been created.
Figure 22: EMF model transformation rule CreateValueObjectClass for refactoring method Create Value Object.
Thereafter, rule CreateValueObjectAttribute is applied for each of the attributes of the entity class that should occur also in the value object class. Each time it is applied, it copies an attribute that has not yet been copied into the value object.
Figure 23: EMF model transformation rule CreateValueObjectAttribute for refactoring method Create Value Object.
Applying rule CreateValueObjectClass once and rule CreateValueObjectAttribute as often as entity class Lecture has attributes (i.e., four
times in this case) to the EMF model instance in Figure 21, we obtain the EMF model instance in Figure 24.

To open up the possibility for analyzing EMF model refactorings, we translate them to graph transformations. In this way, the formal analysis for graph transformation becomes available for EMF model refactoring. Although EMF models show a graph-like structure and can be transformed similarly to graphs, there is an important difference between both. In contrast to graphs, EMF models have a distinguished tree structure that is defined by the containment relation between their classes. Each class can be contained in at most one other class. Since an EMF model may have non-containment references in addition, the following question arises: What if a class, which is transitively contained in a root class, has non-containment references to other classes not transitively contained in some root class? In this case we consider the EMF model to be inconsistent.
A transformation can invalidate an EMF model, if its rule deletes one or more objects. To ensure consistent transformations only, rules that delete objects or containment links or redirect them, have to be equipped with additional NACs.
6.2 Formal solution
As an illustration of how refactoring dependency analysis may increase the understanding of refactoring, consider the following scenario. Assume that a software developer wants to know which refactoring rules need to be applied in order to restructure a software system. Typically, many different refactoring rules may be applicable, and it is not easy to find out what would be the most optimal way to apply these rules. Joint application of some refactoring rules may not be possible due to parallel dependencies between them, and some refactoring rules may sequentially depend on other ones. Graph transformation theory allows us to compute such dependencies by relying on the idea of critical pair analysis. The general-purpose graph transformation tool AGG\(^5\) provides an algorithm implementing this analysis.
Figure 25: Sequential dependencies computed by AGG for a representative set of refactorings implemented as graph transformations.
Figure 25 gives an example of all sequential dependencies that have been computed between a representative, yet simplified, subset of refactorings expressed as graph transformation rules. For example, we see that there is a sequential dependency between the CreateSuperclass refactoring and the PullUpVariable refactoring. CreateSuperclass inserts a new intermediate superclass (identified by node number 2) in between a class (node 1) and its old superclass (node 3). PullUpVariable moves a
\(^5\) http://tfs.cs.tu-berlin.de/agg
variable contained in a class up to its superclass. The dependency between both transformation rules, as computed by AGG, is visualized in Figure 26. The effect of applying CreateSuperclass before PullUpVariable will be that the variable will be pulled up to the newly introduced intermediate superclass instead of the old one. As such, there is a sequential dependency between both refactoring rules. It is even the case, in this example, that the application of both refactorings in a different order will produce a different result.
Figure 26: Example of a sequential dependency between the CreateSuperclass and the PullUpVariable refactoring.
For a more detailed discussion of how critical pair analysis can be used to reason about refactoring dependencies, we refer to (Mens et al., 2007) that provides a detailed account on these issues.
6.3 Related Work
Various authors have proposed to use some kind of rule-based approach to specify model refactorings, so it appears to be a natural choice: Grunske et al. (2005) show an example in Fujaba\(^6\) of how model refactoring may be achieved using graph transformation based on story-driven modeling. Bottoni et al. (2005) use distributed graph transformation concepts to specify coherent refactorings of several software artifacts, especially UML models and Java programs. Both kinds of artifacts are represented by their abstract syntax structures.
\(^6\) http://www.fujaba.de
Synchronized rules are defined to specify not only refactoring on models and programs separately, but to update also the correlation between different model parts and program. Synchronized rules are applied in parallel to keep coherence between model and program. Considering the special case where exactly two parts (one model diagram and the program or two model diagrams) are related, the triple graph grammar (TGG) approach by Schürr et al. (Schürr 1994, Königs & Schürr 2006) could also be used. Originally formulated for graphs, TGGs are also defined and performed on the basis of MOF models by the modeling environment MOFLON7.
(Porres, 2003) uses the transformation language SMW to specify model refactorings. This script language is also rule-based and resembles the Object Constraint Language (OCL). SMW is oriented at OCL for querying patterns, but also provides basic operations to realize transformations. A prototypical refactoring tool for UML models has been implemented based on SMW.
Van Der Straeten and D’Hondt (2006) suggest using a rule-based approach to apply model refactorings, based on an underlying inconsistency detection and resolution mechanism implemented in the description logics engine RACER8.
We decided to specify model refactorings based on EMF model transformation, since EMF is developing to a standard format for models and to be compatible with upcoming UML CASE tools based on EMF. Moreover, our approach opens up the possibility for analyzing model refactorings, since EMF model transformations can be translated to algebraic graph transformations.
7. Summary
Software complexity is constantly increasing, and can only be tamed by raising the level of abstraction from code to models. With the model-driven software engineering paradigm, automated code generation techniques can be used to hide the accidental complexity of the
7 http://www.moflon.org
8 http://www.racer-systems.com
underlying technology (Brooks, 1995). This enables one to deal with complex software in a systematic way.
To guarantee high-quality software, it is also important to address concerns such as readability, extensibility, reusability and usability of software. Software refactoring is a proven technique to reach these goals in a structured, semi-automated manner.
By integrating the process of refactoring into model-driven software development, we arrive at what we call **model-driven software refactoring**. Analogously to program refactoring, the first phase is to determine potential candidates for model refactorings, which can be obtained using “model smells” and “model metrics”. The second phase consists of applying the selected refactorings. This would be a relatively straightforward issue, if hundred-percent code generation were achievable. In practice, for large and complex software systems, this is not the case. Full code generation is not even desirable in many situations since – at least for describing algorithms or data conversions – source code seems to be more adequate than behavioral models. An additional difficulty is the lack of a general accepted semantics of UML. This makes it very difficult to determine whether a given model transformation is behavior preserving, which is the main criterion to decide whether something can be called refactoring or not, according to Fowler (1999).
As a feasibility study, we have chosen AndroMDA to illustrate the model-driven development of web applications. We illustrated and discussed a number of standard and domain-specific restructurings. Since they often change the observable behavior of the software in some sense, we explored to what extent they can be considered as refactorings. All restructurings were categorized into three groups, ordered by the fulfillment degree of Fowler’s criterion. The obtained results show that we should address the notion of model refactoring with care, and may serve as suggestions for better tool support:
- **We may want to support refactorings that do not fully preserve behavior, as long as they improve other important software quality aspects. This also implies that we need techniques to assess the effect of a model transformation on the software quality.**
• We need to find a balance between, and provide user support for the ability to specify generic model refactorings, and the ability to adapt and refine these refactorings to work properly in a domain-specific modeling language;
• We need to provide an interactive round-trip engineering approach to refactoring. When performing model refactorings, it turns out that manual intervention is frequently required in order to keep the abstraction levels of source code and model consistent. Model refactorings may also affect and require changes to the hand-written source code.
From a theoretical point of view, we have suggested to use graph transformation to provide a formal specification of model refactorings. It has the advantage of defining refactorings in a generic way, while still being able to provide tool support in commonly accepted modeling environments such as EMF. In addition, the theory of graph transformation allows us to formally reason about dependencies between different types of refactorings. Such a static analysis of potential conflicts and dependencies between refactorings can be helpful for the user during the interactive process of trying to improve the software quality by means of disciplined model transformations.
8. Future Research Directions
In Section 4, we identified many important challenges in model-driven software refactoring. We only worked out some of these challenges in more detail: the need for a formal specification of model refactorings, the need to reason about behavior preservation, the need to synchronize models and source code whilst applying refactorings, the need to relate and integrate the aspects of model refactoring and model quality. There are still many other challenges that remain largely unaddressed:
When developing large software systems in a model-driven manner, several development teams might be involved. In this case, it would be advantageous if the model could be subdivided into several parts that could be developed in a distributed way. Considering refactoring in this setting, model elements from different submodels might be involved. Thus, several distributed refactoring steps have to be performed and potentially synchronized if they involve common model parts.
Distributed refactoring steps could be considered as distributed model transformations (Goedicke et al., 1999) (Bottoni et al., 2005).
The usual way to test refactorings is by testing the code before and after refactoring steps. Clearly, the code has to satisfy the same test cases before and after refactoring it. Considering refactoring within model-driven development, the same testing procedure should be possible, i.e., test cases for the generated code before and after refactoring should produce the same results. As we discussed within this chapter, model-driven software refactoring often does not fulfill Fowler’s criterion in a stringent way. Future investigations should clarify the impact of this kind of restructuring on test suites (Van Deursen et al., 2002).
An important pragmatic challenge that has not been addressed in this chapter has to do with performance and scalability. Is it possible to come up with solutions that scale up to industrial software? Egyed (2006) provided initial evidence that this is actually the case, by providing an instant model synchronization approach that scales up to large industrial software models.
Another interesting research direction is to apply refactorings at the meta-model level. This raises the additional difficulty of needing to convert all models that conform to this meta-model accordingly, preferably in an automated way.
References
Mens et al., Model-Driven Software Refactoring
Knowledge, Information, and Data: Theory and Applications (pp. 95-125), Idea Group Publishing
Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1994). Design Patterns: Elements of Reusable Object-Oriented Languages and Systems. Addison-Wesley
Additional Reading
General and up-to-date information about graph transformation can be obtained via the website http://www.gratra.org/. For those readers wishing to get more in-depth information about what graph transformation is all about, we refer to the 3-volume “bible” of graph transformation research. Volume 1 focuses on its theoretical foundations; Volume 2 addresses applications, languages and tools; and Volume 3 deals with concurrency, parallelism and distribution.
Background information about model-driven software engineering can be obtained via the website http://www.planetmde.org/. This includes tool support and events devoted to this very active research domain. Many books on this topic have been published. In particular, we found the following ones to be very useful and relevant:
With respect to software evolution research, we suggest to consult the website http://www.planet-evolution.org/. Many books on this topic have been published. In particular, we found the following ones to be very useful and relevant:
Regarding software refactoring in particular, we would like to point to some of the early work on refactoring, which has been published in the following PhD dissertations:
There are many useful standards that have been published for software maintenance and software evolution. As is frequently the case, some of these standards may be somewhat outdated compared to the current state-of-the-art in research:
- The ISO/IEC 14764 standard on "Software Maintenance" (1999)
- The IEEE 1219 standard on "Software Maintenance" (1999)
- The ANSI/IEEE 1042 standard on "Software Configuration Management" (1987)
Finally, without pretending to be complete, we mention some useful websites with open source tools related to the themes of this chapter:
- The Eclipse Modeling Framework (EMF)
http://www.eclipse.org/emf
- The AndroMDA open source initiative
http://www.andromda.org
• The Tiger EMF Model Transformation Framework:
http://tfs.cs.tu-berlin.de/emftrans
• The graph transformation environment AGG:
http://tfs.cs.tu-berlin.de/agg
• The round-trip software engineering tool Fujaba relying on graph
transformation technology:
http://www.fujaba.de
• The graph-based model-driven engineering tool MOFLON relying on
graph transformation technology:
http://www.moflon.org
|
{"Source-Url": "http://www.mathematik.uni-marburg.de/~swt/lit/mdd/MTM08.pdf", "len_cl100k_base": 12883, "olmocr-version": "0.1.50", "pdf-total-pages": 46, "total-fallback-pages": 0, "total-input-tokens": 95445, "total-output-tokens": 18491, "length": "2e13", "weborganizer": {"__label__adult": 0.0003688335418701172, "__label__art_design": 0.0003216266632080078, "__label__crime_law": 0.0002834796905517578, "__label__education_jobs": 0.001239776611328125, "__label__entertainment": 4.7147274017333984e-05, "__label__fashion_beauty": 0.0001653432846069336, "__label__finance_business": 0.0001627206802368164, "__label__food_dining": 0.00031256675720214844, "__label__games": 0.0005140304565429688, "__label__hardware": 0.00045371055603027344, "__label__health": 0.00033783912658691406, "__label__history": 0.0001959800720214844, "__label__home_hobbies": 7.349252700805664e-05, "__label__industrial": 0.00028634071350097656, "__label__literature": 0.0002682209014892578, "__label__politics": 0.0002378225326538086, "__label__religion": 0.00044465065002441406, "__label__science_tech": 0.003208160400390625, "__label__social_life": 8.14199447631836e-05, "__label__software": 0.0033168792724609375, "__label__software_dev": 0.98681640625, "__label__sports_fitness": 0.0003104209899902344, "__label__transportation": 0.0004680156707763672, "__label__travel": 0.00019419193267822263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 76074, 0.02009]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 76074, 0.50053]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 76074, 0.89765]], "google_gemma-3-12b-it_contains_pii": [[0, 1401, false], [1401, 3704, null], [3704, 5176, null], [5176, 6992, null], [6992, 8231, null], [8231, 10679, null], [10679, 13043, null], [13043, 15064, null], [15064, 16336, null], [16336, 17551, null], [17551, 18042, null], [18042, 18979, null], [18979, 20676, null], [20676, 22340, null], [22340, 23202, null], [23202, 23287, null], [23287, 24505, null], [24505, 25574, null], [25574, 27996, null], [27996, 30259, null], [30259, 32691, null], [32691, 35021, null], [35021, 36989, null], [36989, 39152, null], [39152, 41419, null], [41419, 42214, null], [42214, 43380, null], [43380, 44615, null], [44615, 45955, null], [45955, 46854, null], [46854, 48451, null], [48451, 49195, null], [49195, 50523, null], [50523, 52025, null], [52025, 53462, null], [53462, 55393, null], [55393, 57673, null], [57673, 59925, null], [59925, 62265, null], [62265, 64622, null], [64622, 67043, null], [67043, 69472, null], [69472, 71853, null], [71853, 73878, null], [73878, 75668, null], [75668, 76074, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1401, true], [1401, 3704, null], [3704, 5176, null], [5176, 6992, null], [6992, 8231, null], [8231, 10679, null], [10679, 13043, null], [13043, 15064, null], [15064, 16336, null], [16336, 17551, null], [17551, 18042, null], [18042, 18979, null], [18979, 20676, null], [20676, 22340, null], [22340, 23202, null], [23202, 23287, null], [23287, 24505, null], [24505, 25574, null], [25574, 27996, null], [27996, 30259, null], [30259, 32691, null], [32691, 35021, null], [35021, 36989, null], [36989, 39152, null], [39152, 41419, null], [41419, 42214, null], [42214, 43380, null], [43380, 44615, null], [44615, 45955, null], [45955, 46854, null], [46854, 48451, null], [48451, 49195, null], [49195, 50523, null], [50523, 52025, null], [52025, 53462, null], [53462, 55393, null], [55393, 57673, null], [57673, 59925, null], [59925, 62265, null], [62265, 64622, null], [64622, 67043, null], [67043, 69472, null], [69472, 71853, null], [71853, 73878, null], [73878, 75668, null], [75668, 76074, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 76074, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 76074, null]], "pdf_page_numbers": [[0, 1401, 1], [1401, 3704, 2], [3704, 5176, 3], [5176, 6992, 4], [6992, 8231, 5], [8231, 10679, 6], [10679, 13043, 7], [13043, 15064, 8], [15064, 16336, 9], [16336, 17551, 10], [17551, 18042, 11], [18042, 18979, 12], [18979, 20676, 13], [20676, 22340, 14], [22340, 23202, 15], [23202, 23287, 16], [23287, 24505, 17], [24505, 25574, 18], [25574, 27996, 19], [27996, 30259, 20], [30259, 32691, 21], [32691, 35021, 22], [35021, 36989, 23], [36989, 39152, 24], [39152, 41419, 25], [41419, 42214, 26], [42214, 43380, 27], [43380, 44615, 28], [44615, 45955, 29], [45955, 46854, 30], [46854, 48451, 31], [48451, 49195, 32], [49195, 50523, 33], [50523, 52025, 34], [52025, 53462, 35], [53462, 55393, 36], [55393, 57673, 37], [57673, 59925, 38], [59925, 62265, 39], [62265, 64622, 40], [64622, 67043, 41], [67043, 69472, 42], [69472, 71853, 43], [71853, 73878, 44], [73878, 75668, 45], [75668, 76074, 46]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 76074, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
a6502c355372406f5046788c71ba6496ce647fa2
|
On Monadic Parametricity of Second-Order Functionals
Andrej Bauer¹, Martin Hofmann², and Aleksandr Karbyshev³
¹ University of Ljubljana
andrej.bauer@andrej.com
² Universität München
hofmann@ifi.lmu.de
³ Technische Universität München
aleksandr.karbyshev@in.tum.de
Abstract. How can one rigorously specify that a given ML functional \( f : (\text{int} \to \text{int}) \to \text{int} \) is pure, i.e., \( f \) produces no computational effects except those produced by evaluation of its functional argument? In this paper, we introduce a semantic notion of monadic parametricity for second-order functionals which is a form of purity. We show that every monadically parametric \( f \) admits a question-answer strategy tree representation. We discuss possible applications of this notion, e.g., to the verification of generic fixpoint algorithms. The results are presented in two settings: a total set-theoretic setting and a partial domain-theoretic one. All proofs are formalized by means of the proof assistant Coq.
1 Introduction
The problem under consideration is: how do we rigorously specify that a given ML functional \( f : (\text{int} \to \text{int}) \to \text{int} \) is pure, i.e., \( f \) only produces computational effects (changes store, raises an exceptions, produces output, consumes input, etc.) through calls of its functional argument? Second-order functionals of this type may appear as inputs in various third-order algorithms, such as generic fixpoint solvers [4,5] and algorithms for exact integration [15,20]. The algorithms often apply a presumably pure input \( f \) to an effectful argument in order to observe the intentional behaviour of \( f \), and to control the computation process.
In a previous paper [8] we addressed the question with regard to functionals that were polymorphic in the state monad and had the type \( \forall S.(A \to \text{State}_S B) \to \text{State}_S C \). The motivation there was rigorous verification of a generic fixpoint algorithm RLD [7] that used state. As it turns out [8], we could not use the standard notion of relational parametricity [17,18] because it is too weak to exclude the snapback functional \( f_{\text{snap}} : \forall S.(A \to \text{State}_S B) \to \text{State}_S B \), defined by
\[
f_{\text{snap}} S k s = \text{let } (b, s) = k a_0 s \text{ in } (b, s).
\]
The functional invokes its argument \( k \) to compute a result \( b \) but then discards the new state and restores the initial one instead. We can show that every functional
which is pure in the sense of [8] is represented by a question-answer strategy tree that computes the result by calling its function argument and letting through any effects generated by the calls. The functional \( f_{\text{snap}} \) is not pure in that sense.
The strategy tree reflects only the “skeleton” of a computation and is not specific to the kind of effects that may be raised. Obviously, we should look for a more general representation theorem that applies to other kinds of effectful computations. Indeed, in this paper we remove the limitation of [8] to state and prove a corresponding theorem for the class of second-order functionals polymorphic with respect to monads from an arbitrary fixed collection \( \text{Monad} \), i.e., those of type
\[
\text{Func} = \prod_{T \in \text{Monad}} (A \to TB) \to TC,
\]
so long as continuation monads \( \text{Cont}_R \) are included, for all \( R \). We may think of \( \text{Monad} \) as the class of monads present in a programming language. Every monad can be expressed in terms of continuation and state [6], but we do not use this fact and do not require \( \text{State} \in \text{Monad} \). Thus our representation result and that of Filinski [6] are different and do not imply each other directly. An interesting corollary is that a functional \( F \) which is pure for the state monads in the sense of [8] has an equivalent implementation which makes no use of state, and is moreover polymorphic in all monads from the given collection \( \text{Monad} \). Such an implementation is defined by a strategy tree for \( F \).
One possible application of the representation result is formal verification of the above mentioned algorithms. For example, when trying to prove correctness of the local fixpoint solver RLD we assumed without loss of generality that the input constraint system is given in the form of strategy trees. That allowed us to formulate sufficient pre- and post-conditions for the algorithm and complete the proof by induction. The fundamental lemma then allows us to argue that the functional input is indeed pure if it can be defined in some restricted programming language (with recursion) which is often the case in real-life program analysis.
The outline of the paper is as follows. After a preliminary Section 2 we define purity in Section 3 as a semantical notion of monadic parametricity. We also formulate a fundamental lemma for the call-by-value lambda calculus with monadic semantics. In section 4 we define a notion of a strategy tree and show they represent pure functionals of type Func in the total setting. Section 5 provides a similar result in the partial setting. In section 6 we discuss generalizations of purity to other types. In section 7 we discuss some application of purity.
All the proofs have been formalized by means of Coq theorem prover [21] and are available for download at [11]. We used the development of constructive \( \omega \)-cpos and inverse-limit construction for solution of recursive domain equations by Benton et al. [3]. Our contribution takes around 1500 lines of Coq code.
2 Preliminaries
We study purity in both the total and the partial setting. For the former we interprets types as sets and the latter as continuous posets (cpos), and thus use the notations $a : X$ and $a \in X$ interchangeably. We write $X \times Y$ and $X \rightarrow Y$ for Cartesian product and exponential, respectively. We denote pairs by $(x, y)$, and projections by $\text{fst}$ and $\text{snd}$. We use $\lambda$, $\circ$ and juxtaposition for function abstraction, composition and applications, correspondingly. For a family of sets or cpos $(X_i)_{i \in I}$ we write $\prod_{i \in I} X_i$ for its Cartesian product.
**Definition 1.** A monad is a triple $(T, \text{val}_T, \text{bind}_T)$ where $T$ is the monad constructor assigning to a type $X$ the type $TX$ of computations over $X$, and
$$\begin{align*}
\text{val}_T^A & : A \rightarrow TA \\
\text{bind}_T^{A,B} & : TA \rightarrow (A \rightarrow TB) \rightarrow TB
\end{align*}$$
are the monadic operators, satisfying for all $a$, $f$, $g$ and $t$ of suitable types
$$\begin{align*}
\text{bind}_T^{A,B}(\text{val}_T^A a)(f) &= f a \\
\text{bind}_T^{A,A}(t)(\text{val}_T^A) &= t \\
\text{bind}_T^{B,C}(\text{bind}_T^{A,B}(t(f))(g)) &= \text{bind}_T^{A,C}(t)(\lambda x. \text{bind}_T^{B,C}(f x)(g)) .
\end{align*}$$
For the partial case, we require that $TX$ is a pointed cpo (cppo) and that $T$ is strict,
$$\text{bind}_T^{A,B} \perp_T A f = \perp_T B .$$
We omit the indices $A, B, C$ when they can be deduced from the context.
The continuation monad $\text{Cont}_R$ with result type $R$ is defined by $\text{Cont}_R X = (X \rightarrow R) \rightarrow R$ and
$$\begin{align*}
\text{val}_{\text{Cont}_R} x &= \lambda c. c x \\
\text{bind}_{\text{Cont}_R} t f &= \lambda c. t(\lambda x. f x c) .
\end{align*}$$
The state monad $\text{State}_S$ with the type of states $S$ is defined by $\text{State}_S X = S \rightarrow X \times S$ and
$$\begin{align*}
\text{val}_{\text{State}_S} x &= \lambda s. (x, s) \\
\text{bind}_{\text{State}_S} t f &= \lambda s. \text{let} (x_1, s_1) \leftarrow t s \text{ in } f x_1 s_1 .
\end{align*}$$
In the following, we assume that $A, B, C, A_i, B_i$ are sets or cpos, as appropriate. Let $\text{Monad}$ be a fixed collection of monads such that $\text{Cont}_R \in \text{Monad}$, for all $R$, and denote
$$\text{Func} = \prod_{T \in \text{Monad}} (A \rightarrow TB) \rightarrow TC .$$
3 Purity
To define purity in our sense we first introduce several notions and notations. We then provide a relational interpretation of types and terms of call-by-value $\lambda$-calculus with monadic semantics, and establish a fundamental lemma of logical relations stating that every well-typed program respects any monadic relation, similar to \cite{[8]}.
Definition 2. If \( X, X' \) are types then \( \text{Rel}(X, X') \) denotes the type of binary relations between \( X \) and \( X' \). Furthermore:
- if \( X \) is a type then \( \Delta_X \in \text{Rel}(X, X) \) denotes the equality on \( X \);
- if \( R \in \text{Rel}(X, X') \) and \( S \in \text{Rel}(Y, Y') \) then \( R \to S \in \text{Rel}(X \to Y, X' \to Y') \) is given by
\[
f (R \to S) f' \quad \text{iff} \quad \forall x x'. xR x' \implies (f x) S (f' x') ;
\]
- if \( R \in \text{Rel}(X, X') \) and \( S \in \text{Rel}(Y, Y') \) then \( R \times S \in \text{Rel}(X \times Y, X' \times Y') \) is given by
\[
p (R \times S) p' \quad \text{iff} \quad \text{fst}(p) R \text{fst}(p') \land \text{snd}(p) S \text{snd}(p') .
\]
Definition 3. For cpos \( X, X' \) and \( R \in \text{Rel}(X, X') \), \( R \) is admissible if for any chains \( \{ c_i \}_{i \in \mathbb{N}}, \{ c'_i \}_{i \in \mathbb{N}} \) such that \( c_i R c'_i \), for all \( i \), \( (\bigsqcup c_i) R (\bigsqcup c'_i) \) holds.
Definition 4. Fix \( T, T' \in \text{Monad} \). For every \( X, X' \) and \( Q \in \text{Rel}(X, X') \) fix a relation \( T^\text{rel}(Q) \in \text{Rel}(T X, T' X') \). We say that the mapping \( (X, X', Q) \mapsto T^\text{rel}(Q) \) is an acceptable monadic relation if
- for all \( X, X', Q \in \text{Rel}(X, X') \), \( x \in X \), \( x' \in X' \),
\[
x Q x' \implies (\text{val}_T x) T^\text{rel}(Q) (\text{val}_{T'} x') ;
\]
- for all \( X, X', Q \in \text{Rel}(X, X'), Y, Y', R \in \text{Rel}(Y, Y') \), \( t \in T X \), \( t' \in T' X' \),
\[
t T^\text{rel}(Q) t' \land f(Q \to T^\text{rel}(R)) f' \implies (\text{bind}_T t f) T^\text{rel}(R) (\text{bind}_{T'} t' f') .
\]
In the domain-theoretic setting, we additionally assume that the monadic relation \( T^\text{rel} \) is
- admissible, i.e., \( T^\text{rel}(Q) \) is admissible for every admissible \( Q \in \text{Rel}(X, X') \),
- strict, i.e., \( (\bot_{T X}, \bot_{T' X'}) \in T^\text{rel}(Q) \).
Definition 5. A functional \( F \in \text{Func} \) is pure (monadically parametric) for the collection \( \text{Monad} \) of monads iff
\[
(F_T, F_{T'}) \in (\Delta_A \to T^\text{rel}(\Delta_B)) \to T^\text{rel}(\Delta_C)
\]
holds for all \( T, T' \in \text{Monad} \) and acceptable monadic relations \( T^\text{rel} \) for \( T, T' \).
Define simple types over a set of base types, ranged over by \( o \), by the grammar
\[
\tau ::= o \mid \tau_1 \times \tau_2 \mid \tau_1 \to \tau_2 .
\]
Fix an assignment of a set or a cpo, as the case may be, \([o]_T\) for each base type \( o \) and monad \( T \in \text{Monad} \). We extend \([-]_T\) to all types by putting
\[
\{\tau_1 \times \tau_2\}_T = \{\tau_1\}_T \times \{\tau_2\}_T , \quad \{\tau_1 \to \tau_2\}_T = \{\tau_1\}_T \to T\{\tau_2\}_T .
\]
Given a set of constants ranged over by \( c \), with corresponding types \( \tau^c \), and variables ranged over by \( x \), we define the \( \lambda \)-terms by
\[
e := x \mid c \mid \lambda x.e \mid e_1 e_2 \mid e.1 \mid e.2 \mid \langle e_1, e_2 \rangle
\]
with the last rule for recursive definitions in the partial case only. A typing context \( \Gamma \) is a finite map from variables to types. The typing judgement \( \Gamma \vdash e : \tau \) is defined by the usual rules:
\[
\begin{align*}
\Gamma \vdash x : \Gamma(x) & \quad \text{if } x \in \text{dom}(\Gamma) \\
\Gamma, x : \tau_1 \vdash e : \tau_2 & \quad \text{if } \Gamma \vdash \lambda x.e : \tau_1 \rightarrow \tau_2 \\
\Gamma \vdash e_1 : \tau_1 & \quad \Gamma \vdash e_2 : \tau_2 & \quad \Gamma \vdash e_1 e_2 : \tau_2 \\
\Gamma \vdash \langle e_1, e_2 \rangle : \tau_1 \times \tau_2 & \quad \Gamma \vdash e.1 : \tau_1 & \quad \Gamma \vdash e.2 : \tau_2 \\
\Gamma \vdash e_1 : \tau_1 & \quad \Gamma, x : \tau_1 \vdash e_2 : \tau_2 & \quad \Gamma \vdash \text{let } x \leftarrow e_1 \text{ in } e_2 : \tau_2 \\
& \quad \Gamma \vdash \text{let rec } f(x) = e : \tau_1 \rightarrow \tau_2 \\
\end{align*}
\]
The term \( e : \tau \) is closed if \( \emptyset \vdash e : \tau \).
For each \( T \in \text{Monad} \) and constant \( c \) fix an interpretation \( \llbracket c \rrbracket_T \in \llbracket \tau^c \rrbracket_T \). An environment for a context \( \Gamma \) and \( T \in \text{Monad} \) is a mapping \( \eta \) such that \( x \in \text{dom}(\Gamma) \) implies \( \eta(x) \in \llbracket \Gamma(x) \rrbracket_T \). If \( \Gamma \vdash e : \tau \) and \( \eta \) is such an environment then we define \( \llbracket e \rrbracket_T(\eta) \in T[\tau]_T \) by the following clauses:
\[
\begin{align*}
\llbracket x \rrbracket_T(\eta) &= \text{val}_T(\eta(x)) \\
\llbracket c \rrbracket_T(\eta) &= \text{val}_T(\llbracket c \rrbracket_T) \\
\llbracket \lambda x.e \rrbracket_T(\eta) &= \text{val}_T(\text{val}_V(\llbracket e \rrbracket_T(\eta|_{x \mapsto v}))) \\
\llbracket e_1 e_2 \rrbracket_T(\eta) &= \text{bind}_T(\llbracket e_1 \rrbracket_T(\eta)) \text{ (bind}_T(\llbracket e_2 \rrbracket_T(\eta)) \\
\llbracket e.i \rrbracket_T(\eta) &= \text{bind}_T(\llbracket e.i \rrbracket_T(\eta)) (\text{val}_T \circ \pi_i), \ i = 1, 2 \\
\llbracket \langle e_1, e_2 \rangle \rrbracket_T(\eta) &= \text{bind}_T(\llbracket e_1 \rrbracket_T(\eta)) (\text{bind}_T(\llbracket e_2 \rrbracket_T(\eta)) \circ \text{curry}(\text{val}_T)) \\
\llbracket \text{let } x \leftarrow e_1 \text{ in } e_2 \rrbracket_T(\eta) &= \text{bind}_T(\llbracket e_1 \rrbracket_T(\eta)) (\text{val}_V(\llbracket e.2 \rrbracket_T(\eta|_{x \mapsto v})))) \\
\llbracket \text{let rec } f(x) = e \rrbracket_T(\eta) &= \text{val}_T(\text{fixp}(\lambda h.\text{val}_V(\llbracket e \rrbracket_T(\eta|_{f \mapsto h}|_{x \mapsto v}))))
\end{align*}
\]
where \( \text{fixp} : \forall D. (D \rightarrow D) \rightarrow D \) is the least fixpoint operator for oppos, and \( \text{curry} \) is the currying function.
**Definition 6.** Fix monads \( T, T' \in \text{Monad} \) and an acceptable monadic relation \( T^\text{rel} \) for \( T, T' \). Given a binary relation \( \llbracket o \rrbracket_{T,T'}^\text{rel} \in \text{Rel}(\llbracket o \rrbracket_T, \llbracket o \rrbracket_{T'}) \) for each base type \( o \), we can associate a relation \( \llbracket \tau \rrbracket_{T,T'}^\text{rel} \in \text{Rel}(\llbracket \tau \rrbracket_T, \llbracket \tau \rrbracket_{T'}) \) with each type \( \tau \) by the following clauses:
\[
\begin{align*}
\llbracket o \rrbracket_{T,T'}^\text{rel} &= \llbracket o \rrbracket_T^\text{rel} \quad \llbracket \tau_1 \times \tau_2 \rrbracket_{T,T'}^\text{rel} &= \llbracket \tau_1 \rrbracket_{T,T'}^\text{rel} \times \llbracket \tau_2 \rrbracket_{T,T'}^\text{rel} \\
\llbracket \tau_1 \rightarrow \tau_2 \rrbracket_{T,T'}^\text{rel} &= \llbracket \tau_1 \rrbracket_{T,T'}^\text{rel} \rightarrow \llbracket \tau_2 \rrbracket_{T,T'}^\text{rel}.
\end{align*}
\]
The following parametricity theorem is immediate from the definition of acceptable monadic relation and the previous one.
**Theorem 7.** Fix $T, T' \in \text{Monad}$, and an acceptable monadic relation $T_{\text{rel}}$ for $T, T'$. Suppose that $[c]_T [\tau]_{\text{rel}} [c]_{T'}$ holds for all constants $c$. If $\emptyset \vdash e : \tau$ then $[e]_T T_{\text{rel}}([\tau]_{\text{rel}}) [e]_{T'}$.
**Proof.** One proves the following stronger statement by induction on typing derivations. Given $\Gamma \vdash e : \tau$ and environments $\eta$ for $\Gamma$ and $T$ and $\eta'$ for $\Gamma$ and $T'$ then
$$\forall x. \eta(x) [\Gamma(x)]_{\text{rel}} \eta'(x) \ \text{implies} \ [e]_T(\eta) T_{\text{rel}}([\tau]_{\text{rel}}) [e]_{T'}(\eta') .$$
The assertion of the theorem follows.
Every well-typed program $\emptyset \vdash e : \tau$ defines a truly polymorphic function of type $\forall T. [\tau]_T$ by taking a product over $\text{Monad}$. From theorem 7 we obtain
**Corollary 8.** Every truly polymorphic $F \in \text{Func}$ implemented in the calculus is monadically parametric.
We remark that we could incorporate Theorem 7 into the definition of Func after the definition 1 which would provide “higher-kindned type polymorphism” at that level. The theorem would then turn into a well-definedness assertions to go with the interpretation of type formers. We find the chosen presentation more convenient because it allows for a priori impure functionals whose purity can then be established a posteriori.
## 4 The Total Case
We first consider the set-theoretic semantics in which all functions are total and there is no general recursion, but we can use structural recursion on inductively defined sets.
Let the set of strategy trees $\text{Tree}$ be inductively generated by the constructors $\text{Ans} : C \rightarrow \text{Tree}$ and $\text{Que} : A \rightarrow (B \rightarrow \text{Tree}) \rightarrow \text{Tree}$. Thus, a strategy tree is either an answer leaf $\text{Ans} c$ with an answer value $c : C$, or a question node $\text{Que} a f$ with a query $a : A$ and a branching (continuation) function $f : B \rightarrow \text{Tree}$ that returns a tree for every possible answer of type $B$.
For a given monad $T \in \text{Monad}$, every strategy tree defines a functional. The conversion from trees to functionals is performed by the function $\text{tree2fun}_T : \text{Tree} \rightarrow (A \rightarrow TB) \rightarrow TC$ defined by structural recursion as
$$\text{tree2fun}_T(\text{Ans} c) = \lambda k. \text{val}_T c$$
$$\text{tree2fun}_T(\text{Que} a f) = \lambda k. \text{bind}_T(k a)(\lambda b. \text{tree2fun}_T(f b) k).$$
The functional queries and answers its argument $k$ according to the strategy tree, and passes through any effects produces by $k$. The definition is parametric in the monad $T$, so we can define the polymorphic version $\text{tree2fun}_t = \Lambda T : \text{Monad}. \text{tree2fun}_T t$ whose type is $\text{Tree} \rightarrow \text{Func}$.
Example 9. For \( A = B = C = \mathbb{N} \) and the tree \( t = \text{Que} 0 (\lambda x. \text{Ans} 42) \) we have
\[
\begin{align*}
t_{\text{tree2fun}} & = t_{\text{tree2fun}} (\text{Que} 0 (\lambda x. \text{Ans} 42)) = \\
& = \lambda k. \text{bind}_{T} (k \ 0) (\lambda b. t_{\text{tree2fun}} (\text{Ans} 42) \ k) \\
& = \lambda k. \text{bind}_{T} (k \ 0) (\lambda b. \text{val}_{T} \ 42).
\end{align*}
\]
Thus, the tree \( t = \text{Que} 0 (\lambda x. \text{Ans} 42) \) corresponds to a second-order function that queries its argument \( k \) at 0 and returns 42. Any effect produced by \( k \) is propagated, and no other effects are produced.
The following lemma states that every \( t \in \text{Tree} \) defines a monadically parametric computation.
**Lemma 10.** For any \( t \in \text{Tree} \), \( t_{\text{tree2fun}} \) is pure.
**Proof.** By induction on \( t \), see Appendix. \( \square \)
It may be a bit surprising that \( t_{\text{tree2fun}} \) has an inverse \( t_{\text{fun2tree}} \) which is defined with the help of the continuation monad simply as
\[
t_{\text{fun2tree}} F = F_{\text{Cont}_{\text{Tree}}} \text{Que} \text{Ans}.
\]
Let us show that \( t_{\text{fun2tree}} \) and \( t_{\text{tree2fun}} \) are inverses of each other. As is to be expected, one direction is easier than the other, so we first dispose of the easy one:
**Lemma 11.** For any \( t \in \text{Tree} \), \( t_{\text{fun2tree}} (t_{\text{tree2fun}} t) = t \).
**Proof.** We proceed by structural induction on \( t \). The case \( t = \text{Ans} \ c \) is easy:
\[
\begin{align*}
\text{fun2tree} (\text{tree2fun} (\text{Ans} \ c)) & = \\
& = \text{fun2tree} (\lambda T. \lambda k. \text{val}_{T} \ c) (\lambda k. \text{val}_{\text{Cont}_{\text{Tree}}} \ c) \text{Que} \text{Ans} = \text{Ans} \ c.
\end{align*}
\]
To check the case \( t = \text{Que} \ a \ f \), assume the induction hypothesis, for all \( b \in B \)
\[
\begin{align*}
\text{fun2tree} (\text{tree2fun} (\text{Que} \ a \ f)) & = \\
& = \text{fun2tree} (\lambda T. \lambda k. \text{bind}_{T} (k \ a) (\lambda b. \text{tree2fun}_{\text{Cont}_{\text{Tree}}} (f \ b) \ k)) \\
& = (\lambda k. \text{bind}_{\text{Cont}_{\text{Tree}}} (k \ a) (\lambda b. \text{tree2fun}_{\text{Cont}_{\text{Tree}}} (f \ b) \ k)) \text{Que} \text{Ans} \\
& = (\text{bind}_{\text{Cont}_{\text{Tree}}} (\text{Que} \ a) (\lambda b. \text{tree2fun}_{\text{Cont}_{\text{Tree}}} (f \ b) \text{Que})) \text{Ans} \\
& = (\text{Que} \ a) (\lambda b. \text{tree2fun}_{\text{Cont}_{\text{Tree}}} (f \ b) \text{Que} \text{Ans}) \\
& = (\text{Que} \ a) (\lambda b. \text{fun2tree} (\text{tree2fun} (f \ b))) \\
& = \text{Que} \ a \ f.
\end{align*}
\]
We used the induction hypothesis in the last step. \( \square \)
Of course, for the other inverse we have to use purity of functionals:
Theorem 12. For a pure $F \in \text{Func}$ and $T \in \text{Monad}$,
$$\text{tree2fun}_T(\text{fun2tree } F) = F_T.$$
We first verify the theorem for the continuation monad.
Lemma 13. Given a pure $F \in \text{Func}$, $\text{tree2fun}_{\text{Cont}_S}(\text{fun2tree } F) = F_{\text{Cont}_S}$ holds for all $S$.
Proof. Given $S$ and functions $q : A \to (B \to S) \to S$ and $a : C \to S$, we define the conversion function $\text{conv}_{q,a} : \text{Tree} \to S$ by $\text{conv}_{q,a} = \lambda t. \text{tree2fun}_{\text{Cont}_S} t q a$. We have:
$$\text{tree2fun}_{\text{Cont}_S}(\text{fun2tree } F) = F_{\text{Cont}_S}$$
$$\iff \forall q, a. (\text{F}_{\text{Cont}_S}(\text{Que})(\text{Ans}), F_{\text{Cont}_S} q a) \in G_{\text{conv}_{q,a}}$$
where $G_f$ is a graph of $f$, i.e., $(x, y) \in G_f$ iff $y = f x$. We prove the last proposition by constructing an appropriate monadic relation for $\text{Cont}_{\text{Tree}}$ and $\text{Cont}_S$ and utilizing purity of $F$. Fix some $q$ and $a$. For $X, X'$ and $R \in \text{Rel}(X, X')$, we define $T^\text{rel}_1(R) \in \text{Rel}(\text{Cont}_{\text{Tree}} X, \text{Cont}_S X')$ by
$$(H, H') \in T^\text{rel}_1(R) \iff \forall h, h'((h, h')) \in R \Rightarrow G_{\text{conv}_{q,a}} \implies (Hh, H'h') \in G_{\text{conv}_{q,a}}$$
It is straightforward to show $T^\text{rel}_1$ is an acceptable monadic relation. Since $F$ is pure, $(F_{\text{Cont}_{\text{Tree}}}, F_{\text{Cont}_S}) \in (\Delta_A \to T^\text{rel}_1(\Delta_B)) \to T^\text{rel}_1(\Delta_C)$. Thus, it suffices to check that $(\text{Que}, q) \in \Delta_A \to T^\text{rel}_1(\Delta_B)$ and $(\text{Ans}, a) \in \Delta_C \to G_{\text{conv}_{q,a}}$. The latter is obvious. For the former, take $a_1 \in A$ and $f : B \to \text{Tree}$, $f' : B \to S$ such that $(f, f') \in \Delta_B \to G_{\text{conv}_{q,a}}$. Then
$$\text{conv}_{q,a}(\text{Que } a_1 f) = \text{tree2fun}_{\text{Cont}_S}(\text{Que } a_1 f) q a$$
$$= \text{bind}_{\text{Cont}_S}(q a_1)(\lambda b. \text{tree2fun}_{\text{Cont}_S}(f b) q a)$$
$$= (q a_1)(\lambda b. \text{conv}_{q,a}(f b))$$
$$= q a_1 f'$$
and the former holds. \(\square\)
Now by the lemma $\text{tree2fun}_{\text{Cont}_T}(F_{\text{Cont}_T} \text{Que } \text{Ans}) = F_{\text{Cont}_T}$. Let
$$\varphi_1 = \text{bind}^{B,C}_T : TB \to \text{Cont}_T B,$$
$$\varphi_2 = \lambda g.g(\text{val}^C_T) : \text{Cont}_T C \to TC$$
and define $\Phi_T : ((A \to \text{Cont}_T B) \to \text{Cont}_T C) \to (A \to TB) \to TC$ as
$$\Phi_T F = \lambda h. \varphi_2(F(\varphi_1 \circ h)) = \lambda h. F(\text{bind}^{B,C}_T \circ h)(\text{val}^C_T).$$
Lemma 14. For any pure $F \in \text{Func}$ and with $\Phi_T$ as above, $\Phi_T(F_{\text{Cont}_T}) = F_T$.
Proof. The idea is to construct a suitable acceptable monadic relation and exploit
the purity of $F$. For $X, X', R \in \text{Rel}(X, X')$, we define $T^\text{rel}_2(R)$ as an element of
$\text{Rel}(\text{Cont}_TC X, TX')$ by letting $(H, H') \in T^\text{rel}_2(R)$ iff
\[
\forall h, h'. (h, h') \in R \Rightarrow (H h) \Delta_{TC} (\text{bind}_T H' h') .
\]
It is straightforward to show that $T^\text{rel}_2$ is an acceptable monadic relation, so we
omit the proof. Since $F$ is pure, we have $(F_{\text{Cont}_T} T, F_T) \in (\Delta_A \to T^\text{rel}_2(\Delta_B)) \to T^\text{rel}_2(\Delta_C)$. Note that for any $g : A \to TB$,
\[
\Phi_T(F_{\text{Cont}_T} T) g = F_{\text{Cont}_T} T (\text{bind}^{B,C}_T g)(\text{val}^C_T) \quad \text{ and }
F_T g = \text{bind}^{C,C}_T (F_T g)(\text{val}^C_T) .
\]
First, we show that $(\text{bind}^{B,C}_T g, g) \in \Delta_A \to T^\text{rel}_2(\Delta_B)$. Indeed, for any $a \in A$ and $h, h'$ such that $(h, h') \in \Delta_B \to \Delta_{TC}$ (and thus, $h = h'$) we have
$(\text{bind}^{B,C}_T g) a h = \text{bind}^{B,C}_T (g a) h'$. Therefore, we conclude
\[
(F_{\text{Cont}_T} T (\text{bind}^{B,C}_T g), \text{bind}^{C,C}_T (F_T g)) \in T^\text{rel}_2(\Delta_C) .
\]
Since $(\text{val}^C_T, \text{val}^C_T) \in \Delta_C \to \Delta_{TC}$, the lemma is proved. \hfill \Box
Proof (of Theorem 12). With the help of lemmas we see that
\[
F_T = \Phi_T(F_{\text{Cont}_T} T) \quad \text{(by lemma 14)}
= \Phi_T(\text{tree}_2\text{fun}_C (\text{fun}_2\text{tree} F)) \quad \text{(by lemma 13)}
= \text{tree}_2\text{fun}_C (\text{fun}_2\text{tree} F) \quad \text{(by lemmas 10, 14)}
\]
and the other inverse is established. \hfill \Box
We link the present result with that of [8]:
Corollary 15. Any functional
\[
F : \forall S. (A \to \text{State}_S B) \to \text{State}_S C
\]
which is pure in the sense of [8] may be implemented generically without using
state, i.e., there exists a monadically parametric functional $G \in \text{Func}$ such that
$F_S = G_{\text{State}_S}$ for all $S$.
Proof. Take $G = \text{tree}_2\text{fun}_T t_F$ where $t_F$ is the tree representation of $F$.
5 The Partial Case
In this section, we generalize the characterisation of monadically parametric
second-order functionals for the partial case in the domain-theoretic setting. In
what follows, we will use the term acceptable monadic relation to refer to ac-
ceptable monadic relations which are strict and admissible as formulated in
Definition 4.
5.1 Domain of Strategy Trees
We construct a cppo of “strategy trees” as a solution of a recursive domain equation $X \simeq \mathcal{F}(X)$ with a locally continuous functor $\mathcal{F} : \mathcal{C} \to \mathcal{C}$ for a suitable category $\mathcal{C}$ of domains.
Let $\eta_X : X \to X_\bot$ and $kleisli_X : (X \to X_\bot) \to (X_\bot \to X_\bot)$ be defined by
$$\eta_X x = x \quad kleisli_X f x = \begin{cases} \bot & \text{if } x = \bot \\ f x & \text{otherwise} \end{cases}.$$
Define the lift monad $T_\bot$ over $\text{Cpo}$ (category of cpos with continuous functions) by
$$T_\bot X = X_\bot, \quad \text{val}_{T_\bot}^X = \eta_X, \quad \text{bind}_{T_\bot}^{X,Y} f t = kleisli_X f t.$$
Let $\mathcal{F}(X) = C + B \times (A \to X_\bot)$ be such a functor for the Kleisli category for $T_\bot$ over $\text{Cpo}$. Let $\text{Tree}$ be a cpo such that $\text{Tree} \simeq \mathcal{F}(\text{Tree})$, together with two (continuous) isomorphism functions
$$\text{fold} : C + B \times (A \to \text{Tree}_\bot) \to \text{Tree}_\bot \quad \text{and} \quad \text{unfold} : \text{Tree} \to (C + B \times (A \to \text{Tree}_\bot))_\bot,$$
i.e., $kleisli(\text{fold}) \circ \text{unfold} = \eta_{\text{Tree}}$ and $kleisli(\text{unfold}) \circ \text{fold} = \eta_{\mathcal{F}(\text{Tree})}$ hold. For all isomorphisms in the Kleisli category for $T_\bot$, say, $f : X \to Y_\bot$ and $g : Y \to X_\bot$ that $kleisli(f) \circ g = \eta$ and $kleisli(g) \circ f = \eta$, $f$ and $g$ are total functions. Therefore, we can define total
$$\text{roll} : C + B \times (A \to \text{Tree}_\bot) \to \text{Tree} \quad \text{and} \quad \text{unroll} : \text{Tree} \to C + B \times (A \to \text{Tree}_\bot)$$
using their “partial” counterparts fold and unfold. Moreover, the minimal invariance property takes place
$$\text{fixp } \delta = \eta$$
for $\delta : (\text{Tree} \to \text{Tree}_\bot) \to (\text{Tree} \to \text{Tree}_\bot)$ defined by $\delta e = \text{fold} \circ F(e) \circ \text{unfold}$. For details on a Coq development of the reverse-limit construction and a formal proof of the minimal invariance, refer to [3].
It is well known that the morphism fold forms an initial $F$-algebra in the Kleisli category, i.e., for any other $F$-algebra $\varphi : F(D) \to D$ there exists the unique homomorphism $h : \text{Tree} \to D_\bot$ such that $\varphi \circ F(h) = h \circ \text{fold}$.
**Definition 16.** We call elements of $\text{Tree}_\bot$ strategy trees. Define continuous “constructor” functions $\text{Ans} : C \to \text{Tree}_\bot$ and $\text{Que} : A \to (B \to \text{Tree}_\bot) \to \text{Tree}_\bot$ by
$$\text{Ans} = \text{fold} \circ \text{inl} \quad \text{and} \quad \text{Que} = \text{fold} \circ \text{inr}.$$
As in the total case, a strategy tree can be extracted by means of the continuation monad $\text{Cont}_{\text{Tree}_\bot}$. We define the extracting function $\text{fun2tree} : \text{Func} \to \text{Tree}_\bot$ by
$$\text{fun2tree } F = F_{\text{Cont}_{\text{Tree}_\bot}} \text{Que } \text{Ans}.$$
The definition is correct since \( \text{Cont}_{\text{Tree}_\perp} \) is a strict monad. The function \( \text{fun2tree} \) is strict and continuous.
The reverse translation mapping \( \text{Tree}_\perp \) into \( \text{Func}_T \) is defined by means of the fixpoint operator \( \text{fixp} : \forall D. (D \to D) \to D \) for cppos as follows. Given \( T \in \text{Monad} \), we construct
\[
\text{tree2fun}_T : \text{Tree}_\perp \to \text{Func}_T = \text{fixp} G_T
\]
where
\[
G_T : (\text{Tree}_\perp \to \text{Func}_T) \to \text{Tree}_\perp \to \text{Func}_T = \lambda f. \text{kleisli}(\phi_T, \psi^f_T) \circ \text{unroll}
\]
\[
\phi_T : C \to \text{Func}_T = \lambda c. \lambda h. \text{val}_T c
\]
\[
\psi^f_T : A \times (B \to \text{Tree}_\perp) \to \text{Func}_T = \lambda p. \lambda h. \text{bind}_T(h(\pi_1 p))(\lambda b. (f \circ \pi_2 p) b h).
\]
For every pointed \( T \in \text{Monad} \), \( \text{tree2fun}_T \) is correctly defined (since \( \text{Func}_T \) is pointed) and is continuous and strict. The parametric version is defined by \( \text{tree2fun}_t = \Lambda T. \text{tree2fun}_T t \). The following result is proved in Appendix.
**Lemma 17.** For any \( t \in \text{Tree}_\perp \), \( \text{tree2fun} t \) is pure. \( \square \)
### 5.2 Representation Theorem
**Lemma 18.** For any \( t \in \text{Tree}_\perp \), \( \text{fun2tree}(\text{tree2fun} t) = t \).
**Proof.** We note that \( \text{fun2tree} \circ \text{tree2fun} \) is a homomorphism for \( \text{Tree} \). Thus, the statement follows from initiality of \( \text{fold} \). We give a direct formal proof using the minimal invariance property. \( \square \)
Proofs of the following results are similar to the proofs in the total case.
**Theorem 19.** For a pure \( F \in \text{Func} \),
\[
\text{tree2fun}_T(\text{fun2tree} F) = F_T
\]
holds (extensionally) for any \( T \in \text{Monad} \).
We first prove that the statement holds for an arbitrary continuation monad with a pointed result domain. See Appendix for the proof.
**Lemma 20.** Given pure \( F \), \( \text{tree2fun}_{\text{Cont}_S}(\text{fun2tree} F) = F_{\text{Cont}_S} \) holds for any cppo \( S \). \( \square \)
As in the total case, for \( T \in \text{Monad} \) we define
\[
\Phi_T : ((A \to \text{Cont}_{TC} B) \to \text{Cont}_{TC} C) \to (A \to TB) \to TC
\]
and prove
**Lemma 21.** For a pure \( F \in \text{Func} \) and \( T \in \text{Monad} \), \( \Phi_T(F_{\text{Cont}_T}) = F_T \).
**Proof.** The proof repeats the one of lemma 14. We only have to check that \( T^\text{rel}_2 \) defined as in lemma 14 is a strict, admissible and acceptable monadic relation, which does hold. \( \square \)
6 Generalizations
In this section, we argue that it is possible to extend the notion of purity to an arbitrary second-order type. Consider a general type \( n\)-\text{Func} of second-order functionals with \( n \) functional arguments
\[
n\text{-Func} = \forall T. (A_1 \to TB_1) \to \cdots \to (A_n \to TB_n) \to TC.
\]
Definition 22. A functional \( F \in n\)-\text{Func} is pure (monadically parametric) iff
\[
(F_T, F_{T'}) \in (\Delta A_1 \to T^{\text{rel}}(\Delta B_1)) \to \cdots \to (\Delta A_n \to T^{\text{rel}}(\Delta B_n)) \to T^{\text{rel}}(\Delta C)
\]
holds for all \( T, T' \in \text{Monad} \) and acceptable monadic relations \( T^{\text{rel}} \) for \( T, T' \).
By theorem 7 any well-typed program of type \( n\)-\text{Func} is pure in this sense.
Definition 23. The set of strategy trees \( n\)-\text{Tree} is a minimal set generated by constructors
- \( \text{Ans} : C \to n\text{-Tree} \)
- \( \text{Que}_i : A_i \to (B_i \to n\text{-Tree}) \to n\text{-Tree}, i = 1, \ldots , n \)
Similar to the case of one functional argument, one defines functions
\[
tree2\text{fun} : n\text{-Tree} \to n\text{-Func} \quad \text{and} \quad \text{fun2tree} : n\text{-Func} \to n\text{-Tree}.
\]
Now, the result of Theorem 12 can be generalized for \( n\)-\text{Func}.
Theorem 24. Given a pure \( F \in n\)-\text{Func}, \( \text{tree2fun}_T(\text{fun2tree} F) = F_T \) holds (extensionally) for any \( T \in \text{Monad} \).
The formal Coq proof of the theorem is provided in the total setting and uses dependent types.
Characterization for the type \( n\)-\text{Func} with a parameter type \( D \) (equivalently, with finitely many parameter types \( D_1, \ldots , D_k \))
\[
n\text{-Func}_D = \forall T. D \to (A_1 \to TB_1) \to \cdots \to (A_n \to TB_n) \to TC
\]
is similar, with parameterized strategies of type
\[
n\text{-Tree}_D = D \to n\text{-Tree}.
\]
For types of order higher than two it is not that clear yet what corresponding strategies should be let alone how one could characterise their existence by parametricity. It could be, however, that strategies in the sense of game semantics, like in [1,2,9], are the right generalization. The another possible approach is in using of Kripke relations of varying arity as in [10]. This might be an interesting question for further investigation.
\begin{verbatim}
let rec solve (n:int) x s : Maybe S = match n with |
| 0 \to None |
| _ \to if is_stable x s then Some s
else let s0 = add_stable x s in do p \leftarrow F (eval (n-1) x) s0;
let (d, s1) = p in let cur = getval s1 x in if d \subseteq curval s1 x in Some s1
else let s2 = setval (cur \sqcup d) s1 in let s0 = add_infl y \times s in
let (w, s3) = extract_work s2 in do s1 \leftarrow solve (n-1) y s0;
solve_all (n-1) w s3
and solve_all (n:int) w : Maybe S = match n with |
| 0 \to None |
| _ \to match w with |
| \[
\] \to Some s |
| x \to x s |
and eval n x y : StateT S Maybe D = match n with |
| 0 \to fun s \to None |
| _ \to fun s \to let s0 = add_infl y \times s in
let s0 = add_infl y \times s in
let (w, s3) = extract_work s2 in do s1 \leftarrow solve (n-1) y s0;
Some (getval s1 y, s1)
\end{verbatim}
Fig. 1. The pure functional implementation of totalized RLD
7 Applications
Modulus of Continuity. Recall that a functional \( F : \mathbb{B} \to \mathbb{N} \) defined on the Baire space \( \mathbb{B} = \mathbb{N} \to \mathbb{N} \) is continuous at \( f \in \mathbb{B} \) if \( Ff \) depends only on finitely many elements of \( f \). A modulus for \( F \) at \( f \) is a number \( n \) such that \( Ff \) depends only on the first \( n \) terms of \( f \). Suppose \( F \) is pure functional, i.e., it is given by means of a monadically parametric function \( F : \prod _{T} S \to \mathbb{N} \) such that \( F = TId \), where \( Id \) is the identity monad. Then we can effectively extract a modulus for \( F \) at \( f \) by means of the functional
\[
\text{Mod } F f = \max (\text{snd} (\text{StateListN} (\text{Instr f} [[])))
\]
where \( \text{Instr f} : \mathbb{N} \to \text{StateListN} = \lambda a. \lambda l. (f a, l++[a]) \) instruments \( f \) by means of recording of a list of visited indices. That \( \text{Mod} \) computes what it is supposed to is shown by the following proposition.
Proposition 25. Let \( F : \mathbb{B} \to \mathbb{N} \) be pure, \( f : \mathbb{B} \) and \( m = \text{Mod } F f \). Then for every \( g : \mathbb{B} \) if \( f i = g i \) holds for all \( i \leq m \), then \( F f = F g \).
Proof (sketch). Given \( l_f = \text{snd} (\text{StateListN} (\text{Instr f} [[))) \), one can use \( l_f \) to traverse the strategy tree for \( F \) using values from \( l_f \) as corresponding answers at Que-nodes. We show that by so using \( l_f \) one reaches a leaf \( \text{Ans} n \) with \( n = F f \). By assumption, for all the questions queried when traversing with \( l_f \), \( f \) and \( g \) must deliver identical answers. We conclude, \( l_f = l_g \), and hence \( F f = F g \).
Verified Fixpoint Algorithms. The provided characterization of pure functionals of type \( \text{Func} \) can be used for verification of generic off-the-shelf fixpoint
algorithms which are used to compute a (local) solution of a constraint system $x \sqsubseteq F_x$, $x \in V$, defined over a bounded join-semilattice $\mathbb{D}$ of abstract values and a set of variables $V$. The local solver RLD, which relies on self-observation, applies $F$ to a special stateful function to discover variable dependencies and perform demand-driven evaluations [7]. In order to reason about the algorithm formally, we implement RLD in purely functional manner and model side-effects by means of the state monad. Thus, the pure right-hand side $F$ is assumed to be of type
$$F : \forall S. V \rightarrow (V \rightarrow \text{State}_S \mathbb{D}) \rightarrow \text{State}_S \mathbb{D}.$$
Assuming that all right-hand sides $F$ are pure and hence representable by strategy trees, one can formulate sufficient pre- and post-conditions to verify partial correctness of the algorithm.
Notice that RLD may diverge since we pose no extra restrictions on $\mathbb{D}$ (e.g., ascending chain condition) in general. However, we can define a totalized version of RLD by passing an extra natural parameter to every main function of the algorithm which limits a maximum depth of recursion. Once the limit is reached, the solver terminates with None. Figure 1 gives a pure functional implementation of the totalized version of RLD. Since $F$ is pure, by Corollary 15, a corresponding strategy tree provides a monadically parametric implementation, which can be used as
$$F : V \rightarrow (V \rightarrow \text{State}_T S \text{Maybe} \mathbb{D}) \rightarrow \text{State}_T S \text{Maybe} \mathbb{D}$$
where $\text{Maybe}$ is an option monad, $\text{State}_T$ is a state monad transformer, and $S$ is a state structure managed by the solver. The total version can be implemented and proven correct in CoQ with the certified code extracted in ML.
The characterization of 2-Func can be applied to verification of local fixpoint algorithms for side-effecting constraint systems [19] used for interprocedural analysis and analysis of multithreaded code. The main idea here is that in each constraint $x \sqsubseteq F_x$ the right-hand side $F_x$ is a pure function representable by a strategy tree with two kind of question nodes: QueR for which values of variables are queried using a stateful function $\text{get}$ and QueW which, when accessed, update current values of some variables by means of a stateful function $\text{set}$. Thus, the strategy tree specifies a sequence of reading and writing accesses to some constraint variables. One version of such a solver although not verified presently is implemented in the program analyzer Goblint [23].
8 Conclusion
We have provided two equivalent characterisations of pure second-order functionals in the presence of nontermination; an extensional one based on preservation of relations and an intensional one based on strategy trees. All verifications have been formalized in Coq.
Our results can be applied to the verification of algorithms that take pure second-order functionals as input. Among these are generic fixpoint algorithms and algorithms for exact real arithmetic. It is generally easier to verify the correctness of such an algorithm assuming the intensional characterisation of purity...
for its input. On the other hand, for a concretely given input, e.g. in the form of a program in some restricted language it will be easier to establish the extensional characterisation. The techniques developed in this paper were extended to impure higher-order functions enabling modular reasoning about monadic mixin components [13].
We note that a closely related characterisation albeit in a rather different guise has already been given in O’Hearn and Reynolds landmark paper [16]. Our strategy trees appear there as an intensional characterisation of first-order Algol procedures which due to the call-by-name policy are in fact second-order functionals. New aspects of the present work are in particular the monadic formulation, the generalisation of the extensional characterisation to monads other than the state monad, and the complete formalisation in CoQ.
Interestingly, our acceptable monadic relations in the total case (Definition 4), also appear in [22] where they are used to derive free theorems in the sense of Wadler [24] for Haskell programs in monadic style. However, the application to the characterisation of pure second-order functionals and the subsequent characterisation with strategy trees do not appear in loc.cit. It is, however, fair to say that the method of [22], being essentially the same as ours, could be used to derive our main result (Representation Theorems), assuming that one adapts it to the partial case which was left open in loc.cit.
As pointed out by an anonymous reviewer, a proof of our results can be given using Katsumata’s $\top\top$-lifting construction [12] if one considers strategy trees as free monads. This approach would require $\text{Tree} \in \text{Monad}$ for all possible result sets $C$. However, from the practical point of view, we would prefer that $F$ is defined for continuation monads rather than for syntactical monads $\text{Tree}$.
A natural question, albeit of mostly academic interest, is the extension of this work to higher than second order. Given that the strategy trees resemble winning strategies in game semantics it would seem natural to attempt to find extensional characterisations of the existence of a winning strategy. Care would have to be taken so as to sidestep the undecidability of lambda definability [14], thus the extensional property would have to be undecidable even if basic types receive a finite interpretation.
Acknowledgements. We thank Alex Simpson, University of Edinburgh, for raising an interesting question and fruitful discussions on the topic. We thank Helmut Seidl and anonymous reviewers for valuable comments on the paper. The third author was supported by GRK 1480.
References
13. Keuchel, S., Schrijvers, T.: Modular monadic reasoning, a (co-)routine. IFL 2012, pre-proceedings, RR-12-06 (August 2012)
14. Loader, R.: The undecidability of lambda-definability
|
{"Source-Url": "https://rd.springer.com/content/pdf/10.1007%2F978-3-642-37075-5_15.pdf", "len_cl100k_base": 14046, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 66474, "total-output-tokens": 16802, "length": "2e13", "weborganizer": {"__label__adult": 0.000545501708984375, "__label__art_design": 0.0006031990051269531, "__label__crime_law": 0.0006589889526367188, "__label__education_jobs": 0.0011777877807617188, "__label__entertainment": 0.00013113021850585938, "__label__fashion_beauty": 0.00028014183044433594, "__label__finance_business": 0.0003724098205566406, "__label__food_dining": 0.0007734298706054688, "__label__games": 0.0015583038330078125, "__label__hardware": 0.00119781494140625, "__label__health": 0.0013380050659179688, "__label__history": 0.0005240440368652344, "__label__home_hobbies": 0.00017642974853515625, "__label__industrial": 0.0008955001831054688, "__label__literature": 0.0007443428039550781, "__label__politics": 0.0005826950073242188, "__label__religion": 0.0010042190551757812, "__label__science_tech": 0.12298583984375, "__label__social_life": 0.0001499652862548828, "__label__software": 0.005146026611328125, "__label__software_dev": 0.85693359375, "__label__sports_fitness": 0.0005102157592773438, "__label__transportation": 0.001148223876953125, "__label__travel": 0.0002987384796142578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46511, 0.01616]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46511, 0.26179]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46511, 0.71909]], "google_gemma-3-12b-it_contains_pii": [[0, 2525, false], [2525, 5635, null], [5635, 8390, null], [8390, 11170, null], [11170, 15194, null], [15194, 18198, null], [18198, 21019, null], [21019, 23730, null], [23730, 26198, null], [26198, 29243, null], [29243, 31919, null], [31919, 34250, null], [34250, 37091, null], [37091, 40360, null], [40360, 43419, null], [43419, 46511, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2525, true], [2525, 5635, null], [5635, 8390, null], [8390, 11170, null], [11170, 15194, null], [15194, 18198, null], [18198, 21019, null], [21019, 23730, null], [23730, 26198, null], [26198, 29243, null], [29243, 31919, null], [31919, 34250, null], [34250, 37091, null], [37091, 40360, null], [40360, 43419, null], [43419, 46511, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46511, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46511, null]], "pdf_page_numbers": [[0, 2525, 1], [2525, 5635, 2], [5635, 8390, 3], [8390, 11170, 4], [11170, 15194, 5], [15194, 18198, 6], [18198, 21019, 7], [21019, 23730, 8], [23730, 26198, 9], [26198, 29243, 10], [29243, 31919, 11], [31919, 34250, 12], [34250, 37091, 13], [37091, 40360, 14], [40360, 43419, 15], [43419, 46511, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46511, 0.01253]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
90ea99c68d814a4642f747a685f53df58e52efef
|
Microarchitectural Implications of Event-driven Server-side Web Applications
Yuhao Zhu Daniel Richins Matthew Halpern Vijay Janapa Reddi
The University of Texas at Austin, Department of Electrical and Computer Engineering
{yzhu, drichins, matthalp}@utexas.edu, vj@ece.utexas.edu
Abstract
Enterprise Web applications are moving towards server-side scripting using managed languages. Within this shifting context, event-driven programming is emerging as a crucial programming model to achieve scalability. In this paper, we study the microarchitectural implications of server-side scripting, JavaScript in particular, from a unique event-driven programming model perspective. Using the Node.js framework, we come to several critical microarchitectural conclusions. First, unlike traditional server-workloads such as CloudSuite and BigDataBench that are based on the conventional thread-based execution model, event-driven applications are heavily single-threaded, and as such they require significant single-thread performance. Second, the single-thread performance is severely limited by the front-end inefficiencies of today’s server processor microarchitecture, ultimately leading to overall execution inefficiencies. The front-end inefficiencies stem from the unique combination of limited intra-event code reuse and large inter-event reuse distance. Third, through a deep understanding of event-specific characteristics, architects can mitigate the front-end inefficiencies of the managed-language-based event-driven execution via a combination of instruction cache insertion policy and prefetcher.
Categories and Subject Descriptors
C.1 [Processor Architecture]: General
Keywords
Microarchitecture, Event-driven, JavaScript, Prefetcher
1. Introduction
Processor architecture advancements have been largely driven by careful observations made of software. By examining and leveraging the inherent workload characteristics, such as instruction-, thread-, and data-level parallelism, processor architects have been able to deliver more efficient computing by mapping software efficiently to the hardware substrate. We must continue to track the developments in the software ecosystem in order to sustain architecture innovation.
At the cusp of the software evolution are managed scripting languages, which provide portability, enhanced security guarantees, extensive library support, and automatic memory management. In particular, JavaScript is the peak of all the programming languages, surpassing C, C++, and Java to be the most widely used language by developers [1]. From interactive applications in mobile systems to large-scale analytics software in datacenters, JavaScript is ushering in a new era of execution challenges for the underlying processor architecture.
In this paper, we focus on server-side JavaScript, specifically its implications on the design of future server processor architectures. While there are numerous studies that have focused on various aspects of dynamic languages on hardware, such as garbage collection [2], type checking [3], exploiting parallelisms [4, 5], and leveraging hardware heterogeneity [6], we study the implications of the programming model that is emerging in server-side JavaScript applications, i.e., asynchronous event-driven programming.
In server-side asynchronous event-driven programming [7, 8], user requests are treated as application events and inserted into an event queue. Each event is associated with an event callback. The event-driven system employs a single-threaded event loop that traverses the event queue and executes any available callbacks sequentially. Event callbacks may initiate additional I/O events that are executed asynchronously to the event loop in order to not block other requests. The event-driven model has a critical scalability advantage over the conventional thread-based model because it eliminates the major inefficiencies associated with heavy threading, e.g., context switching and thread-local storage [9, 10]. Thus, the event-driven model has been widely adopted in building scalable Web applications, mainly through the Node.js [11] framework.
We find that event-driven server applications are fundamentally bounded by single-core performance because of their reliance on the single-threaded event loop. However, unlike conventional single-threaded benchmarks (e.g., SPEC CPU 2006) for which current processor architectures are highly optimized, event-driven server applications suffer from severe microarchitecture inefficiencies, particularly front-end bottlenecks, i.e., high instruction cache and TLB misses and branch misprediction rate. Moreover, unlike conventional heavily threaded enterprise workloads that also suffer from front-end
issues, the front-end bottleneck of an event-driven server application stems from the single-threaded event execution model, rather than microarchitectural resources being clobbered by multiple threads. With the front-end constituting up to half of the execution cycles, it is clear that current server processor designs are suboptimal for executing event-driven workloads.
To improve the front-end efficiency of event-driven server applications, we study them from an event perspective. We find that the severe front-end issue arises fundamentally because events have large instruction footprints with little intra-event code reuse. Recent studies on client-side event-driven applications also derive similar conclusions [12, 13]. We take this research a step further to make the key observation that event-driven programming inherently exposes strong inter-event code reuse. Taking the L1 I-cache as a starting point, we show that coordinating the cache insertion policy and the instruction prefetcher can exploit the unique inter-event code reuse and reduce the I-cache MPKI by 88%.
In summary, we make the following contributions:
- To the best of our knowledge, we are the first to systematically characterize server-side event-driven execution inefficiencies, particularly the front-end bottlenecks.
- We tie the root-cause of front-end inefficiencies to characteristics inherent to the event-driven programming model, which gives critical microarchitectural optimization insights.
- We show that it is possible to drastically optimize away the instruction cache inefficiencies by coordinating the cache insertion policy and prefetching strategy.
The remainder of the paper is structured as follows. Sec. 2 provides a background into asynchronous event-driven programming and why it has emerged as a crucial tipping point in server-side programming. Sec. 3 presents the workloads we study and shows the event-driven applications’ single-threaded nature. Sec. 4 discusses our microarchitecture analysis and presents the extreme front-end bottlenecks. Sec. 5 shows that it is possible to leverage the inherent event-driven execution characteristics to largely mitigate instruction cache inefficiencies through a combined effort between cache insertion policy and a suitable prefetcher. Sec. 6 discusses the related work, and Sec. 7 concludes the paper.
2. Background
Web applications employ server-side scripting to respond to network requests and provide dynamic content to end-users. The traditional approach to providing responsiveness to end-users at scale has been thread-based programming, i.e., to increase the number of threads as the number of incoming requests increases. Recently, because of several fundamental limitations of heavy multi-threading that limit system scalability, many industry leaders, such as eBay, PayPal, and LinkedIn, have started to adopt event-driven programming as an alternative to achieve scalability more efficiently.
In this section, we first discuss thread-based execution and its limitations (Sec. 2.1). On that basis, we explain why event-driven programming is emerging as an alternative for developing large-scale Web applications (Sec. 2.2).
2.1. Thread-based Programming
Traditional server-side scripting frameworks, such as PHP and Ruby, pair user requests with threads, commonly known as the “thread-per-request” or “single-request-per-script” execution model. These thread-based execution models, shown in generality in Fig. 1, consist of a dispatch thread that assigns each incoming request to a worker thread for processing. The result is that at any given time, the server abounds with the same number of threads as the number of requests.
While the thread-based execution model is intuitive to program with, it suffers from fundamental drawbacks. As the number of client requests increases, so does the number of active threads in the system. As a result, the operating system overhead, such as thread switching and aggregated memory footprint, grows accordingly. Therefore, operating systems typically have a maximum number of threads that they support, which fundamentally limits the server scalability [10].
To address the scalability limitations of thread-based execution on a single node, modern datacenters scale-out the hardware resources. Instead of scaling the number of threads on a single compute node, threads are distributed and balanced across a large number of compute nodes. However, increasing the number of physical compute nodes has direct financial im-
which is the most popular server-side event-driven platform
the conventional thread-per-usage scenarios of these applications (Sec. 3.2).
We then describe how we generate loads to study realistic efficiency and scalability of their application services [21, 22, eBay, PayPal, and LinkedIn have adopted it to improve the based on JavaScript [11]. Numerous companies [23] such as
represent them (Sec. 3.1). These applications use
driven programming and describe the workloads we use to
investigated in the past. In this section, we identify several important Web application domains that have embraced event-driven designs for large-scale Web applications.
2.2. Event-driven Programming
A more scalable alternative to the conventional thread-per-request execution model is event-driven execution, as employed in Node.js [11]. Fig. 2 shows the event-driven execution model. Incoming I/O requests are translated to events, each associated with an event handler, also referred to as a callback function. Events are pushed into an event queue, which is processed by the single-threaded event loop. Each event loop iteration checks if any new I/O events are waiting in the queue and executes the corresponding event handlers sequentially. An event handler may also initiate additional I/O operations, which are executed asynchronously with respect to the event loop in order to free the main event loop.
Event-driven server designs achieve orders of magnitude performance improvements over their thread-based counterparts in both industry [21, 22] and academia [9, 10], because they are not limited by the number of threads a system supports. Rather, their scalability depends on the performance of the single-threaded event loop. As such, event-driven programming restores the emphasis on scale-up single-core processor designs for large-scale Web applications.
3. Event-driven Server Applications
Event-driven server-side scripting has not been extensively investigated in the past. In this section, we identify several important Web application domains that have embraced event-driven programming and describe the workloads we use to represent them (Sec. 3.1). These applications use Node.js, which is the most popular server-side event-driven platform based on JavaScript [11]. Numerous companies [23] such as eBay, PayPal, and LinkedIn have adopted it to improve the efficiency and scalability of their application services [21, 22, 24]. We then describe how we generate loads to study realistic usage scenarios of these applications (Sec. 3.2).
<table>
<thead>
<tr>
<th>Workload</th>
<th>Domain</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Etherpad Lite</td>
<td>Document Collaboration</td>
<td>An online word processing engine, similar to services such as Google Docs and Microsoft Office Online, for real-time document editing and management. The users we simulate create documents, add and edit document contents, and delete documents.</td>
</tr>
<tr>
<td>Let’s Chat</td>
<td>Messaging</td>
<td>Multi-person messaging platform, akin to Google Chat and WhatsApp, where users participate in group chats. Each enters a group chat and then sends and receives messages.</td>
</tr>
<tr>
<td>Lighter</td>
<td>Content Management</td>
<td>A blogging platform comparable to Blogspot. Each of the users requests resources, such as HTML, CSS, JavaScript, and images, corresponding to blog post webpages.</td>
</tr>
<tr>
<td>Mud</td>
<td>Gaming</td>
<td>A real-time multi-user dungeon game with multiple users playing the game simultaneously.</td>
</tr>
<tr>
<td>Todo</td>
<td>Task Management</td>
<td>A productivity tool and service, similar to the Google Task list management service within Gmail. Users create, modify, and delete multiple tasks within their task lists.</td>
</tr>
<tr>
<td>Word Finder</td>
<td>API Services</td>
<td>A word search engine that finds words matching a user-specified pattern. The pattern is searched against a 200,000-word corpus. Users execute several pattern queries.</td>
</tr>
</tbody>
</table>
Given the selected applications and their loads, we conduct system-level performance analysis on the Node.js software architecture to understand its various applications’ execution behaviors (Sec. 3.3). The key observation is that while Node.js is multi-threaded, the single-threaded event loop that sequentially executes all the event callbacks dominates the CPU time. We use this observation as our rationale to focus on analyzing the event loop execution in the rest of the paper.
3.1. Workloads
We study important Web application domains that have begun to adopt event-driven programming on the server-side, as shown in Table 1. To enable future research, as well as for reproducibility of our results, we intentionally choose applications that are open-sourced. We release the workload suite at https://github.com/nodebenchmark.
Document Collaboration Services such as Google Docs and Microsoft Office Online allow multiple users to collaborate on documents in real-time. As users edit documents, they communicate with the application server to report document updates. We study Etherpad Lite [14], a real-time collaborative text editing application. Each user creates a new document, makes several edits to that document, and then finally deletes it once all edits have been made.
Messaging Messengers are amongst the most popular applications used today [25]. Each user sends and receives messages by communicating with the application server that manages a message database. We study the Let’s Chat [15] messaging application. Each user initiates a new chat, sends multiple messages to other users, and exits the service.
Content Management Many applications and services from news outlets (e.g. CNN) to blogging platforms (e.g. WordPress) rely on content management platforms to serve a variety of file resources to users. We study Lighter [16], which is a blogging platform that serves webpage resources corresponding to a blog post. We focus on users who request different blog entry resources using a regular Web browser.
Gaming Online computer gaming, already very popular, is increasingly moving to support multiplayer interaction. These
games, such as Farmville and Words With Friends, have to manage the shared game state across multiple users. We study the multiplayer game Mud [17], wherein each player is assigned a position on a grid. The players can then update their positions to navigate the environment.
**Task Management** Cloud-based task management tools such as Asana and Trello have become increasingly popular for organizations and individuals to stay organized. Tasks can be created, modified, and deleted based on what the user desires. We study a simplified form of task management, using the Todo [18] task management application. Users can create, view, and modify various tasks in a task list.
**API Services** Third-party API services provide functionalities that otherwise would not be available in an application. On such example is the Google autocomplete API that aids applications automatically filling out forms [26]. We restrict our study to Word Finder [19]. It is a pattern matching API service used for autocompletion and spell checking. Each user queries the API with various word patterns, which are matched against an English dictionary of 200,000 words.
### 3.2 Load Generation
Our study is focused on processor design at the microarchitecture level, thus we focus on a single instance of Node.js. Typically, a production server will run multiple instances of Node.js to handle a massive number of requests [27]. However, by design, a single instance of Node.js runs primarily in a single thread, coupled with a handful of helper threads.
All of our applications run at the most recent stable software release of Node.js at the time of writing (version 0.12.3). To exercise the Node.js applications, we develop a query generator to emulate multiple users making requests to the Node.js application under study. We model individual users making requests to the server under realistic usage scenarios, which we obtain by observing requests made by real users. We also interleave and serialize concurrent user requests to the server. This does not change the internal execution characteristics of Node.js application—because events will eventually be serialized by the single-threaded event loop—but enables crucial reproducibility across experiments. Unless otherwise noted, our results are based on simulating 100 users to minimize experiment runtime, as our detailed microarchitectural analyses are based on simulations. We verified that load-testing with a larger number of users or using different request interleavings did not change the results and conclusions presented throughout the paper.
### 3.3 Performance Analysis
In order to understand how these applications exercise the Node.js runtime and guide the simulations used throughout the remainder of the paper, we conduct a system-level performance analysis using the Intel VTune system profiler tool on a quad-core Intel i5 processor. Because we are running on real hardware, in this section we are able to conduct performance analysis using 100,000 users for each application.
While Node.js is actually multi-threaded, we find that the execution time of each Node.js application is primarily compute-bound within the single-threaded event loop that is responsible for executing JavaScript-based event callbacks. Our measured results emphasize the need to deeply understand the event-driven execution nature of these workloads.
**Event Loop** Although the Node.js architecture possesses multiple threads for handling asynchronous I/O, its computation is bounded by the single-threaded event loop. The thread-level parallelism (TLP [28]) column in Table 2 shows that Node.js applications are effectively single-threaded, indicating the importance of single core performance. This aligns with the experience reported from industry [24, 29].
To further understand the importance of single core performance, we study the compute versus memory boundedness of the single-threaded event loop by measuring how the performance changes with the CPU frequency. Fig. 4 shows each application’s normalized execution time as the CPU frequency scales from the peak (3.2 GHz) down to 50%. We observe that the overall performance scales almost linearly with the CPU frequency. For example, for Mud, halving the CPU frequency translates to almost 2X slowdown, emphasizing the importance of single-core performance.

Due to the dominant nature of the event loop thread, we provide an execution breakdown of the event loop for all Node.js applications in Fig. 3. We divide the event loop execution time into four major categories: event callback execution, event loop management (through libuv [30]), idle, and other. We see that event callback execution dominates the event loop execution time. It consumes between 85% (Let’s Chat) and nearly 100% (Word Finder) of the event loop execution time. In contrast, the event loop management overhead is minimal. In all applications but Mud, the event loop management is responsible for less than 1% of the execution time. Idleness due to I/O is also relatively small across all of the applications. Except for Let’s Chat whose idleness is 10%, the other applications exhibit idleness of less than 5%.
Event Callbacks
Because of the dominance of event callback execution in the event loop thread, we provide further details of callback execution behaviors. Event callbacks are written in JavaScript. To execute event callbacks, Node.js relies on Google’s V8 JavaScript engine [31]. V8 supports JavaScript callback execution through various functionalities such as just-in-time (JIT) compilation, garbage collection, and built-in libraries. Table 2 dissects the callback function execution time into three major categories. Generated indicates the execution of dynamically compiled code of callback functions. VM corresponds to the virtual machine management such as garbage collection and code cache handling. Code-Gen corresponds to the JIT compilation.
We make two important observations. First, the majority of the callback time is spent executing the application code (Generated). Second, V8 spends little time generating code (Code-Gen), with the largest time spent in Let’s Chat at 5.3%. This is important to verify because it confirms that our analysis is conducted on each application’s steady state, which is the normal state for server applications.
### 4. Microarchitectural Analysis
Given the single-threaded nature of the event loop, we conduct microarchitectural analysis to identify the bottlenecks for efficient processing of event-driven server applications. We conduct microarchitectural bottleneck analysis using cycle-per-instruction (CPI) statistics to show that instruction delivery dominates execution overhead (Sec. 4.1). Our finding motivates us to perform analysis on the three major microarchitectural structures that impact instruction delivery efficiency: the L1 I-cache (Sec. 4.2), branch predictor (Sec. 4.3), and L1 I-TLB (Sec. 4.4) to understand execution behavior.
Throughout our analysis, we compare the Node.js applications against SPEC CPU 2006 because the latter has long been the de facto benchmark for studying single-threaded performance. A head-to-head comparison between Node.js and SPEC CPU 2006 workloads reveals critical insights into the unique microarchitecture bottlenecks of Node.js. Other server-side applications, such as CloudSuite [32], MapReduce [33], BigDataBench [34], and OLTP [35] do not specifically emphasize single-thread performance.
We focus on CPU microarchitecture due to the importance of single-core performance. Hence, our experimental setup is geared toward studying core activities and does not capture the I/O effects (i.e., storage and network). Node.js applications may also be I/O intensive. However, a complete I/O characterization is beyond the scope of our paper.
#### 4.1. Microarchitectural Bottleneck Analysis
We analyze the microarchitecture bottlenecks for event-driven Node.js applications by examining their cycle-per-instruction (CPI) stacks. A CPI stack breaks down the execution time of an application into different microarchitectural activities (e.g., accessing cache), showing the relative contribution of each activity. Optimizing the largest component(s) in the CPI stack leads to the largest performance improvement. Therefore, CPI stacks are used to identify sources of microarchitecture inefficiencies [36, 37].
We use SniperSim [38] to simulate all the Node.js applications and generate their corresponding CPI stacks. The CPI stack for the main event loop thread within each application is shown in Fig. 5. Components on each bar represents the percentage of cycles that an application spends on a particular type of microarchitectural activity. For example, the base component represents an application’s execution time if there were no pipeline stalls. The *ifetch* and *branch* components indicate the total processing overhead due to instruction cache misses and branch mispredictions, respectively. The *mem-* components indicate the time spent accessing different memory hierarchy levels. The *sync-* and *imbalance-end* components correspond to multithreaded execution overheads.
We make two observations from Fig. 5. First, about 80% of the processing time is spent on various types of on-chip microarchitectural activities. Amongst all sources of overall processing overhead, fetching instructions (*ifetch*) and branch
prediction (branch) emerge as the two most significant sources. These two components alone contribute about 50% of the total execution overhead, which implies that delivering instructions to the backend of the pipeline is of critical importance to improve the performance of event-driven Node.js applications.
Second, the processing overhead for synchronization (sync-sleep and sync-futex) is negligible. We corroborate this result by performing VTune analysis on 50,000 users. We find that the time spent on synchronization is only about 0.5%. This is not an unexpected result because Node.js uses a single thread to execute event callbacks, and all I/O operations are asynchronous without having to explicitly synchronize. This implies that improving the performance of synchronization primitives in the processor will likely not yield much benefit for event-driven server applications.
Thus, we devote the rest of the section to performing detailed analysis on the three microarchitectural resources that significantly impact the front-end’s execution efficiency: the L1 instruction cache and L1 instruction TLB (for instruction fetching) and the branch predictor (for branch prediction).
4.2. Instruction Cache Analysis
To understand the front-end execution inefficiency of Node.js applications, we start by examining the workloads’ instruction cache (I-cache) behavior. We sweep a wide range of cache configurations in order to study the workloads’ instruction footprints. We show that all the Node.js applications suffer from significantly higher misses per kilo-instruction (MPKI) than the vast majority of SPEC CPU 2006 applications on a standard cache configuration. To achieve SPEC CPU-like MPKI, the processor core would require an I-cache so large that it cannot be practically implemented in hardware.
**Current Design Performance Implications** We study a modern CPU cache with 32 KB capacity, 64-byte line size, and 8-way set associativity. At this default configuration, we examine the I-cache’s efficiency using the MPKI metric. We compare the Node.js programs against the SPEC CPU 2006 workloads’ MPKIs, and present the results in Fig. 6a.
We make two important observations. First, the average I-cache MPKI of Node.js applications is 4.2 times higher than that of the SPEC applications. Even Etherpad, which has the lowest I-cache MPKI of all the Node.js applications, shows over twice the MPKI of the SPEC average (indicated by the horizontal dotted line in the figure). At the other extreme, Word Finder and Mud have I-cache MPKIs higher than all but one of the SPEC applications.
Second, the typical behavior of event-driven applications is on par with the worst-case behavior of single-threaded SPEC CPU 2006 applications that are known to stress the microarchitecture. The event-driven Node.js applications have MPKIs comparable to some of the worst MPKI of SPEC applications, such as gobmk, omnetpp, and cactusADM.
To understand the reason for the poor I-cache performance, we study the instruction reuse distance to quantify the applications’ working set size. Reuse distance is defined as the number of distinct instructions between two dynamic instances of the same instruction [39]. Fig. 7 shows the instruction reuse distances for all of the Node.js application. Each \((x, y)\) point corresponds to the percentage of instructions \(y\) that are at or below a particular reuse distance \(x\). For comparative purposes, we also include two extreme applications from the SPEC CPU 2006 suite: lbm has the lowest I-cache MPKIs and omnetpp suffers from the one of the highest I-cache MPKIs.
The event-driven Node.js applications have very large reuse distances. The instruction footprint of omnetpp, the worst SPEC CPU 2006 application, can be effectively captured within a reuse distance of \(2^{11}\). In our measurement, the average instruction size is about 4 bytes; this means an I-cache of just 8 KB would be sufficient to capture omnetpp’s instruction locality (assuming a fully-associative cache). In contrast, Let’s Chat has a significantly larger reuse distance of up to \(2^{18}\) instructions, requiring a cache of 1 MB to capture.
For comparison purposes, we also examine the data cache behavior of Node.js applications, and compare and contrast it against the SPEC CPU 2006 applications. Fig. 6b shows the D-cache MPKI of Node.js and SPEC CPU 2006 applications. Event-driven Node.js applications do not appear to stress the data cache heavily. All the Node.js applications have MPKIs that are significantly lower than the SPEC CPU average. Even the extreme cases, Word Finder and Mud, which have the highest MPKIs of 37 and 34, are comparable to the lowest MPKI of SPEC CPU applications.
**Ideal Resource Requirements** To determine the ideal instruction cache resource requirements for our event-driven Node.js applications, we sweep the I-cache size and determine application sensitivity under a variety of resource configurations. We find that the instruction working set sizes approach 1 MB, which far exceeds the typical L1 cache capacity.
In Fig. 8, the cache size is swept from 16 KB to 1024 KB on the x-axis (in log-scale) and the resulting MPKIs of the Node.js applications are shown on the y-axis. The SPEC CPU 2006 average I-cache MPKI for a cache of 32 KB is indicated by the horizontal dotted line.
The most significant observation from Fig. 8 is that the I-cache MPKI keeps improving as the cache size increases for all of the Node.js applications. Some applications such as Word Finder and Etherpad show a knee in their MPKIs at the 128 KB cache size. However, it is not until 256 KB, or even 512 KB, that all the event-driven applications have MPKIs that are comparable to the SPEC CPU 2006 average. Such a large L1 I-cache is infeasible for practical implementation.
Instruction cache performance on the event-driven applications cannot be easily improved by adjusting conventional cache parameters, such as line size and associativity. Using Mud, which has an MPKI close to the average of all Node.js applications, as an example, Fig. 9 shows the impact of line size and associativity while keeping the same cache capacity. The line size is held constant while sweeping the associativity from 4 to 16 ways, and then holding the associativity at 8 ways while sweeping the line size from 32 to 128 bytes. The I-cache MPKI is improved when the two parameters are properly selected. For example, increasing the line size from 64 bytes to 128 bytes improves the MPKI by nearly 25%, indicating that Node.js applications exhibit a noticeable level of spatial locality in their code execution behavior. However, the 43 MPKI on a 128-byte line is still significantly higher than the average 14 MPKI of SPEC CPU 2006 applications.
Comparing the impact of the two parameters, cache line size and associativity, changing the associativity has less impact than changing the cache line size. Increasing the cache associativity actually worsens the MPKI on average by about 10 for Mud. Between increasing associativity and line size while keeping the cache size the same, increasing the line size to capture spatial locality is a better design trade-off than increasing the associativity to reduce cache conflict misses. But even this cannot reduce the cache misses to the average level of SPEC CPU 2006 workloads. The difference is still as much as two orders of magnitude or more.
### 4.3. Branch Prediction Analysis
Event-driven Node.js applications suffer from bad branch prediction performance. Such behavior stems from the large number of branch instructions in the Node.js applications. In SPEC CPU 2006, only 12% of all dynamic instructions are branches. In Node.js applications, 20% of all instructions are branches. As such, different branch instructions tend to alias into the same branch prediction counters and thus are likely to pollute each other’s predictions. We further show that reducing branch aliasing by attempting to simply scale the branch predictor structures would require excessive resources that are infeasible to implement.
**Current Design Performance Implications**
We compare Node.js applications with SPEC CPU 2006 applications under three common branch predictor designs—global, local, and tournament predictor. Intel and AMD do not provide the necessary details to mimic the actual implementation. However, they do provide sufficient information about program optimization [40] that indirectly indicate reasonable predictor parameters. Based on those informational resources, we mimic branch predictor parameters that are typically adopted in today’s processors. For all three predictors, we use history registers of 12 bits, which leads to 4 K unique bimodal predictors. The local predictor is configured to use 256 local branch histories. The tournament predictor further utilizes another 4 K bimodal prediction array of its own.
Branch misprediction results are shown in Fig. 10. We draw two conclusions. First, even under the best-performing predictor (the tournament predictor), Node.js applications have an average misprediction rate (8.8%) over 2 times higher than that of SPEC CPU (3.7%). Four Node.js applications (Todo, Mud, Let’s Chat, and Lighter) are as hard to predict as the hardest of the SPEC CPU programs (e.g., gobmk and astar).
Second, the performance difference between the local and global predictors depends heavily on the applications. There-
fore, a tournament predictor is necessary to achieve better prediction results. The local predictor is equivalent to or more accurate than the global predictor for Word Finder and Etherpad but performs worse in the other four applications.
To understand the high branch misprediction rate for the event-driven applications, we study the possibility for destructive branch aliasing to occur. Destructive branch aliasing arises when two or more branch instructions rely on the same prediction counter. We quantify branch aliasing by capturing the number of unique branches between two dynamic instances of the same branch instruction being predicted. We call this number the “branch aliasing distance,” which, conceptually, is similar to instruction reuse distance that indicates the number of unique instructions that occur between two dynamic instances of a specific static instruction.
We bin the branch aliasing distance of all the bimodal predictors into 18 bins, each represents a single distance from 0 to 16 and 17+. Zero-aliasing distance is ideal because it indicates that the branch predictor predicts for the same branch instruction back-to-back without any intervening interference from the other branches. A non-zero value for the reuse distance indicates the degree of branch aliasing.
Fig. 11 shows the branch aliasing distances for Node.js applications. It also includes the average for SPEC CPU 2006 applications. Each (x, y) point in the figure corresponds to the percentage of dynamic branch instruction instances (y) that are at a particular branch aliasing distance (x).
Node.js applications suffer from heavier branch aliasing than SPEC CPU 2006. For the global predictor, Fig. 11a shows that about 90% of the branch predictions in the SPEC applications have zero-aliasing distance. By comparison, in the Node.js applications that figure drops to about 60%. Furthermore, about 10% of the predictions in Node.js applications have an aliasing distance 17+. SPEC has none that far.
The contrast between Node.js and SPEC applications is more prominent in the local predictor (Fig. 11b). Over 50% of the Node.js predictions have aliasing distance 17+ while only about 10% do in the SPEC applications. The local aliasing is higher than the global aliasing because local histories are more varied than the global history. Note that we omit the tournament predictor’s aliasing as it is indexed identically to the global predictor and so would produce the same results.
**Ideal Resource Requirements** To determine whether scaling the hardware resources will address the branch prediction and aliasing issues, we sweep the global and local predictor sizes. Even with much larger predictors, the full set of Node.js applications never becomes universally well-predicted.
Fig. 12a shows the misprediction rates of the Node.js applications as the number of prediction table entries in the global predictor changes from 128 \( (2^7) \) to 64 K \( (2^{16}) \). Even with 64 K entries, Word Finder, Todo, Let’s Chat, and Lighter still exceed the average SPEC CPU 2006 misprediction rate at the much smaller 4 K entry predictors. In addition, for most of the applications, as predictor size increases, we observe a remarkably linear trend without a knee of the curve. This indicates that the branch misprediction is far entering the diminishing return area, and further reducing the misprediction requires significantly more hardware resources.
Local predictor trends are similar to the global predictor trends. Fig. 12b shows the misprediction rates as the number of unique instructions that occur between two dynamic instances of a specific static instruction.
of local histories increases from 128 (2^7) to 16 K (2^{14}). *Mud* is a notable example in that it approaches the prediction accuracy of *Word Finder* and *Etherpad*, which are the easier to predict (see Fig. 10). The remaining three applications, however, require heavy branch prediction hardware investment to even approach the average of SPEC CPU 2006 applications.
### 4.4. Instruction TLB Analysis
Traditionally, I-TLBs have not been the primary focus in TLB-related studies due to their extremely low miss rates [41–43]. However, I-TLB performance is crucial because every instruction fetch requires a TLB lookup, and TLB misses result in expensive page table walks. Our analyses show that the event-driven *Node.js* applications suffer from high I-TLB misses. Scaling the number of TLB entries reduces the miss ratio, but only at prohibitive hardware cost.
**Current Design Performance Implications** We simulate a TLB using a Pin tool that resembles the TLB found in modern Intel server processors with 64 entries and 4-way set associativity. Because TLB results are typically sensitive to system-level activities and Pin only captures user-level code, we validated our tool’s accuracy using hardware performance counters. Its accuracy is within 95% of the measured hardware TLB results on an Intel processor.
The I-TLB MPKIs of *Node.js* applications dwarf those of the SPEC CPU 2006 suite. Fig. 13a compares the I-TLB MPKI of *Node.js* applications with the SPEC applications. SPEC applications hardly experience any I-TLB misses whereas almost all *Node.js* applications have close to 3 MPKI. In stark contrast, *Node.js* applications fall far short of the worst applications in SPEC in terms of D-TLB MPKIs. As Fig. 13b shows, *Node.js* are roughly comparable to the average D-TLB miss rate of SPEC applications.
To understand whether the poor I-TLB performance is caused by a large code footprint, we analyze the contribution of static code footprint to dynamic instruction execution behavior. Specifically, we study if the event-driven *Node.js* applications contain a few hot instructions or a lot of cold instructions that contribute to a majority of the dynamic instructions that impact the TLB’s performance.
We discover that *Node.js* applications have a small number of hot instructions that contribute to a large percentage of the total dynamic instruction count. Fig. 16 shows the hotness of static instructions as a cumulative distribution function. On average, 5% of the static instructions are responsible for 90% of the dynamic instructions. This behavior is similar to many SPEC CPU 2006 applications whose code footprints are attributed to a few hot static instructions [44] and yet do not suffer from poor I-TLB performance.
The data in Fig. 16 suggests that the poor I-TLB performance of *Node.js* applications is not due to a lack of hot code pages; rather it must be due to the poor locality of execution. Sec. 3.3 showed that the *Node.js* applications rely heavily on native call bindings that are supported by the V8 VM, thus we hypothesize that the user-level context switches between the *Node.js* event callbacks and native code (inside the VM) are the main reason for the poor I-TLB performance.
**Ideal Resource Requirements** The event-driven *Node.js* applications require unconventionally large I-TLB sizes to achieve SPEC-like I-TLB performance. Fig. 14 shows the I-TLB behavior as the TLB size is progressively increased from 8 to 512 entries. In order to get SPEC-like behavior (indicated by the arrow and so close to the 0 line as to be nearly indistinguishable from it), the I-TLB would have to be increased to 256 or more entries.
Building such a large I-TLB is inefficient. Current TLB lookups already impose non-negligible energy costs, and therefore scaling the TLB sizes will likely increase energy per access [45, 46]. In fact, TLB sizes have largely remained stable over the past several generations [47].
The alternative to increasing the TLB size is to use superpages. In event-driven applications, switching to a large page size reduces the MPKI significantly. Fig. 15 compares the I-TLB MPKI under 4 KB and 2 MB (i.e., superpage) page sizes. Although superpages are traditionally used for reducing D-TLB misses [43, 48], our results indicate that large pages would be helpful for improving I-TLB performance.
### 5. Event-based Optimizations
To improve the execution efficiency of event-driven applications, we must mitigate several front-end inefficiencies. However, given all of the major bottlenecks in the front-end, this section specifically focuses on alleviating the instruction cache inefficiencies. The insights are likely to be generalizable to other structures (i.e., TLB and branch predictor).
We study I-cache misses from an event callback perspective. We find that individual events have large instruction footprints...
with little reuse, which leads to cache thrashing. Fortunately, event-driven programming inherently exposes strong inter-event instruction reuses (Sec. 5.1). Such heavy inter-event instruction reuse exposes a unique opportunity for improving the instruction cache performance. We demonstrate that it is necessary to coordinate cache insertion policy and instruction prefetcher (Sec. 5.2). The combined efforts reduce the instruction cache MPKI by 88% (Sec. 5.3).
### 5.1. Optimization Opportunity
We examine event execution along two important dimensions to discover opportunities for mitigating I-cache inefficiencies: intra-event and inter-event. In the intra-event case, execution characteristics correspond to one event, whereas in inter-event execution the characteristics correspond to the shared execution activity across two or more events.
We analyze intra-event and inter-event instruction reuse to understand the poor I-cache behavior of event-driven applications. Fig. 17 shows the percentage of instructions (y-axis) that are reused a certain amount of times (x-axis) both within and across events for all six Node.js applications. The reuses are reported as buckets on the x-axis. The $n^{\text{th}}$ bucket represents reuses between $X_{n-1}$ and $X_n$ with the exception of the first bucket, which represents less than 32 reuses and the last bucket which represents 256 or more reuses.
When we consider the event callbacks in isolation (i.e., intra-event) almost 100% of the instructions across all the Node.js are reused less than 32 times. The low intra-event reuse is inherent to event-driven programming. Developers consciously program the event callbacks to avoid hot, compute-intensive loops to ensure application responsiveness. Recall that events in the event queue are executed sequentially by the single-threaded event loop, thus all of the events must execute quickly, similar to interrupts (Sec. 3.3).
When the low intra-event code reuse is coupled with the large instruction footprint of each event, it leads to the large instruction reuse distance that results in poor I-cache performance (as previously shown in Fig. 7). In Fig. 18, we show the code footprint (i.e., total byte size of static instructions) for all the events in each application. Each $(x, y)$ point in the figure indicates the percentage of events $(x)$ whose footprints are at or below a particular size $(y)$. We overlay a 32 KB line marker to indicate the L1 I-cache capacity. Almost all of the events have a footprint greater than the standard 32 KB I-cache capacity. In some events, the footprints exceed 1 MB.
In contrast, instruction reuse is much higher for inter-event application activity. Fig. 17 shows that over 40% of the instructions are reused over 256 times in the inter-event case. Such frequent reuse implies that events share a considerable number of instructions, otherwise the inter-event behavior would be similar to intra-event behavior.
Inter-event reuse is the direct result of the event-driven programming paradigm: events exercise the same JavaScript runtime features, which provides support for compiler optimizations, inline cache handling, garbage collection, various built-in functions, etc.
To quantitatively demonstrate that different events indeed share similar code paths within V8’s VM, we show instruction-level similarity between different events. Fig. 19 is a heat map where each $(i, j)$ point in the figure corresponds to an event pair $(i, j)$, where event $i$ appears earlier than event $j$ in the application. Each $(i, j)$ point indicates the percentage of V8 instructions that event $j$ uses that can also be found in event $i$. The darkness of the heatmap at any given point is proportional to the percentage of code sharing between those two events, as indicated by the color scale on the right side of the figure. For the purposes of presentation, we limit the data in the figure to 100 randomly chosen consecutive events. We verified that the results hold true when we expand the graph to include all events in the application. The figure confirms that most of the events share close to 100% of the V8 code.
### 5.2. Optimization Strategy
The low intra-event reuse coupled with large event footprints suggests that even an optimal cache cannot fully capture the entire working set of all the events. However, the heavy inter-event reuse indicates the potential available locality. Intuitively, the instruction cache needs to first retain the “hot”
fraction of the event working set in the cache so that at least that portion reduces cache misses. In addition, it is necessary to deploy an instruction prefetcher that can always prefetch instructions that are not fully retained in the cache by capturing the instruction-miss sequence pattern.
**Caching** We propose to use the LRU Insertion Policy (LIP) [49] for the instruction cache (while still maintaining the LRU eviction policy) to retain the hot portion of the event footprint. LIP is known for being able to effectively preserve a subset of a large working set in the cache by inserting all the incoming cache lines into the LRU way instead of the MRU way and only promoting the LRU way to the MRU way if it has a cache hit. As such, the less frequently-used instructions that cause the instruction footprint to exceed the cache capacity will be quickly evicted from the LRU way instead of thrashing the cache. A critical advantage of LIP is that it requires little hardware and design effort and can be readily adopted in existing designs. LIP was originally proposed for last-level caches and used primarily for addressing large data working sets. To the best of our knowledge, we are the first to apply LIP to the instruction stream and show its benefits.
**Prefetching** Although LIP preserves a subset of event footprints in the I-cache, improvement is still fundamentally limited by cache capacity. As discussed in Sec. 4.2, simply increasing the cache size will lead to practical design issues. To compensate for cache capacity limitations, we must orchestrate the prefetcher to accurately fetch instructions in the miss sequence. Our key observation is that the instruction miss sequence in event-driven applications exhibits strong recurring patterns, primarily because inter-event execution has significant code similarities. For instance, as Fig. 19 shows, different events heavily share code from the V8 JavaScript engine.
To quantify the recurring patterns in Node.js applications, we perform oracle analysis to determine the number of repetitive patterns in the instruction cache miss sequence. We use the SEQUITUR [50] tool, which is widely used to detect patterns in a given stream, to analyze the instruction stream entry of an LIP cache. We classify instruction misses into three categories as originally defined in [51]. *Non-repetitive* misses do not belong to any recurring pattern. *New* misses are those instructions misses that appear in a pattern when it first occurs. The subsequent misses in an recurring pattern are classified as *Opportunity* misses.
The oracle repetitive pattern analysis results are shown in Fig. 20. For all the *Node.js* applications, over 50% of the cache misses are opportunity misses. This means up to 50% of the instruction misses can be eliminated if the prefetcher can capture all the recurring patterns and accurately match instruction misses to their corresponding patterns.
We propose to use the Temporal Instruction Fetch Streaming (TIFS) prefetcher [51] to prefetch recurring missing instructions. TIFS predicts and prefetches future instruction misses through recording and replaying the recurring instruction miss pattern. Specifically, it records all the missing instructions into an instruction missing log (IML). Upon an instruction miss, TIFS finds the location in IML where the miss address was most recently seen and begins prefetching subsequent instructions from the addresses in the IML.
### 5.3. Evaluations
We evaluate our proposal using an in-house instruction cache Pin tool. The reason we choose to only simulate the instruction cache is that it isolates other microarchitecture effects and provides crisp insights into the I-cache issue.
We implemented LIP as it was described by Qureshi et al. [49]. We do not find noticeable differences between LIP and the bimodal insertion policy (BIP) as observed for the LLC in [49]. Because of the additional hardware cost, we choose LIP instead of BIP. TIFS is implemented as described by Ferdman et al. [51]. We find that it is sufficient for the IML to keep track of 8 K instruction misses. More IML entries only lead to marginal improvements. The total storage overhead of TIFS is about 100 KB per core.
The baseline we compare against is the standard LRU cache with a 32 KB I-cache, 64-byte line size, and 8-way set associativity. We compare it with the following schemes. First, we compare it against an instruction cache with LIP insertion policy to understand the effectiveness of retaining the hot fraction of the event working set. Second, we compare it against a LIP-enabled cache with a next-line prefetcher to understand the effectiveness of retaining the hot fraction of the event working set. Third, we compare it against a LIP-enabled instruction cache enhanced with the TIFS prefetcher to understand the benefits of prefetching recurring instruction misses. Finally, we compare against a LIP instruction cache of 128 KB size without TIFS to understand whether the storage overhead introduced by TIFS can be simply used to increase the cache size.
The I-cache MPKI comparison results are shown in Fig. 21. We also overlay the average MPKI of SPEC CPU 2006 applications at 32 KB. We see that LIP drastically improves the MPKI by at least 45% and 70% on average compared to the LRU-only cache policy. Specifically, it records all the missing instructions into an instruction missing log (IML). Upon an instruction miss, TIFS finds the location in IML where the miss address was most recently seen and begins prefetching subsequent instructions from the addresses in the IML.
The TIFS-based instruction prefetcher reduces the MPKI by
another 60% on top of the cache improvements. As a comparison, using a next-line prefetcher only reduces the MPKI by 33.6%. With TIFS, all applications’ MPKI fall below SPEC CPU 2006’s average. This shows the necessity of capturing the instruction misses’ recurring pattern for prefetching. Combining the LIP cache with TIFS prefetching effectively reduces the L1 I-cache MPKI by 88%, which would otherwise be impossible to achieve without event-specific optimization. LIP+TIFS is almost as effective as an extremely large L1 I-cache. In all but one application (Mud), LIP+TIFS achieves an equivalent or better MPKI than a 128 KB I-cache.
Cost Analysis The cost of LIP is negligible. TIFS operations (e.g., logging miss sequences in IML, updating the Index Table) are off the critical path, following the general design principle of prefetching structures [52, 53]. Hence, TIFS is not likely to affect the cycle time. We also estimate that the additional power consumption of TIFS-related structures is only about 92 mW based on CACTI v5.3 [54].
6. Related Work
Characterization of Emerging Paradigms At the time multicore was starting to become ubiquitous on commodity hardware, Bienia et al. developed the PARSEC multicore benchmark suite [55]. Similarly, Ranger et al. characterized the implications of MapReduce applications when MapReduce was becoming prevalent in large-scale data-center applications. More recently, numerous research efforts have been devoted to characterizing warehouse-scale and big data workloads [32,34,35,56–58].
We address a new and emerging computing paradigm, i.e., event-driven programming, as others have done in other domains at the time those domains were becoming important. Although event-driven programming has existed for many years for highly concurrent server architecture [9,59,60], large-scale simulations [61,62], and interactive graphical user interface (GUI) application design [63], server-side event-driven applications that are tightly coupled with scripting languages have only recently become important. In this context, our work is the first to present a comprehensive analysis of the microarchitectural bottlenecks of scripting-language-based server-side event-driven applications.
Asynchronous/Event Execution Analysis Prior work on event-driven applications primarily focus on client-side applications [12,13] whereas we study server-side applications. While prior art also attributes front-end bottlenecks to little intra-event code reuse and proposes instruction prefetching and pre-execution techniques, we take the event-level analysis a step further to demonstrate heavy inter-event code reuse. As a result, we show that simple changes to the instruction cache insertion policy can drastically improve the front-end efficiency, even without the prefetching. Hempstead et al. [64] designed a specialized event-driven architecture for embedded wireless sensor network applications. Our work focuses on server-side event-driven programming and studies its implications on the general purpose processor. EBS [65] improves the energy-efficiency of client-side event-driven Web applications and is orthogonal to the performance study of our paper.
Scripting Languages Richards et al. explore language-level characteristics of client-side JavaScript programs [66]. Our work studies server-side JavaScript and focuses on the nature of events and their microarchitectural implications. Prior work on improving the performance of JavaScript, especially its dynamic typing system [3,67], complements our event-level optimizations. Ogasawara conducted source code analysis of server-side JavaScript applications, also using Node.js, and found that little time is spent on dynamically compiled code, leading to limited optimization opportunity [68]. We take an event perspective and demonstrate significant optimization opportunities by exploiting event-specific characteristics. In addition, the prior work does not focus on or investigate the microarchitectural implications of event-driven execution.
7. Concluding Remarks
As computer architects, it is important to understand how to optimize (micro)architecture in light of emerging application paradigms. This paper systematically studies microarchitectural implications of Node.js applications, which represent the unique intersection between two trends in emerging server applications: managed language systems and event-driven programming. We show that Node.js applications are bottlenecked by front-end inefficiencies. By leveraging heavy inter-event code reuse inherent to event-driven programming, we drastically improve the front-end efficiency by orchestrating the instruction cache insertion policy with an instruction prefetcher. Our results are readily useful for building an optimized server architecture for event-driven workloads and provide a baseline, which further research can build upon.
8. Acknowledgments
We are thankful to our colleagues as well as the anonymous reviewers for the many comments that have contributed to this work. This work is partially supported by AMD Corporation. Any opinions expressed in this material are those of the authors and do not necessarily reflect the views of the sponsors.
References
|
{"Source-Url": "http://3nity.io/~vj/downloads/publications/zhu15micro-eve.pdf", "len_cl100k_base": 11646, "olmocr-version": "0.1.49", "pdf-total-pages": 13, "total-fallback-pages": 0, "total-input-tokens": 47480, "total-output-tokens": 12655, "length": "2e13", "weborganizer": {"__label__adult": 0.0006380081176757812, "__label__art_design": 0.0008258819580078125, "__label__crime_law": 0.0004849433898925781, "__label__education_jobs": 0.001064300537109375, "__label__entertainment": 0.00020432472229003904, "__label__fashion_beauty": 0.00030994415283203125, "__label__finance_business": 0.0004668235778808594, "__label__food_dining": 0.0004863739013671875, "__label__games": 0.00124359130859375, "__label__hardware": 0.014404296875, "__label__health": 0.0008602142333984375, "__label__history": 0.0005960464477539062, "__label__home_hobbies": 0.0002027750015258789, "__label__industrial": 0.0012712478637695312, "__label__literature": 0.00030732154846191406, "__label__politics": 0.00037169456481933594, "__label__religion": 0.0007572174072265625, "__label__science_tech": 0.270751953125, "__label__social_life": 8.434057235717773e-05, "__label__software": 0.0084228515625, "__label__software_dev": 0.6943359375, "__label__sports_fitness": 0.00039124488830566406, "__label__transportation": 0.0012693405151367188, "__label__travel": 0.00034427642822265625}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59247, 0.01784]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59247, 0.34832]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59247, 0.90387]], "google_gemma-3-12b-it_contains_pii": [[0, 4759, false], [4759, 9299, null], [9299, 15489, null], [15489, 19930, null], [19930, 24993, null], [24993, 30088, null], [30088, 34457, null], [34457, 38133, null], [38133, 43040, null], [43040, 47547, null], [47547, 53233, null], [53233, 59247, null], [59247, 59247, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4759, true], [4759, 9299, null], [9299, 15489, null], [15489, 19930, null], [19930, 24993, null], [24993, 30088, null], [30088, 34457, null], [34457, 38133, null], [38133, 43040, null], [43040, 47547, null], [47547, 53233, null], [53233, 59247, null], [59247, 59247, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59247, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59247, null]], "pdf_page_numbers": [[0, 4759, 1], [4759, 9299, 2], [9299, 15489, 3], [15489, 19930, 4], [19930, 24993, 5], [24993, 30088, 6], [30088, 34457, 7], [34457, 38133, 8], [38133, 43040, 9], [43040, 47547, 10], [47547, 53233, 11], [53233, 59247, 12], [59247, 59247, 13]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59247, 0.04848]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
5de34842fdf6204199d4217aec5293c822cafe8a
|
The BEST scheduler for integrated processing of best-effort and soft real-time processes
Scott A. Banachowsky and Scott A. Brandt
Computer Science Department, University of California, Santa Cruz
ABSTRACT
Algorithms for allocating CPU bandwidth to soft real-time processes exist, yet best-effort scheduling remains an attractive model for both application developers and users. Best-effort scheduling is easy to use, provides a reasonable trade-off between fairness and responsiveness, and imposes no extra overhead for specifying resource demands. However, best-effort schedulers provide no resource guarantees, limiting their ability to support processes with timeliness constraints. Reacting to the need for better support of soft real-time multimedia applications while recognizing that the best-effort model permeates desktop computing for very good reasons, we have developed BEST, an enhanced best-effort scheduler that combines desirable aspects of both types of computing. BEST provides the well-behaved default characteristics of best-effort schedulers while significantly improving support for periodic soft real-time processes. BEST schedules using estimated deadlines based on the dynamically detected periods of processes exhibiting periodic behavior, and assigns pseudo-periods to non-periodic processes to allow for good response time. This paper discusses the BEST scheduling model and our implementation in Linux and presents results demonstrating that BEST outperforms the Linux scheduler in handling soft real-time processes, outperforms real-time schedulers in handling best-effort processes, and sometimes outperforms both, especially in situations of processor overload.
Keywords: Soft real-time, scheduling, Linux
1. INTRODUCTION
Although many people wish to use their desktop workstations as multimedia platforms, conventional desktop operating systems do not directly support the scheduling needs of soft real-time multimedia applications. Schedulers in conventional desktop operating systems use best-effort time-sharing policies designed to reduce the latency of interactive processes and provide adequate progress for all processes. Because they provide no guarantees of processing bandwidth, multimedia applications may or may not receive the timely scheduling they require in order to play continuous sound or video.\textsuperscript{1}
Our previous work examined dynamic desktop soft real-time using Dynamic QoS Level Resource Management (DQM).\textsuperscript{2,3} In that work we showed that it is possible to robustly execute soft real-time applications on best-effort systems. In particular, we developed a middleware framework that allowed applications to dynamically adjust their resource usage based on the available resources. By adjusting resource usage such that the set of running applications use less than 100\% of the available resources, a best-effort scheduler is able to provide reasonable soft real-time performance. In that work we also demonstrated dynamic estimate refinement, a technique that enables the system to dynamically adapt to incorrect or unspecified resource usage estimates.
Like most soft real-time systems, the DQM system has several issues that limit its ultimate utility in generic desktop environments. First, because it is a middleware solution, the performance of soft real-time applications varies significantly in the presence of best-effort or other applications that do not cooperate with the middleware resource manager. Second, like most soft real-time systems\textsuperscript{4-10} it requires applications to interface with special-purpose soft real-time interface routines. Third, like other soft real-time systems, the DQM requires that applications provide \textit{a priori} estimates of resource usage and period. Although the DQM
Further author information:
Email: {sbanacho,sbrandt}@cse.ucsc.edu Address: Computer Science Department, School of Engineering, Applied Sciences Bldg., U.C. Santa Cruz, 1156 High Street, Santa Cruz, CA 95064.
system can dynamically adjust to incorrect or unspecified resource usage estimates, it cannot adapt to incorrect or unspecified application periods.
This paper presents a solution that addresses those issues—BEST, a time-sharing scheduler that directly supports multimedia applications while providing adequate progress and response time for best-effort applications. BEST dynamically measures process behavior and uses the information to aid in scheduling decisions. By detecting the rate at which waiting processes enter the run queue, the scheduler boosts the performance of “well-behaved” periodic processes by increasing their priority, while preserving the behavior of traditional time-sharing schedulers for non-periodic processes; we use a Best-effort scheduler that is Enhanced for Soft real-time Time-sharing, so we call it the BEST scheduler.
Current approaches to soft real-time scheduling require special interfaces to the scheduler—BEST differs by removing software authors’ and users’ awareness of the scheduler. Most specialized systems place a burden of specifying scheduling needs of an application either with the developer, who must use system calls to communicate and negotiate with a scheduler, or the user, who explicitly chooses priorities or executes external software to control scheduling policies. The BEST scheduler uses the best-effort model, so no process is refused admission or provided a service guarantee. This is an attractive model because it incurs no overhead for programmers or users. Like other best-effort systems, if the user overburdens the system, the user will experience degraded system performance. However, in the presence of other applications or heavy (but not overburdened) use, the BEST scheduler effectively meets soft real-time deadlines for applications that are well-behaved. And when overburdened, BEST continues to provide satisfactory progress to all applications.
This paper describes an implementation of the BEST scheduler in the Linux kernel. Section 2 summarizes related research that supports scheduling for multimedia. Section 3 describes the scheduler implementation, and Section 4 presents quantitative performance data. Finally, Section 5 discusses our future plans for this research and Section 6 provides concluding remarks.
2. RELATED WORK
Continuous real-time applications require enough processor bandwidth to meet their periodic deadlines. We classify multimedia applications as soft real-time because, like real-time processes, they must meet periodic deadlines, but missing an occasional deadline results in diminished performance rather than outright failure.
2.1. Real-time Scheduling
Real-time systems, such as RT-Mach, are designed to meet hard deadline constraints. Some versions of UNIX support real-time scheduling classes, and many systems adapt the POSIX standard for real-time extensions. In order to ensure predictable behavior, these system use strict scheduling policies such as Rate Monotonic (RM) or Earliest Deadline First (EDF). These scheduling algorithms require that the worst-case workload is known when configuring a system. For industrial applications, where systems are typically dedicated to specific purposes and deadlines are hard, real-time systems are attractive because they may be tuned to perform predictably. However real-time operating systems are not well-suited for desktop use because workload cannot in general be predicted. Most multimedia scheduling research focuses on integrating the desirable features of hard real-time scheduling into general-purpose systems that have inconsistent workloads; an example is the Nemesis Atropos scheduler, which uses EDF based on deadlines derived from a process’s specified share of CPU bandwidth. Multics also provides an EDF scheduler, using desired response time to determine virtual deadlines of non-real-time processes. Like these systems, BEST schedules by earliest deadline, but unlike previous systems it automatically detects the periods of processes and assigns appropriate deadlines based on this information, and assigns pseudo-deadlines to non-periodic processes and schedules accordingly.
2.2. Multi-level Scheduling
One approach for handling a mix of applications divides processes according to type, and assigns each type to different schedulers; each scheduler uses the policy best suited for its type. In hierarchical schemes, a lower-level scheduler receives bandwidth allocated by the higher-level scheduling policy. For example, in Real-Time Linux, the Linux kernel executes as the lowest priority task in a real-time scheduler alongside the other higher
priority real-time tasks. POSIX extensions also implement hierarchical scheduling—the real-time classes defer
to the time-sharing class when no real-time process is ready to execute.
Researchers use several techniques of adapting multi-level scheduling to the needs of soft real-time systems. Taking advantage of the POSIX multi-level scheduling classes, user processes may schedule soft real-time processes by dynamically altering their priorities, thereby removing soft real-time scheduling decisions from the kernel. Some more sophisticated approaches to hierarchical scheduling include the SFQ algorithm, which proportionally shares bandwidth among the levels so that time-critical applications receive adequate resources, and CPU Inheritance Scheduling, which allows scheduling threads to donate processing to other scheduler threads in flexible arbitrary arrangements of hierarchies. The Vassal project adds a system interface for users to install their own schedulers. Another method applied to soft real-time is middleware resource management*. Middleware managers monitor a system’s resources usage, and provide recommendations to adaptive soft real-time processes. DQM uses this approach to maximize benefits for scalable soft real-time processes, independent of the underlying kernel scheduler.
The architectural approach of dividing scheduling into levels creates flexibility for systems running a mix of applications of differing processing needs; with it comes the problem of choosing ideal configurations, which as research indicates is not trivial. System architects, and in some cases users, must make informed decisions for the layout of scheduling hierarchy. For the BEST scheduler, we do not introduce the complexity of multiple levels of scheduling, and instead rely on a single algorithm for all processes. The algorithm is designed to minimize latency for periodic and interactive processes. However, using the scheduler does not preclude integration into multi-level schemes.
2.3. Proportional-share Scheduling
Recognizing the low predictability of general-purpose system workloads and the relaxed deadline requirements for multimedia applications, a large body of research focuses on creating new schedulers better suited to a mix of application types. Most systems allocate each process a share of processing bandwidth, and use an algorithm to assign allotted CPU guarantees within minimal error bounds. For periodic applications, share is allocated to meet the execution rate required to meet deadlines. Fair-sharing is enforced so no process inhibits another’s ability to meet deadlines.
Proportional scheduling systems share similar concepts yet differ in strategy. Here we briefly mention some systems; this list is not comprehensive. EEVDF calculates a virtual deadline for each process as a function of measured and allotted share, and schedules according to EDF; Stride Scheduling uses a similar notion of virtual time. Systems such as BVT and BERT provide enhanced fair-sharing algorithms aimed at increasing the throughput of deadline-sensitive processes by dynamically reallocating shares on a short-term basis. Some systems utilize admission control; processes reserve shares, and the scheduler denies admission when requested reservations are not available. The CM and SMART schedulers provide feedback to applications so they may adapt to dynamically changing loads, allowing the scheduler to adjust to higher workloads without resorting to restricting admission.
To meet deadlines, the proportional scheduler must determine the proper share for each process; a process must somehow specify its rate requirement. In many cases, this information is built into the process, and upon start-up it notifies the scheduler through a system API. It may be difficult to determine a desired rate if the speed of the target processor is unknown; abstractions for specifying rate address this problem (however because the abstracted rates are typically not expressed in units of system clock ticks, clock skew is inevitably introduced). For systems that include feedback from the scheduler to the process, greater flexibility comes at the expense of even more demand on application developers. Additionally, some systems provide mechanisms for users to specify the quality of service they desire from a process, and allow run-time modification of share assignments through GUIs, placing the burden of scheduling specification on both the developers and the software users. The BEST scheduler does not need to be informed of processes’ rates, making the development and use of SRT applications easier.
*While not strictly hierarchical, middleware can be considered a meta-scheduler for participating processes.
2.4. The State of SRT Scheduling
The scheduling algorithms and systems proposed by researchers support service guarantees that are not possible with best-effort scheduling. However, fully utilizing them involves difficult decisions provided by system builders, applications developers, and users. System builders must set appropriate architecture for hierarchies of schedulers. Developers must conform to new system APIs, reducing the portability of applications. Users must hassle with tuning the scheduling parameters for desired performance; the average desktop user may not be interested in or capable of accomplishing this task. Our experience suggests that most multimedia applications only suffer occasional glitches which may be adequately addressed with better best-effort scheduling. The ease and simplicity of best-effort scheduling makes it the most attractive model for many platforms—by enhancing the performance of soft real-time processes, the users may never notice the absence of service guarantees.
3. IMPLEMENTATION
The goal of BEST is to enhance the performance of soft real-time tasks by detecting periodic processes and boosting their priorities to improve their chances of meeting their deadlines. Like most UNIX schedulers, it dynamically calculates process priorities. It is aimed at desktop users who desire better performance from multimedia applications without the complexity of a system with service guarantees.
The scheduler must decide which programs have periodic deadline requirements by making an assumption: applications with periodic deadlines enter a runnable state when they begin a periodic computation, and upon completion use synchronization primitives (such as timers) to wait for the beginning of the next period. We predict that by observing the times that a process enters the queue of runnable processes we can make reasonable guesses about its period. A periodic process is “well-behaved” if it enters the runnable queue in a predictable pattern. It is possible that some processes that repeatedly enter the runnable state may be misidentified as having a periodic deadline even though they do not; in this case, they may benefit from the mistake. This is not a concern as long as the CPU resource isn’t significantly overburdened, and the scheduler can be tuned to minimize the likelihood of such occurrences.
In order to test the assumption that multimedia processes enter the run queue with predictable period, we instrumented the Linux kernel to record the entry time of a process to the nearest $\frac{1}{1000}$ of a second, and then ran some sample single-threaded multimedia processes. We examined mpeg_play, a desktop MPEG video player, and mpg123, a desktop mp3 audio player. We found that these processes did exhibit measurable periodic behavior. Table 1 shows the average period and standard deviation in microseconds for the sample runs. These experiments were executed on a 650 MHz AMD 6666 system.
Both multimedia programs enter the run queue with detectable periods, however their behavior differs: the video player must keep a nominal framerate, whereas the audio player periodically feeds a buffer so its timing requirement is not as strict; it only needs to keep the buffer from completely draining. When mpeg_play displays frames, it enters the run queue twice per frame, once for frame synchronization and once waiting for a video buffer, then sleeps until it is time to display the next frame. Because it enters the run queue twice during the same tick, the detected average period is half the actual frame period, and the standard deviation is close
<table>
<thead>
<tr>
<th>Process</th>
<th>Average period (ms)</th>
<th>Standard deviation</th>
<th>CPU usage</th>
</tr>
</thead>
<tbody>
<tr>
<td>mpeg_play (24 frame/s)</td>
<td>21.7</td>
<td>21.9</td>
<td>19.3%</td>
</tr>
<tr>
<td>mpeg_play (24 frame/s) (no display)</td>
<td>42.3</td>
<td>9.2</td>
<td>13.0%</td>
</tr>
<tr>
<td>mpeg_play (30 frame/s)</td>
<td>17.0</td>
<td>17.4</td>
<td>19.5%</td>
</tr>
<tr>
<td>mpeg_play (30 frame/s) (no display)</td>
<td>34.6</td>
<td>13.1</td>
<td>15.9%</td>
</tr>
<tr>
<td>mpg123 (128 kbit/s)</td>
<td>160.2</td>
<td>31.7</td>
<td>2.2%</td>
</tr>
<tr>
<td>mpg123 (128 kbit/s) (different mp3)</td>
<td>160.2</td>
<td>31.8</td>
<td>2.2%</td>
</tr>
</tbody>
</table>
to the average period (Section 3.3.2 explains how BEST deals with this anomaly). When display is disabled, mpeg_play processes the file without rendering it. In this case it does not block waiting for the video frame buffer, and its period it equivalent to its frame rate. The audio player is not driven by a framerate or clock; it repeatedly fills a buffer with audio data, sleeping for a fixed period between each fill. As expected, it exhibits periodic behavior, but since the period is not scheduled at a specific rate it has higher variance than the video player.
3.1. Design Goals
In developing the BEST scheduler we had a number of specific design criteria. The criteria and rationale for the scheduler design are:
1. The same scheduling policy should apply to every application, regardless of its scheduling needs—a uniform algorithm simplifies scheduling decisions.
2. Neither users or developers should have to provide any a priori information about the process to be executed.
3. The scheduler should enhance the performance of soft real-time applications.
- Processes that enter the runnable queue in predictable patterns should receive a priority boost; it should be based on classical real-time scheduling results, i.e. the priority boost should be based on measured rate or deadline.
- This algorithm should create a positive feedback loop for well-behaved soft real-time processes; when processes do not miss deadlines, they have the opportunity to wait for the next period, increasing the likelihood of consistent patterns.
- The scheduler should be preemptive. Since periodic processes have higher priority, this prevents missed deadlines.
4. The default behavior of the scheduler should be reasonable and consistent with general purpose time-sharing schedulers.
- The scheduler should favor interactive processes over CPU-bound processes.
- No process should starve. The presence of compute intensive periodic processes cannot completely hinder the progress of other processes. Processes will receive time slices that prevent them from monopolizing the CPU and improve overall responsiveness.
- When the system is not fully loaded, changes to workload should not effect the performance of already executing processes. For fully loaded systems, performance should degrade gracefully.
3.2. Linux Scheduler Details
We implemented the BEST scheduling algorithm in the Linux 2.2.5 kernel. We selected Linux as a development platform because it is a popular desktop environment and source code is readily available. A brief description of the unmodified Linux scheduler is instructive for understanding the differences.
A function called schedule() allocates the CPU to a process. It loops through all processes in the runnable queue, and selects the one with highest dynamic priority. The execution of schedule() is triggered two ways: explicitly when a running process is put to sleep, or upon return from an interrupt or trap if the running process’s need_resched flag is set. For example, when a process’s time quantum expires, the timer interrupt handler sets its need_resched flag.
A function called goodness() calculates dynamic priorities. The dynamic priority is also interpreted as a time quantum, and decreases for every clock tick the process executes. When all runnable processes consume their quantum, schedule() loops through all processes (including those not in the run queue) and recomputes
their dynamic priority using $\text{pri} = \text{pri}/2 + \text{nice}$, where nice is a positively scaled user-settable scheduling priority. When this calculation occurs, a suspended process with a non-zero time quantum receives a priority boost; the purpose is to increase the responsiveness of interactive processes over CPU-bound processes. For a program that is always suspended, the priority as a function of the number of calculations $n$, is $\text{pri}(n) = [2^n + 1 - 1/2^n] \times \text{nice}$. Priority quickly increases, but as $n \to \infty$, $\text{pri} = 2 \times \text{nice}$, limiting the priority (and time quantum) from growing too large.
The Linux scheduler implementation is designed to mimic the behavior of a multi-level feedback queue, and although dynamic priority calculations differ from 4.4BSD (well-documented by McKusick et al.\textsuperscript{29}), the goal of the scheduling policy remains the same: favor I/O-bound over CPU-intensive processes while allowing no process to starve. The 4.4BSD scheduler differs from Linux by including a time-decaying estimate of the CPU usage in the priority calculation. The Windows NT scheduler employs a similar technique.\textsuperscript{24}
3.3. BEST Scheduler Details
The BEST scheduler uses an even simpler algorithm than the Linux scheduler. Every process has a deadline that is computed when the process enters the runnable queue. The \texttt{schedule()} function selects the runnable process with the earliest deadline. Since we do not know a process’s deadline, a simple heuristic is used to estimate its period, and the deadline is set to the expiration of its next period.
3.3.1. Period detection
BEST estimates period when a process enters the runnable queue (queue entry is through a single function called \texttt{wake_up_process()}). The estimated period $P_{est}$ is the time that elapsed since the process previously entered the runnable queue. The new effective period $P_n$ is calculated by taking a weighted average with the previous period $P_{n-1}$, stated as $P_n = (P_{est} + w \times P_{n-1})/(1 + w)$. Adjusting the weight factor $w$ controls how fast the scheduler forgets previous behavior. If the period exceeds a maximum value it is truncated, therefore periods longer than this maximum are not detected. The \texttt{wake_up_process()} function determines a process’s next deadline by adding its effective period to the current time. The scheduler uses the deadline as a priority when selecting runnable processes. This function also sets an additional value called the \textit{deadline timer}. This timer indicates how much CPU time a process may receive before its deadline is reset. Like the quantum timer, the deadline timer value is decremented for every tick the process executes. The deadline and deadline timer values are stored in the process’s state structure.
Every time a process is scheduled for the CPU it executes until either its quantum expires, it blocks, or it is preemted, at which time \texttt{schedule()} is triggered. Before selecting the next process to execute, if the current process’s deadline timer expired, \texttt{schedule()} sets its next deadline to a time beyond the maximum detectable period—in effect it lowers the priority of any process that doesn’t leave the runnable queue before its deadline timer expires. Only \texttt{wake_up_process()} resets the deadline timer, so for a process that never blocks \texttt{schedule()} will postpone its deadline whenever it executes. Postponing a deadline to greater than the maximum period ensures that processes with detected periods will have earlier deadlines. Because a postponed deadline is not recomputed until after the process is allocated the CPU, starvation is prevented. Once a deadline is set, eventually the process will be scheduled as time advances.
3.3.2. Confidence
Not every process that repeatedly wakes up is periodic, so an additional step evaluates the \textit{confidence} that the estimated period is indeed due to periodic behavior. Confidence is a measure of the difference between the current measured period, and the nearest multiple of the average period. (The expression $|P_{est} \mod P_n - P_n/2|$ calculates a confidence value between 0 and $P_n/2$, but in practice we use bit shifts and fixed-point math, yielding a value normalized between 0 and 16). A process is “well-behaved” if its confidence exceeds a threshold. A process that is not well-behaved will receive a deadline timer of 0, meaning that it is eligible to have its deadline reset following its next scheduled quantum. Although scheduling priority is set according to its estimated period, once it uses its current quantum the process will be rescheduled with a CPU-bound pseudo-period unless its confidence increases above threshold.
By calculating confidence using a multiple of the period (implicit in the modulo operation), we elude the effect of detecting an average period that is half the actual period (as observed in Table 1, where we saw that a video player entered the run queue twice per frame). This effect also helps processes that miss an occasional deadline. When a periodic process misses a deadline, it may not sleep and wake up again until a later period, when it successfully completes a computation on time. This process will still receive a high confidence rating when it does, allowing it another opportunity to meet its next deadline. However, the weighting of its time-decaying average period will impact its next deadline assignment and subsequent confidence rating. The coupled effect of this weighting factor and the confidence threshold impact the performance of the scheduler.
### 3.3.3. Other changes
In order to detect periods of processes with high rates, we increased the timer resolution of Linux by a factor of 8. Linux processes 100 clock ticks per second; for a video player showing 33 frames/second the average period is 3 ticks, so a measurement error of 1 tick is a significant percentage of its period. By increasing the timer resolution to 800 ticks per second, measurements are more finely grained and provide a better estimate of the application periods. Interestingly, we found that speeding up the timer increased the throughput of processes by about 5%, not the intuitive result expected from increasing the frequency of timer interrupt processing. We do not at present have a satisfactory explanation for this result.
BEST uses a time quantum to limit the time a process may hold the CPU. In Linux, the default processing time quantum is 0.2 seconds, and may be modified between 0.01 and 0.40 seconds using the UNIX nice facility. In BEST the default processing quantum is set to 0.1 second, which is historically the quantum used in BSD as it provides an ideal responsiveness for interactive processes.\(^\text{20}\) Using the nice facility scales this range between 0.05 and 0.20 seconds. In BEST, a running process may be preempted by one with an earlier deadline; however, similar to Linux, context switches are reduced by disabling preemption when a current quantum expires in less than 10 milliseconds. Note that when an executing process still has a positive deadline timer, an expired quantum will not affect its scheduling priority and it is likely to be selected again. This makes the deadline timer behave like an interval timer, as used in Nemesis.\(^\text{17}\) In the future, we plan to replace all quanta with interval timers to reduce unnecessary scheduling overhead.
### 3.3.4. Tuning the scheduler
Several parameters affect the behavior of the BEST scheduler: the maximum period, the deadline timer, the weight used for averaging period measurements, and the confidence threshold. The maximum detectable period controls the responsiveness of CPU-bound processes in a heavily loaded system, since their pseudo-deadlines are delayed beyond this period. The deadline timer dictates the maximum amount of time a process receives before resetting its deadline; if too large, a process may monopolize the CPU, and if too short, it may not meet its deadline. Finally, the averaging weight and confidence threshold impact the effectiveness of the period detection algorithm.
For the BEST prototype described in Section 4, we use a maximum period of 5.12 seconds (with an extra offset of 0.1 second added to the deadline of CPU-bound processes), a weighting average of \(\frac{1}{3}\), and a generous threshold that allows any confidence level to pass. The deadline timer is the same as the period, so that a process’s deadline is not reset until it uses all the processing time of a period. In practice, a process should use less time than its period, otherwise it will miss deadlines in the presence of any other work and is generally not schedulable on a shared system. These defaults work well in our experiments where all processes were “well-behaved,” although we expect them to require tuning for more real workloads.
### 4. EXPERIMENTAL RESULTS
To examine how well the BEST scheduler meets the design criteria set forth in Section 3.1 we conducted a set of experiments comparing the performance of the BEST scheduler with that of the Linux scheduler and a Rate Monotonic (RM) scheduler. We chose RM as a representative real-time scheduler because the POSIX standard specifies a scheduling class with static priorities capable of supporting RM scheduling. Note, however, that the calculation of priorities for RM scheduling requires a specification of application periods while the default Linux scheduler and BEST do not.
While running combinations of greedy (CPU-intensive) and periodic (soft real-time) processes, we measured the throughput of all processes and the number of missed deadlines for periodic processes. Two synthetic applications were used in the experiments. Loop endlessly consumes CPU bandwidth by crunching math operations. Periodic takes two arguments, a period and a percentage; it attempts to consume the desired percentage of CPU bandwidth during each period. If it completes before a deadline it pauses until the beginning of the next period, and if not it records a missed deadline and starts the next period’s computation. All experiments were executed on a 200 MHz Pentium Pro system with 256K cache and 256M RAM.
Our results show that in general the Linux scheduler performs reasonably well when the total demand of soft real-time processes is less than 100% of the CPU and each process requires no more than \( \frac{1}{n} \) of the CPU, where \( n \) is the number of running processes. This is consistent with our previous work in executing soft real-time processes on best-effort systems. Figure 1 shows the performance of the Linux scheduler and the BEST scheduler with one best-effort process (loop) and one SRT process (periodic, with \( \frac{1}{10} \) second period and CPU requirements of 40% of the CPU). Because the Linux scheduler provides approximately equal amounts of CPU cycles to each application and because the SRT process requires less than 50% of the CPU (it’s nominal fair share) the Linux scheduler met all application deadlines. Similarly, the BEST scheduler met all deadlines and provided the same amount of resources to each application as the Linux scheduler: 40% of the CPU was granted to the SRT process and 60% was granted to the best-effort process. A similar experiment was performed (Figure 2) replacing loop with a second SRT application (periodic, with the same parameters). The results were similar except that the idle loop consumed the remaining 20% of unused CPU cycles. With reasonable priorities, RM would perform the same.
When a soft real-time process requires more than its nominal share of the available CPU cycles, the Linux scheduler is unable to satisfy it in the presence of CPU-bound best-effort processes. Specifically, when two processes of equal priority compete, the Linux scheduler gives them each about 50% of the available CPU cycles (with slightly more given to processes that block occasionally). Figure 3 shows the performance of the Linux, BEST, and RM schedulers with one best-effort process (loop) and one SRT process (periodic, with \( \frac{1}{10} \) second period and 70% CPU usage). Here we see that the Linux scheduler provides approximately 50% of the available CPU cycles to each application, causing the SRT process to miss 29% of its deadlines. By contrast, the RM scheduler (with appropriate priorities) provides the SRT process with 70% of the available cycles, enabling it to meet all of its deadlines while still allowing the best-effort process to progress at a reasonable rate. In this case, the BEST scheduler provided exactly the same performance as the RM scheduler, enabling the SRT process to meet all of its deadlines while still allowing the best-effort process to progress using the remaining CPU cycles. Recall, however, that BEST dynamically determines the application periods whereas Rate Monotonic requires that periods be specified in order to determine appropriate priorities.

Figure 2: Linux and BEST schedulers running (1) periodic 0.1s 40% and (2) periodic 0.1s 40%.
Even in cases where the Linux scheduler should theoretically allow SRT processes to meet all of their deadlines, such as when each requires less than its nominal share of the CPU, it is still possible that each process will fail to meet its deadline. Because the Linux scheduler is unaware of resource requirements or deadlines, its well-intentioned scheduling decisions can result in some processes missing deadlines that could otherwise be met. Figure 4(a) shows the Linux, BEST, and RM schedulers running three processes; one best-effort process and two SRT processes, each of which require 30% of the CPU, one with a period of \(\frac{1}{10}\) second and the other with a period of 1 second. Because each SRT process needs less than its nominal share of the CPU, all deadlines should theoretically be met. However, due to the details of the Linux scheduler, we see that in fact the process with the shorter period received less than 30% of the CPU and missed 6% of its deadlines. By contrast, the same processes running with the BEST scheduler missed no deadlines. As can be seen from the graph, the two SRT process received about the same amount of CPU time and approximately 30% of the available cycles. Similarly, these processes made all deadlines under RM scheduling.
Figure 4(b) shows a magnified view of a portion of the data from Figure 4(a), providing greater detail about when each scheduling decision is made and how much CPU is scheduled at each decision. In particular, it shows that under the Linux scheduler, the short period SRT process receives less CPU and at greater intervals than under the BEST scheduler. Under the Linux scheduler, this process experiences a short gap every second where it is not scheduled. This causes the process to miss some deadlines. Under the BEST scheduler, this does not occur and the processes miss no deadlines at all.
While any set of soft-real time processes with a CPU requirement less than 100% is theoretically schedulable
Figure 4: Linux, BEST, and RM schedulers with (1) loop (2) periodic 1s 30% and (3) periodic 0.1s 30%.
without missed deadlines, in many cases the Linux scheduler cannot allocate enough share to SRT processes in competition with a greedy process. Figure 5 shows the Linux, BEST and RM schedulers with four processes, one best-effort and three SRT, one with a period of 1 second requiring 30% of the CPU, one with a period of \( \frac{1}{3} \) second requiring 30% of the CPU, and one with a period of \( \frac{1}{10} \) second requiring 30% of the CPU. The Linux scheduler cannot meet all deadlines because it allocates roughly \( \frac{1}{4} \) of the resources to each process, and it performs very poorly, missing 83%, 80%, and 10% of the deadlines of the periodic processes, respectively. Again, like the RM scheduler, the BEST scheduler met all deadlines while still allowing the best effort process to make progress.
One shortcoming of rate-monotonic scheduling is its inability to find a feasible schedule that fully utilizes the CPU when running periodic applications that exhibit non-harmonic periods.\(^{12}\) By using EDF to make the actual scheduling decisions, BEST does not exhibit this property. Figure 6 shows the performance of the three schedulers with four processes, one best-effort and three SRT, one with a period of 0.61 seconds requiring 31% of the CPU, one with a period of 0.43 seconds requiring 30% of the CPU and one with a period of 0.13 seconds requiring 31% of the CPU. In this case, the SRT processes need 92% of the CPU and have non-harmonic periods. The Linux scheduler provides approximately equal CPU to each process with the result that the best-
Figure 5. Linux, BEST and RM schedulers with (1) loop (2) periodic 1s 30% (3) periodic 0.5s 30% and (4) periodic 0.1s 30%.
Figure 6. Linux, BEST, and RM schedulers with (1) loop (2) periodic 0.61s 31% (3) periodic 0.43s 30% and (4) periodic 0.13 31%.
effort process makes too much progress and prevents the SRT processes from meeting enough deadlines—they miss 77%, 66%, and 16% respectively. In theory, RM scheduling may not meet all deadlines and that is exactly what we observe. RM causes the process with the longest period (and thus the lowest Rate Monotonic priority) to miss 27% of its deadlines. Outperforming both other schedulers, BEST executes the processes and meets all SRT deadlines.
An important question about any SRT scheduler is how it performs in situations of system overload. Best-effort schedulers will in general allocate a proportional share of the CPU to each process, Rate Monotonic will meet the deadlines of processes with highest priority (generally those with the lowest period), and EDF will miss all deadlines by roughly the same amount. While the overload of either RT scheduler might be considered optimal in some strictly SRT environments, they suffer from the fact that they will starve best-effort processes entirely. Figure 7 shows the performance of the Linux, BEST, and RM schedulers with four processes, one best-effort, one SRT with period 1 second requiring 40% of the CPU, one SRT with period $\frac{1}{2}$ seconds requiring 40% of the CPU, and one SRT with period $\frac{1}{10}$ seconds requiring 40% of the CPU. Because the resource requirements of the SRT process sum to greater than 100% of the CPU, no scheduler can meet all of the deadlines. The Linux scheduler gives each process roughly $\frac{1}{4}$ of the CPU, causing the SRT processes to miss 98%, 93%, and 19% of their deadlines, respectively, and allows the best-effort process to make very good progress, getting a full $\frac{1}{4}$ of the available CPU cycles. The RM scheduler meets all of the deadlines for the two SRT processes with shorter deadlines, but misses 98% of the deadlines for the SRT process with the longest deadline and doesn’t allow the best-effort process to run at all. The BEST scheduler embodies the best characteristics of both schedulers, distributing (somewhat) and minimizing the missed deadlines (71%, 5%, and 2% respectively) while still allowing the best-effort process to make reasonable progress.
A primary goal of the BEST scheduler is to minimize the number of missed deadlines for soft real-time
Figure 7. Linux, BEST, and RM schedulers with (1) loop (2) periodic 1s 40% (3) periodic 0.5s 40% and (4) periodic 0.1 40%.
Table 2: Summary of percentage of deadlines missed for all experiments.
<table>
<thead>
<tr>
<th>Experiment</th>
<th>Process</th>
<th>Linux</th>
<th>BEST</th>
<th>RM</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>loop</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>periodic(0.1s 40%)</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>2</td>
<td>periodic(0.1s 40%)</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>periodic(0.1s 40%)</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>3</td>
<td>loop</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>periodic(0.1s 70%)</td>
<td>29</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>4</td>
<td>loop</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>periodic(1.0s 30%)</td>
<td>0</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>periodic(0.1s 30%)</td>
<td>6</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>5</td>
<td>loop</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>periodic(1.0s 30%)</td>
<td>83</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>periodic(0.5s 30%)</td>
<td>80</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>periodic(0.1s 30%)</td>
<td>10</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>6</td>
<td>loop</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>periodic(0.61s 31%)</td>
<td>77</td>
<td>0</td>
<td>27</td>
</tr>
<tr>
<td></td>
<td>periodic(0.43s 30%)</td>
<td>66</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>periodic(0.13s 31%)</td>
<td>16</td>
<td>0</td>
<td>0</td>
</tr>
<tr>
<td>7</td>
<td>loop</td>
<td>-</td>
<td>-</td>
<td>-</td>
</tr>
<tr>
<td></td>
<td>periodic(1.0s 40%)</td>
<td>98</td>
<td>71</td>
<td>98</td>
</tr>
<tr>
<td></td>
<td>periodic(0.5s 40%)</td>
<td>93</td>
<td>5</td>
<td>0</td>
</tr>
<tr>
<td></td>
<td>periodic(0.1s 40%)</td>
<td>19</td>
<td>2</td>
<td>0</td>
</tr>
</tbody>
</table>
processes while providing good best-effort performance. The previous figures show that BEST approximates the performance of both Linux and RM as appropriate. Table 2 summarizes the percentage of deadlines missed by each scheduler in all of the experiments. It shows that BEST meets or exceeds the performance of both the Linux and Rate Monotonic schedulers in each of the experiments shown.
A final question that is difficult to answer with data is the qualitative one—how does the scheduler perform in general use? To attempt to answer this question, we have been running the BEST scheduler (in Linux) on a desktop machine for the past few months. We have experienced no anomalous behavior, response time has been satisfactory and “normal,” SRT processes definitely appear to run better, and BE processes do not starve while SRT processes are running. While this is not conclusive, it is quite encouraging.
5. FUTURE WORK
Experiments show that the BEST prototype meets its intended purpose: enhancing the performance of periodic processes while capturing the benefits of a best-effort model. It also preserves the design goals of general-purpose operating systems by favoring I/O-intensive over CPU-bound jobs; as users we successfully employ the scheduler on a development and general purpose platform with no adverse effect on responsiveness. However, many of the scheduler parameters are not tuned for executing real multimedia applications and workloads. For example, processes entering the system are currently initialized with scheduling parameters that make them appear periodic. Running a batch process (such as a compile) will generate several jobs that might interfere with already running processes; by determining proper initial values for process structures we can limit this effect. In the future we will tune BEST scheduler using the behavior of popular multimedia packages as examples (such as MpegTV and xmons). Many multimedia applications are multi-threaded and depend on the responsiveness of other processes such as the X server. In light of the dependencies of these applications, we must reexamine the naive assumptions of our test processes. For example, a more sophisticated version of the scheduler may detect dependencies and allow a process to inherit the deadline of related processes.
In addition, we believe that BEST has better jitter performance than the default Linux scheduler. We intend to characterize the jitter performance of BEST and compare it with the other schedulers examined in this paper. Another aspect of BEST that we have yet to examine is the effect of changing priorities. We believe that by automatically adjusting the priorities of the SRT processes we can adapt the system to provide any missed-deadline behavior desired. In particular, we should be able to spread out the missed deadlines across the SRT processes or minimize the missed deadlines of more important processes.
6. CONCLUSION
Standard best-effort schedulers make no resource guarantees, but soft real-time applications require some assurance of resource allocation in order to meet deadlines. Best-effort scheduling is thought to perform poorly for multimedia; but because it is simple to use, the best-effort model continues to be attractive for both application developers and users of general purpose systems. BEST is a CPU scheduler that adheres to a best-effort scheduling policy while automatically detecting and boosting the performance of periodic soft real-time processes. BEST dynamically determines application periods and schedules processes according to earliest deadline first, a well-known scheduler for real-time systems. However, unlike real-time schedulers, it uses simple heuristics to determine deadlines for both periodic and non-periodic processes.
This paper presents the design and implementation of the prototype BEST scheduler in the Linux kernel. It includes the results of a set of experiments demonstrating the scheduler’s effectiveness at boosting the performance of processes with soft deadlines, while preserving desired characteristics of general purpose time-sharing schedulers. In particular, our results show that BEST performs as well as or better than the Linux scheduler and RM scheduling in handling best-effort, soft real-time, and a combination of the two types of processes. This holds true in situations of both processor underload and processor overload and is done with no a priori knowledge of the applications, their resource usage, or their periods. By continuing these experiments with more realistic workloads and by fine-tuning the scheduler parameters, we expect to develop the prototype into a full-fledged and robust system appropriate for widespread and general use.
ACKNOWLEDGMENTS
The work in this paper was motivated in part by a suggestion from Lonnie Welch that it would be interesting to see if we could dynamically detect application periods at run-time; the authors gratefully acknowledge that suggestion. We thank the reviewers for offering additional insight and ideas for future work. We also thank Zachary Peterson for reviewing drafts of this paper. This research was funded in part by a DOE High-Performance Computer Science Fellowship and a USENIX Student Research Grant.
REFERENCES
|
{"Source-Url": "https://www.crss.ucsc.edu/media/pubs/13a13d013a2b5a5d8463fd0434175bf979375c87.pdf", "len_cl100k_base": 10079, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 74368, "total-output-tokens": 12131, "length": "2e13", "weborganizer": {"__label__adult": 0.00030612945556640625, "__label__art_design": 0.0005197525024414062, "__label__crime_law": 0.0002884864807128906, "__label__education_jobs": 0.0012369155883789062, "__label__entertainment": 0.00016963481903076172, "__label__fashion_beauty": 0.00015246868133544922, "__label__finance_business": 0.0004773139953613281, "__label__food_dining": 0.00032210350036621094, "__label__games": 0.0008716583251953125, "__label__hardware": 0.003253936767578125, "__label__health": 0.0004742145538330078, "__label__history": 0.00035071372985839844, "__label__home_hobbies": 0.00010836124420166016, "__label__industrial": 0.0006003379821777344, "__label__literature": 0.0002543926239013672, "__label__politics": 0.0002999305725097656, "__label__religion": 0.0004489421844482422, "__label__science_tech": 0.2099609375, "__label__social_life": 9.626150131225586e-05, "__label__software": 0.040313720703125, "__label__software_dev": 0.73876953125, "__label__sports_fitness": 0.00019943714141845703, "__label__transportation": 0.0005202293395996094, "__label__travel": 0.00020420551300048828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 52654, 0.04857]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 52654, 0.37252]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 52654, 0.89564]], "google_gemma-3-12b-it_contains_pii": [[0, 4033, false], [4033, 8670, null], [8670, 13414, null], [13414, 17505, null], [17505, 20952, null], [20952, 25767, null], [25767, 30528, null], [30528, 34102, null], [34102, 36180, null], [36180, 37865, null], [37865, 40410, null], [40410, 42792, null], [42792, 47154, null], [47154, 51062, null], [51062, 52654, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4033, true], [4033, 8670, null], [8670, 13414, null], [13414, 17505, null], [17505, 20952, null], [20952, 25767, null], [25767, 30528, null], [30528, 34102, null], [34102, 36180, null], [36180, 37865, null], [37865, 40410, null], [40410, 42792, null], [42792, 47154, null], [47154, 51062, null], [51062, 52654, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 52654, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 52654, null]], "pdf_page_numbers": [[0, 4033, 1], [4033, 8670, 2], [8670, 13414, 3], [13414, 17505, 4], [17505, 20952, 5], [20952, 25767, 6], [25767, 30528, 7], [30528, 34102, 8], [34102, 36180, 9], [36180, 37865, 10], [37865, 40410, 11], [40410, 42792, 12], [42792, 47154, 13], [47154, 51062, 14], [51062, 52654, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 52654, 0.19018]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
e8795c482d9ec1aa00b9289f76147401a5377c10
|
Meaningful Change Detection in Structured Data*
Sudarshan S. Chawathe Hector Garcia-Molina
Computer Science Department, Stanford University, Stanford, California 94305
{chaw,hector}@cs.stanford.edu
Abstract
Detecting changes by comparing data snapshots is an important requirement for difference queries, active databases, and version and configuration management. In this paper we focus on detecting meaningful changes in hierarchically structured data, such as nested-object data. This problem is much more challenging than the corresponding one for relational or flat file data. In order to describe changes better, we base our work not just on the traditional "atomic" insert, delete, update operations, but also on operations that move an entire sub-tree of nodes, and that copy an entire sub-tree. These operations allow us to describe changes in a semantically more meaningful way. Since this change detection problem is \( \mathcal{NP} \)-hard, in this paper we present a heuristic change detection algorithm that yields close to "minimal" descriptions of the changes, and that has fewer restrictions than previous algorithms. Our algorithm is based on transforming the change detection problem to a problem of computing a minimum-cost edge cover of a bipartite graph. We study the quality of the solution produced by our algorithm, as well as the running time, both analytically and experimentally.
1 Introduction
Detection of changes between data structures is an important function in many applications. For example, in the World-Wide Web an analyst may be interested in knowing how a competitor's site has changed since the last time visited. This may be achieved by saving a snapshot of the previous HTML pages at the site (something that most browsers do for efficiency anyway). In a CAD design environment, an engineer may be interested in understanding the differences between two related but concurrently developed circuit designs. In a distributed file system, an administrator may need to detect differences between two mirror file systems that became partitioned and independently modified. In a warehousing environment, the changes at a site need to be identified so that a materialized view can be incrementally maintained.
In this paper we present an efficient algorithm, MH-DIFF, for meaningful change detection between two hierarchically structured data snapshots, or trees. The key word here is meaningful (the "M" in the name). That is, our goal is to portray the changes between two trees in a succinct and descriptive way. As is commonly done, we portray the changes as an edit script that gives the sequence of operations needed to transform one tree into another. However, in this paper we use a richer set of operations than has ever been used before, and this leads, we believe, to much higher quality edit scripts.
In particular, we use move and copy operations, in addition to the more traditional insert, delete, and update operations. Thus, if a substructure (e.g., a section of text, a shift register) is moved to another location, our algorithm will report it as a single operation. If the substructure is copied (e.g., a second shift register is added which is identical to one already in the circuit), then our algorithm will identify it as such. Traditional change detection algorithms would report such changes as sequences of inserts and deletes (or simply inserts in the case of a copy), which does not convey the true meaning of the change.
Note that detecting moves and copies becomes more important if the moved or copied subtree is large. For instance, if we are comparing file systems, and a large directory with thousands of files is mounted elsewhere, we clearly do not wish to report the change as thousands of file deletes followed by thousands of file creations. Also note that to detect moves and copies, it is essential that our algorithm understand the structure as well as the content of the data. Thus, our algorithm cannot treat the data as "flat" information, e.g., as files with records or relations with tuples. This means that techniques developed for flat change detection [Mye86, LGM96] are not applicable here.
Algorithm MH-DIFF has two additional important features:
- It does not rely on the existence of node (atomic object) identifiers that can match nodes in one tree to nodes in the other. In many applications such identifiers do not exist. For instance, sentences and paragraphs in text documents do not come with unique
identifiers attached. Even when the nodes are stored in a database system (e.g., circuit components), we may be comparing copies with the same content but different identifiers. Thus, for full generality, MH-DIFF does not assume unique identifiers that span the two trees, and instead compares the contents of nodes to determine if they are related. (If the trees have such identifiers, MH-DIFF could easily take advantage of them, but we do not discuss that here.)
- Algorithm MH-DIFF is based on a fairly flexible cost model. Each operation in the repertoire is given a user-defined fixed cost, except for the update operation, whose cost is determined by a user-provided function that compares the values of two nodes. This gives end users great latitude in saving what types of edit scripts are preferable for an application.
There is a good reason why difference algorithms with the features we have described here have not been developed earlier, even though they are clearly desirable. The reason is the inherent complexity of the problem; one can show that the problem is
Algorithm MH-DIFF provides a heuristic solution, which is based on transforming the problem to the "edge cover domain." That is, instead of working with edit scripts, the algorithm works with edge covers that represent how one set of nodes match another set. In this transformation, the costs of the edit operations are translated into costs on the edges of the cover.
In an earlier paper [CRGMW96] we studied a much simpler version of the change detection problem. In that work we did not consider copy operations, we assumed that the number of duplicates of a node was very limited, we assumed ordered trees, and we assumed that nodes had "tags" that reflect the structural constraints on the input trees. (For example, nodes were tagged as say "paragraphs" or "sections," making it easier to match nodes.) All these restrictions made it much simpler to find a minimum-cost edit script, and indeed we developed an efficient algorithm that found a minimum-cost script. Here, on the other hand, here we drop these restrictions, and introduce copy operations. This leads to an algorithm that is very different from the one in [CRGMW96], and that yields a heuristic solution in worst-case \(O(n^3)\) time, where \(n\) is the number of nodes, but most often in roughly \(O(n^2)\) time. In Section 7 we compare in more detail MH-DIFF to our earlier work, as well as to other work on change detection.
## 2 Model and Problem Definition
We use rooted, labeled trees as our model for structured data. These are trees in which each node \(n\) has a label \(l(n)\) that is chosen from an arbitrary domain \(L\). The problem of snapshot change detection in structured data is thus the problem of finding a way to edit the tree representation of one snapshot to that of the other. We denote a tree \(T\) by its nodes \(N\), the parent function \(p\), and the labeling function \(l\), and write \(T = (N, p, l)\). The children of a node \(n \in N\) are denoted by \(C(n)\).
We begin by defining the tree edit operations that we consider. Since there are many ways to transform one tree to another using these edit operations, we define a cost model for these edit operations, and then define the problem of finding a minimum-cost edit script that transforms one tree to another.
### 2.1 Edit Operations and Edit Scripts
In the following, we will assume that an edit operation \(e\) is applied to \(T_1 = (N_1, p_1, l_1)\), and produces the tree \(T_2 = (N_2, p_2, l_2)\). We write this as \(T_1 \xrightarrow{e} T_2\). We consider the following six edit operations:
- **Insertion**: Intuitively, an insertion operation creates a new tree node with a given label, and places it at a given position in the tree. The position of the new node \(n\) in the tree is specified by giving its parent node \(p\) and a subset \(C\) of the children of \(p\). The result of this operation is that \(n\) is a child of \(p\), and the nodes in \(C\), that were originally children of \(p\), are now children of the newly inserted node \(n\).
Formally, an insertion operation is denoted by \(\text{INS}(n, p, C)\), where \(n\) is the (unique) identifier of the new node, \(p\) is the label of the new node, \(p \in N_1\) is the node that is to be the parent of \(n\), and \(C \subseteq C(p)\) is the set of nodes that are to be the children of \(n\). When applied to \(T_1 = (N_1, p_1, l_1)\), we get a tree \(T_2 = (N_2, p_2, l_2)\), where \(N_2 = N_1 \cup \{n\}\), \(p_2(n) = p_1\), \(p_2(c) = p_1(c) \forall c \in C\), \(l_2(c) = l_1(c) \forall c \in N_1 - C\), \(l_2(n) = v\), and \(l_2(m) = l_1(m)\) \(\forall m \in N_1\). Due to space constraints, we describe the remaining edit operations only informally below; the formal definitions are in [CGM97].
- **Deletion**: This operation is the inverse of the insertion operation. Intuitively, \(\text{DEL}(n)\) causes \(n\) to disappear from the tree; the children of \(n\) are now the children of the (old) parent of \(n\). The root of the tree cannot be deleted.
- **Update**: The operation \(\text{UPD}(n, v)\) changes the label of the node \(n\) to \(v\).
- **Move**: A move operation \(\text{MOV}(n, p)\) moves the subtree rooted at \(n\) to another position in the tree. The new position is specified by giving the new parent of the node, \(p\). The root cannot be moved.
- **Copy**: A copy operation \(\text{CPY}(m, p)\) copies the subtree rooted at \(n\) to another position. The new position is specified by giving the node \(p\) that is to be the parent of the new copy. The root cannot be copied.
- **Glue**: This operation is the inverse of a copy operation. Given two nodes \(n_1\) and \(n_2\) such that the subtrees rooted at \(n_1\) and \(n_2\) are isomorphic, \(\text{GLU}(n_1, n_2)\) causes the subtree rooted at \(n_1\) to disappear. (It is conceptually "united" with the subtree rooted at \(n_2\).) The root cannot be glued. Although the \(\text{GLU}\) operation may seem unusual, note that \(\text{GLU}\) is a natural choice for an edit operation given the existence of the \(\text{CPY}\) operation. As we will see in Example 2.1, inverting an edit script containing a \(\text{CPY}\) operation results in an edit script with a \(\text{GLU}\) operation. This symmetry in the structure of edit operations is useful in the design of our algorithms.
In addition to the above tree edit operations, one may wish to consider operations such as a *subtree delete* operation that deletes all nodes in a given subtree. Similarly, one could define a *subtree merge* operation that merges two
or more subtrees. We do not consider such more complex
edit operations in this paper, but note that some of these
operations, (e.g., subtree deletes) may be detected by post-
processing the output of our algorithm.
We define an edit script to be a sequence of zero or more
edit operations that can be applied in the order in which
they occur in the sequence. That is, given a tree \( T_0 \), a
sequence of edit operations \( E = e_1, e_2, \ldots, e_k \) is an edit script
if there exist trees \( T_i, 1 \leq i \leq k \) such that \( T_{i-1} \xrightarrow{e_i} T_i, 1 \leq
i \leq k \). We say that the edit script \( E \) transforms \( T_0 \) to \( T_k \),
and write \( T_0 \xrightarrow{E} T_k \).
Example 2.1 Consider the tree \( T_1 \) depicted in Figure 1.
We represent the identifier of each node by the number in-
side the circle representing the node. The label of each
node is depicted to the right of the node. Thus, the root
of the tree \( T_1 \) has an identifier 1, and a label \( a \). Figure 1 shows how \( T_1 \) is transformed by applying the edit script to
\( E_1 \) that you defined in Example 2.1, we applied an edit script to a
\[
E_1 = (\text{INS}(11, 9), \text{MOV}(2, 1), \text{CPY}(7, 1)) \quad T_1.
\]
Similarly, if we start with the tree \( T_2 \) in the figure, the edit script
\( E_2 = (\text{GLU}(12, 7), \text{MOV}(2, 1), \text{DEL}(11)) \) transforms it back to
\( T_1 \). We write \( T_1 \xrightarrow{E_1} T_2 \), and \( T_2 \xrightarrow{E_2} T_1 \).
2.2 Cost Model
Given a pair of trees, there are, in general, several edit
scripts that transform one tree to the other. For example,
there is the trivial edit script that deletes all the nodes of
one tree and then inserts all the nodes of the second tree.
There are many other edit scripts that, informally, do more
work than seems necessary. Formally, we would like to find
an edit script that is "minimal" in the sense that it does no
more work that what is absolutely required. To this end, we
define a cost model for edit operations and edit scripts.
There are two major criteria for choosing a cost model.
Firstly, the cost model should accurately capture the domain
characteristics of the data being considered. For example,
if we are comparing the schematics for two printed-circuit
boards, we may prefer an edit script that has as few inserts
as possible, and instead describes changes with moves and
copies of the old components. However, if we are comparing
text documents, we may prefer to see a paragraph as a new
insertion, rather than a description of how it was assembled
from bits and pieces of sentences from the old document.
Secondly, the cost model should be simple to specify, and
should require little effort from the user. For example, a
cost model that requires the user to specify dozens of pa-
rameters is not desirable by this criterion, even though it
may accurately model the domain.
Another issue is the trade-off between generality of the
cost model and difficulty in computing a minimum-cost edit
script. For example, a very general cost model would have
a user-specified function to determine the cost of each edit
operation, based on the type of the edit operation, as well
as the particular nodes on which it operates. However, such
a model is not amenable to the design of efficient algorithms
for computing the minimum-cost edit script, since it does
not permit us to reason about the relative costs of the possi-
bile edit operations.
With the above criteria in mind, we propose a simple
cost model in which the costs of insertion, deletion, move,
copy, and glue operations are given by constants, \( c_I \), \( c_d \), \( c_m \),
\( c_c \), and \( c_g \), respectively. Furthermore, given the symmetry
between \( \text{INS} \) and \( \text{DEL} \), and \( \text{CPY} \) and \( \text{GLU} \), it is reasonable to
use \( c_I = c_d \), and \( c_c = c_g \). Since, intuitively, a \( \text{MOV} \) opera-
tion causes a smaller change than either \( \text{CPY} \) or \( \text{GLU} \), it is
also reasonable to use \( c_m < c_c \). Note, however, that our al-
gorithms do not depend on these relationships between the
cost parameters. The cost of an update operation depends
on the old and new values of the labeling being updated; that
is, \( c(\text{UPD}(n, v)) = c_u(v_0, v) \), where \( v_0 \) is the old label of \( n \),
and \( c_u \) is a domain-dependent function that returns a non-
negative real number.
Finally, the cost of an edit script \( E \), denoted by \( c(E) \), is
defined as the sum of the costs of the edit operations in \( E \).
That is, \( c(E) = \sum_{e \in E} c(e) \).
Problem Statement: Given two rooted, labeled trees \( T_1 \)
and \( T_2 \), find an edit script \( E \) such that \( E \) transforms \( T_1 \)
to a tree that is isomorphic to \( T_2 \), and such that for every edit
script \( E' \) with this property, \( C(E') \geq C(E) \).
3 Method Overview
In this section, we present an overview of algorithm MH-
DIFF for computing a minimum-cost edit script between two
trees. We present our algorithm informally using a running
example; the details are deferred to later sections.
Consider the two trees depicted in Figure 2. We would
like to find a minimum-cost edit script that transforms tree
\( T_1 \) into tree \( T_2 \). The reader may observe that these trees are
isomorphic to the initial and final trees from Example 2.1 in
Section 2. Note, however, that there is no correspondence
between the node identifiers of \( T_1 \) and \( T_2 \) in Figure 2. This is
because in Example 2.1 we applied a known edit script to a
tree, transforming it to another tree in the process, whereas in this section, we are trying to find an edit script, given two trees with no information on the relationship between their nodes. Therefore, our first step consists of finding a correspondence between the nodes of the two given trees.
For example, consider the node 8 in Figure 2. We want to find the node in \( T_2 \) that corresponds to this node in \( T_1 \). The dashed lines in Figure 2 represent some of the possibilities. Intuitively, we can see that matching the node 8 to the node 51 does not seem like a good idea, since not only do the labels of the two nodes differ, but the two nodes also have very different locations in their respective trees; node 8 is a leaf node, while node 51 is the root node. Similarly, we may intuitively argue that matching the node 8 to node 62 seems promising, since they are both leaf nodes and their labels match. However, note that matching a node based simply on their labels ignores the structure of the trees, and thus is not, in general, the best choice. We make this intuitive notion of a correspondence between nodes more precise below.
### 3.1 The Induced Graph
Consider the complete bipartite graph \( B \) consisting of the nodes of \( T_1 \) on one side, and the nodes of \( T_2 \) on the other, plus the special nodes \( \$ \) (on \( T_1 \)'s side) and \( \& \) (on \( T_2 \)'s side). We call \( B \) the induced graph of \( T_1 \) and \( T_2 \). The dashed lines in Figure 2 correspond to a few edges of the induced graph. Intuitively, we would like to find a subset \( K \) of the edges of \( B \) that tells us the correspondence between the nodes of \( T_1 \) and \( T_2 \). If an edge connects a node \( m \in T_1 \) to a node \( n \in T_2 \), it means that \( n \) was "derived" from \( m \). (For example, \( n \) may be a copy of \( m \).) We say \( m \) is matched to \( n \). A node matched to the special node \( \$ \) indicates that it was inserted, and a node matched to \( \& \) indicates that it was deleted. Note that this matching between nodes need not be one-to-one; a node may be matched to more than one other nodes. (For example, referring to Figure 2 node 7 may be matched to both node 52 and node 61.) The only restriction is that a node be matched to at least one other node. Thus, finding the correspondence between the nodes of two trees consists essentially of finding an edge cover\(^2\) of their induced graph.
The induced graph has a large number of edge covers (this number being exponential in the number of nodes). However, we may intuitively observe that most of these possible edge covers of \( B \) are undesirable. For example, and edge cover that maps all nodes in \( T_1 \) to \( \& \), and all nodes in \( T_2 \) to \( \$ \) seems like a bad choice, since it corresponds to deleting all the nodes of \( T_1 \) and then inserting all the nodes of \( T_2 \). We will define the correspondence between an edge cover of an induced graph and an edit script for the underlying trees formally in Section 4, where we also describe how to compute an edit script corresponding to an edge cover. For now, we simply note that, given an edge cover of the induced graph, we can compute a corresponding edit script for the underlying trees. Hence, we would like to select an edge cover of the induced graph that corresponds to a minimum-cost edit script.
---
\(^2\)An edge cover of a graph is a subset \( K \) of the edges of the graph such that any node in the graph is incident on at least one edge in \( K \).
### 3.2 Pruning the Induced Graph
We noted earlier that many of the potential edge covers of the induced graph are undesirable because they correspond to expensive and undesirable edit scripts. Intuitively, we may therefore expect a substantial number of the edges of the induced graph to be extraneous. Our next step, therefore, consists of removing (pruning) as many of these extraneous edges as possible from the induced graph, by using some pruning rules. The pruning rules that we use are conservative, meaning that they remove only those edges that we can be sure are not needed by a minimum-cost edit script.
We discuss pruning rules in detail in Section 5.3, presenting only a simple example here.
As an example of the action of a simple pruning rule, consider the edge \( e_1 = [5, 53] \) representing the correspondence between nodes 5 and 53 in Figure 2. Suppose that the cost \( c_{0}(a, ac) \) of updating the label \( a \) of node 5 to the label \( ac \) of node 53 is 3 units. Furthermore, let the cost of inserting a node and deleting a node be 1 unit each. Then we can safely prune the edge \([5, 53]\) because, intuitively, given any edge cover \( K_1 \) that includes the edge \( e_1 \), we can generate another edge cover that excludes \( e_1 \) and that corresponds to an edit script that is at least as good as the one corresponding to \( K_1 \). As an illustration of such pruning, consider the edge cover \( K_2 = K_1 - \{ e \} \cup \{ [5, \$], [53, \&] \} \). This edge cover corresponds to an edit script that deletes the node 5, and inserts the node 53. These two operations cost a total of 2 units, which is less than the cost of the update operation suggested by the edge \( e \) in edge cover \( K_1 \). We therefore conclude that the edge \([5, 53]\) in our running example may safely be pruned. In Section 5.3 we present Pruning Rule 3, which is a generalization of this example.
### 3.3 Finding an Edge Cover
By applying the pruning rules (Section 5.3) to the induced graph of our running example, say we obtain the pruned induced graph depicted in Figure 3 (ignore for the present the difference between dotted and solid lines in the figure). Although the pruned induced graph typically has far fewer edges than the original induced graph does, it may still contain more edges than needed to form an edge cover. In Section 4.2 we will see that we need only consider edge covers that are minimal; that is, edge covers that are not proper supersets of any edge cover. In other words, we would like to remove from the pruned induced graph those edges that are not needed to cover nodes. For example, in the pruned induced graph shown in Figure 3, having all four of the edges \([7, 61], [7, 63], [9, 61], \) and \([9, 63]\) is unnecessary; we may remove either \([7, 63]\) and \([9, 61]\), or \([7, 61]\) and \([9, 63]\). However, it is not possible to decide a priori which of these options is the better one; that is, it is not obvious which choice would lead to an edit script of lower cost. With pruning, on the other hand, there was no doubt that certain edges could be
One way to decide among these options is to enumerate all possible minimal edge covers of the pruned induced graph, find the edit script corresponding to each one (using the method described later in Section 5), and pick the one with the least cost. However, given the exponentially large number of edge covers, this is obviously not an efficient algorithm. To compute an optimal edge cover efficiently, we need to be able to determine how much each edge in the edge cover contributes to the total cost of an edit script corresponding to an edge cover containing it. That is, we need to distribute the cost of the edit script corresponding to an edge cover over the individual edges of the edge cover. Once we have a cost defined for each edge in the pruned induced graph, we can find a minimum-cost edge cover using standard techniques based on reducing the edge cover problem to a weighted matching problem [PS82, Law76]. For example, if the edges [7,61], [7,63], [9,61], and [9,63], have costs 0, 1.3, 0.2, and 2.4, respectively, then we generate an edge cover that includes [7,61] and [9,61], and excludes [7,63] and [9,61].
Note, however, that such a reduction of the edit script problem to an edge cover (and thus, weighted matching) problem cannot be exact, given the hardness of the edit script problem. Indeed, our method of assigning costs to edges of the induced graph (Section 5.1) is only approximate, and thus the minimum-cost edge cover is not guaranteed to produce the best solution for the edit script problem.
### 3.4 Generating the Edit Script
Returning to the pruned induced graph of our running example, let us assume that we have gone through the process of determining the cost of each edge, and have computed a minimum-cost edge cover according to these costs, obtaining the edge cover represented by the bold edges in Figure 3. Our next step consists of using this edge cover to compute an edit script that transforms the tree $T_1$ to the tree $T_2$. Our algorithm CtoS (Cover-to-Script) for this purpose is described in Section 5. Here, we briefly illustrate some of the ideas used by the algorithm by considering its action on an edge in the edge cover for our running example.
Consider the edge $e_1 = [7,52]$ of the edge cover depicted by the bold lines in Figure 3. In Figure 4, we depict this edge in relation to the original trees. (We also depict two other edges from the edge cover. The edge cover edges are shown as dashed lines in Figure 4. We observe that there is one other edge in the edge cover that is incident on node 7, viz. [7,61], suggesting that the node 7 was copied either directly, or indirectly (due to one of its ancestors being copied). Furthermore, we note that the parent (node 4) of node 7 is matched to the parent (node 55) of node 61 (i.e., the edge [4,55] exists in the edge cover), while the parent of node 52 is not matched to the parent of node 7. This matching of the parents suggests that node 61 is the original instance of node 7, while node 52 is the copy. We therefore generate a copy operation that copies the subtree rooted at node 7 to the location of node 52. A convenient way of depicting this copy operation is by annotating the corresponding edge ([7,52] in our example) with a CPY mark: this scheme allows us to talk about edit operations without having to refer to explicit node identifiers. Edges that do not correspond to any edit operation (e.g., [6,57] in our example) are annotated with a NIL mark. In the sequel, we will use such edge annotations interchangeably with the actual edit operations that they represent.
Consider next the edges [8,53] and [8,62]. Although both these edge cover edges are incident on node 8, neither of them corresponds to a CPY operation, since the copy 52 of node 8 is generated "for free" when node 7 is copied. Therefore, both these edges are annotated NIL. Proceeding thusly, we annotate all the edges in the edge cover of our running example, to obtain the annotated edge cover depicted in Figure 5, which shows only the edges with non-nil annotations, for clarity. These annotations correspond to the edit script $(\text{INS}(g,1,\{9\}), \text{MOV}(2,6), \text{CPY}(7,1))$. We see that this edit script is identical to the one in Example 2.1, which happens to be a minimum cost edit script for our example. Of course, the above edit operations may also be listed in the order $(\text{MOV}(2,6), \text{CPY}(7,1), \text{INS}(g,1,\{9\}))$. Both edit scripts have the same final effect, and have the same cost. In general, all edit scripts corresponding to a set of annotated edges have the same overall effect and the same cost.
method for generating an edit script from an edge cover of the induced graph. In Section 5, we describe how the cost of an edit script is distributed over the edges of the corresponding edge cover of the induced graph. In that section, we also describe how this cost function is approximated by deriving upper and lower bounds on the cost of an edge of the induced graph, and how these bounds are used to prune the induced graph. Since finding a minimum-cost edge cover for a bipartite graph with fixed edge costs is a problem that has been previously studied in the literature [PS82, Law76], we do not present the details in this paper.
4 Edge Covers and Edit Scripts
In this section, we describe algorithm CtoS, which generates an edit script between two trees, given an edge cover of their induced graph. Before we can describe this algorithm, we need to understand the relationship between an edit script and the induced graph. Therefore, we first define the edge cover induced by an edit script. That is, we describe how, given an edit script between two trees, we generate an edge cover of the induced graph. (Note that this process is the reverse of the process the algorithm CtoS performs. However, a definition of this reverse process is needed for the description of the algorithm.)
4.1 Edge Cover Induced by an Edit Script
In Section 3, we introduced the graph induced by two trees $T_1$ and $T_2$ as the complete bipartite graph $B = (U, V, U \times V)$, with $U = N_1 \cup \{\oplus\}$ and $V = N_2 \cup \{\ominus\}$ (where $N_1$ and $N_2$ are the nodes of $T_1$ and $T_2$, respectively). Let $\mathcal{E}$ be an edit script that transforms $T_1$ to $T_2$; that is, $T_1 \xrightarrow{\mathcal{E}} T_2$. We now define the edge cover $K(\mathcal{E})$ induced by $\mathcal{E}$. Intuitively, we obtain $K(\mathcal{E})$ as follows. Create a copy $T_3$ of $T_1$, and introduce an edge between each node in $T_1$ and its copy in $T_3$. Apply the edit script to $T_3$, moving, copying, etc. the end-points of the edges with the nodes they are attached to as nodes are moved, copied, etc. Thus, when an a node $n \in T_1$ is copied, producing node $n'$, any edge $[m, n]$ is split to produce an new edge $[m, n']$. The other edit operations are handled analogously. Furthermore, an edge between the special nodes $\oplus$ and $\ominus$ is added initially, and removed when it is no longer needed to cover either $\oplus$ or $\ominus$. Due to space limitations, we illustrate the definition of the edge cover induced by an edit script informally using an example; the formal definition is in [CGM97].
Example 4.1 Consider the edit script from Example 2.1, and the initial tree $T_1$ from Figure 1. As described above, our first step consists of creating a copy $T_3$ of $T_1$, and adding an edge between each node of $T_1$ and its counterpart in $T_3$. We also add the special nodes $\oplus$ and $\ominus$, along with an edge connecting them. The result of this step is depicted in Figure 6. For clarity in presentation, the edges between the nodes of $T_1$ and their counterparts in $T_3$ are not shown in Figure 6; instead, we encode these edges using the node identifiers of $T_1$ and $T_3$. That is, as indicated in the figure, imagine an edge $[n, n + 30], \forall n = 1 \ldots 10$.

Our next step consists of applying the edit script from Example 2.1 to the tree $T_3$. To enable this application of the edit script for $T_1$ to $T_2$, we change the node identifiers in the edit script from the identifiers of the nodes of $T_1$ to those of $T_3$, obtaining $\mathcal{E}_1 = (\text{INS}(41, g, 31, \{39\}), \text{MOV}(32, 36), \text{CPY}(37, 31))$. As a result of the INS operation, a node with identifier 41 and label $g$ is inserted as a child of node 31, and node 37 is made its child. In addition, we add an edge $[\emptyset, 41]$ to the induced edge cover. Next, consider the action of the MOV operation, which moves node 32 to become a child of node 37. This operation does not add any new edges to the edge cover. (The existing edges $[2, 32]$ and $[3, 33]$ continue to exist.) Finally, the CPY operation creates a copy of the subtree rooted at node 30, and inserts this copy as a child of node 31. In addition, the edges $[7, 42]$ and $[8, 43]$ are added to the edge cover. The result is depicted in Figure 7, which also omits edges $[n, n + 30], \forall n = 1 \ldots 10$ for clarity. Note that the transformed tree $T_3$ is now isomorphic to the tree $T_2$ in Example 2.1, so that essentially, we now have an edge cover of the induced graph of $T_1$ and $T_2$.
4.2 Using Edge Covers to Generate Edit Scripts
The goal of using an edge cover is that it should capture the essential aspects of an edit script; that is, no important information should be lost in going from an edit script to the edge cover induced by it. However, there are certain edit scripts for which this property does not hold. For example, consider an edit script $\mathcal{E}_2$ that inserts a node $p$ as the parent of ten siblings (children of the same parent) $n_1, \ldots, n_{10}$, then moves $p$ to another location in the tree, and finally deletes $p$. The node $p$ is present from both the initial tree to the final tree. Therefore, an edge cover of the initial and final tree contains no record of the temporary insertion of node $p$. Thus, we have lost some information in going from $\mathcal{E}_2$ to the edge cover.

cost of one move, plus the cost of one delete, for a total cost of 3. If we do not use the "bulk move trick" that \( E_2 \) uses, we need to move each of \( n_1, \ldots, n_{10} \) individually, for a cost of 10. Thus, \( E_2 \) could be the minimum cost edit script, and if we rule it out, then \( MH-DIFF \) would miss it.
On the other hand, scripts like \( E_2 \) do not represent transformations that are meaningful or intuitive to an end user. In other words, if a user saw \( E_2 \), he would not understand why node \( p \) was inserted, since it really has no function in his application. True, the costs provided by the user are intended to describe the desirability of edit operations, but if we abuse these numbers we can end up with "tricky" scripts like \( E_2 \) that are more confusing than helpful.
Another example of a potentially unintuitive edit script is the following: Consider an edit script \( E_3 \) that moves a node \( n_1 \) to become a child of another node \( n_2 \), then makes several copies of the subtree rooted at \( n_2 \) (thus making copies of \( n_1 \) as well), and finally deletes the original copy of \( n_1 \). This edit script moves \( n_1 \) to a place where it does not need to be (under \( n_2 \)) only to generate free copies of \( n_1 \).
The cause of the unintuitive nature of the edit scripts described above is an interaction between different edit operations, which gives rise to a "compound" effect. For example, in the edit script \( E_2 \) above, the effect of the move operation is compounded because it acts on a node that was previously inserted. Similarly, in edit script \( E_3 \) above, the effects of the copy operations are compounded because they act on a subtree into which a node was previously moved. Our approach is to disallow such unintuitive compound effects.
A simple way of characterizing edit scripts that disallow undesirable compound effects is to require edit operations to occur in phases, and to order the phases appropriately. In the following discussion, we use the names \( INS \), \( DEL \), etc. to denote phases consisting of, respectively, \( INS \) operations, \( DEL \) operations, etc. First, we require that the \( INS \) phase occur after the \( DEL \) phase, so that an edit script cannot first insert a node and then delete it. Next, we require the other edit phases (\( UPD \), \( MOV \), \( CPY \), and \( GLU \)) to occur after the \( DEL \) phase (so that nodes operated on by these phases cannot be later deleted), and before the \( INS \) phase (so that inserted nodes cannot be operated on by these phases). Furthermore, we require that the \( UPD \) (respectively, \( MOV \)) phase occur after the \( CPY \) phase and before the \( GLU \) phase, so that an edit script cannot copy the effect of an \( UPD \) (respectively, \( MOV \)) operation by copying the updated node (and similarly for glues). These ordering constraints yield the following order of edit phases: \( DEL \), \( CPY \), \( UPD \), \( MOV \), \( GLU \), \( INS \). (We chose the relative order of the \( UPD \) and \( MOV \) phases arbitrarily.)
One additional restriction, not covered by the above ordering constraint, is the following: A node in a subtree operated on by a \( CPY \) operation cannot be operated on by a \( GLU \) operation. We call edit scripts that satisfy these restrictions structured edit scripts. In the sequel, we consider only structured edit scripts. Structured edit scripts have the following important property that allows us to consider only minimal edge covers in the sequel. (A minimal edge cover is an edge cover that is not a proper superset of any edge cover.)
Lemma 4.1. The edge cover induced by a structured edit script is minimal.
The reader may observe that, in addition to disallowing unintuitive compound effects, the above restrictions also disallow some intuitive sequences of operations. For example, a structured edit script cannot delete a node produced as a result of a \( CPY \) operation. Therefore, a structured edit script cannot copy a subtree containing 100 nodes if 99 of them are needed, because it would be unable to delete the unwanted copy of the 100th node. An analogous situation exists for \( INS \) and \( GLU \) operations. Our algorithms [CGM97] actually do permit such deletions (called ghost deletions) after copies, and insertions (called ghost insertions) before glues. For similar reasons, we also permit certain move operations to occur before the \( CPY \) phase. Furthermore, we allow a move or copy operation to a destination that is currently unavailable (e.g., because it is produced by a copy operation) to be "paused" until the destination becomes available.
We now describe how, given a minimal edge cover \( K \) of the graph induced by (trees \( T_1 \) and \( T_2 \), we compute a minimum-cost edit script corresponding to this edge cover. As explained in Section 3, we also represent the edit operations of such an edit script as annotations on the affected edges. Due to space constraints, we do not present the full details of our algorithm \( CtoS \) (cover-to-script) in this paper, and present instead a brief explanation of the basic ideas behind the algorithm. The detailed algorithm is presented in [CGM97].
The algorithm proceeds in phases that roughly reflect the phases of a structured edit script described above. We refer to edges belonging to the given edge cover \( K \) as \( K \)-edges. We say two nodes are matched to each other if there is a \( K \)-edge connecting them. The first phase of the algorithms is the delete phase, in which we generate an edit operation \( DEL(m) \) for each node \( m \) that is matched to the special node \( \emptyset \). We claim that any edit script that matches \( m \) to \( \emptyset \) must contain this \( DEL \) operation, due to the following observations: Firstly, any node matched to \( \emptyset \) is absent from the final tree. Furthermore, there are only two ways in which a node can be made to disappear: either it is deleted explicitly, or it is glued to some other node. (We use here the fact that structured edit scripts cannot first glue a node to another and then delete the second node.) However, the second method will not result in \( m \) matching \( \emptyset \) in the edge cover induced by the script; instead, \( m \) will match the node to which it was glued. Therefore we can safely produce a \( DEL(m) \) operation for all such nodes \( m \).
The next phase of the algorithm handles copy operations. In particular, it looks for sets two or more of \( K \)-edges incident on a common node \( m \in T_1 \). Note that from Lemma 4.1, and the observation that minimal edge covers cannot contain any path of length three, it follows that if \( e = [m,n] \) is such an edge, there can be no other \( K \)-edge incident on \( n \). We call such a set of edges a flower with base \( m \). This set of edges represents copies of the node \( m \). However, as we have seen in Section 3, some of the copies of \( m \) could be produced as a result of some ancestor of \( m \) being copied. We call such copies free copies of \( m \). Our algorithm considers flowers in preorder of the base nodes. As copy operations are generated for some node \( m \), we also keep track of the number of free copies of nodes in the copied subtree. Knowing the number of available free copies allows us to determine exactly which flowers correspond to explicit copy operations and which correspond to implicit (free) copies. Furthermore, any unused free copies are nodes that need to be deleted after the copy operation is performed. These are the ghost deletions we introduced above. Finally, note that a free copy may need to be moved to its final location; this situation is easily detected by checking whether the parents of the affected nodes match.
The update phase of the algorithm is straightforward, and produces an update operation for each edge $[m, n]$ such that the labels of $m$ and $n$ differ. Since we are considering only structured edit scripts, there is no way to avoid such an update; in particular, "tricks" like updating a node and then copying it are disallowed. The glue and delete phases of the algorithm are analogous to the copy and insert phases, respectively. The details are in [CGM97].
5 Finding the Edge Cover
In this section we describe how MH-DIFF finds a minimal edge cover of the induced graph. The resulting cover will serve as input to algorithm CtoS (Section 4). Our goal is to find not just any minimal edge cover, but one that corresponds to a minimum-cost edit script. Let us call such an minimal edge cover the target cover.
Consider an edge $e$ in our pruned induced graph. To get the target cover, MH-DIFF must decide whether $e$ should be included in the cover. To reach this decision, it would be nice if MH-DIFF knew the "cost" of $e$. That is, if $e$ remains in the target cover, then it would be annotated (by algorithm CtoS) with some operation, and we could say that the cost of this operation is the cost of $e$. Unfortunately, we have a "chicken and the egg problem" here: CtoS cannot run until we have the target cover, and we cannot get the target cover until we know the costs it will imply. To break the impasse, our approach uses the following idea:
Instead of trying to compute the actual cost of $e$, we compute an upper and lower bound to this cost. These bounds can be computed without the knowledge of which other edges are included in the target cover, and serve two purposes: Firstly, they allow us to design pruning rules that are used to conservatively eliminate unnecessary edges from the induced graph. Secondly, after pruning, the bounds can guide our search for the target cover.
As an enhancement, we actually use a variation on the edge cost suggested above. The following example shows that simply "charging" each annotation to the edge it is on is not entirely "fair". We are given a tree $T_1$, containing two nodes, $n_1$ and $n_2$ with the same label $l$. Furthermore $n_1$ has children $n_{11}$ and $n_{12}$ with labels $a$ and $b$, respectively, and $n_2$ has children $n_{21}$ and $n_{22}$ with labels $c$ and $d$, respectively. Suppose $T_2$ is a logical copy of $T_1$. (That is, $T_1$ and $T_2$ are isomorphic.) Consider an edge cover that matches each node in $T_1$ to its copy in $T_2$ except that it "cross matches" $n_1$ and $n_2$ across the trees, as shown in Figure 8. Given this edge cover, algorithm CtoS will produce a move operation for each of the edges $n_{11}, n_{12}, n_{21}, n_{22}$, and $n_{22}$, and $n_{22}$, but instead, by the mismatching of $n_1$ and $n_2$. Therefore it would be intuitively more fair to charge these move operations to the edges responsible for the mismatch, viz. $[n_1, n_2]$ and $[n_2, n_1]$. To achieve this, we use the following scheme: If $e$ is annotated with INS, DEL, or UPD in the target cover, we do charge $e$ for this operation. However, if $e$ is annotated with MOV, CPY, or GLU, then the parent of $e$, and not $e$ is charged. We call the edge costs computed in such a fashion fair costs, and define them below:
Figure 8: Distributing edge costs fairly
5.1 An Edge-wise Cost Function
Let $K$ be an annotated minimal edge cover. For an edge $e \in K$, if the annotation on $e$ is MOV, CPY, or GLU, let $c_s(e)$ denote the cost of that operation. If $e$ is annotated with INS, DEL, or UPD, then let $c_s(e)$ denote the cost of the operation. Furthermore, let $E(m)$ be the set of edges in $K$ that are incident on $m$, that is, $E(m) = \{[m, n] \in K \mid m, n \in m\}$. Let $C(m)$ be the set of the children of $m$. We then define the fair cost of each edge $[m, n] \in K$ as follows:
$$c_K([m, n]) = c_s(m, n) + \frac{1}{2|E(m)|} \sum_{m' \in C(m)} \sum_{n' \in K} c_s([m', n']) + \frac{1}{2|E(n)|} \sum_{n' \in C(n)} \sum_{m' \in K} c_s([m', n'])$$
Note that this cost depends on $K$, and thus is not a function of $e$ alone. The following lemma, proved in [CGM97], states that the above scheme of distributing the cost of an edge cover over its component edges is a sound one; that is, adding up the cost edge-wise yields the overall cost of the edge cover (i.e., the cost of the corresponding edit script).
Lemma 5.1 If $K$ is an annotated, minimal edge cover of the graph induced by two trees, then $c(K) = \sum_{e \in E} c_K(e)$.
5.2 Bounds on Edge Costs
Although Lemma 5.1 suggests a method of distributing the cost of an annotated edge cover (and thus an edit script) over the component edges, the cost of each edge depends on the other edges present in the edge cover, and is thus not directly useful for computing a minimum-cost edge cover. However, we use that distribution scheme to derive upper and lower bounds on the fair cost $c_K(e)$ of an edge $e$ over all minimal edge covers $K$.
Intuitively, given that the cost of any UPD annotation on an edge is charged to that edge (by Equation 1), a simple choice for the lower bound on the cost of an edge $[m, n]$ is simply the cost $c_s(m, n)$ of updating the label $m$ to that of $n$. However, we can do a little better. In some cases, selecting an edge $[m, n]$ (as part of the edge cover being constructed) may force some of the children $m'$ of $m$ to be moved to $n$. In particular, this happens for those children of $m'$ for which there is no edge that could possibly match $m'$ to a child of $n$. We call such moves forced moves. In cases where we can determine a forced move exists, the cost of a MOVE is added to the lower bound cost. However, according to Equation 1 not all the cost of a forced move goes to edge $[m, n]$. In the worst
rules we use to reduce the size of the induced graph of the two trees being compared. Let $e_1 = [m, n]$ be any edge in the induced graph. Let $e_2$ be any edge incident on $m$, and let $e_3$ be any edge incident on $n$. Intuitively, our first pruning rules removes an edge with a lower bound cost that is so high that it is preferable to match each of its nodes using some other edge that has a suitably lower upper bound cost.
Pruning Rule 1 Let $C_i = \max\{c_{\text{ub}}(e_1), c_{\text{ub}}(e_2), c_{\text{ub}}(e_3)\}$. If $c_{\text{ub}}(e_1) \geq c_{\text{ub}}(e_2) + c_{\text{ub}}(e_3) + 2C_i$ then prune $e_1$.
Example 5.1 To illustrate this rule, consider a tree $T_1$ containing, among others, two childless nodes 1 (label $f$) and 2 (label $g$). Similarly, $T_2$ contains childless nodes 3 (label $g$) and 4 (label $f$), among others. Say the costs $c_{\text{ub}}(f, g)$ and $c_{\text{ub}}(g, f)$ are one unit each, while the update costs are $c_{\text{ub}}(f, g) = 3$, and $c_{\text{ub}}(f, f) = c_{\text{ub}}(g, g) = 0$. Let us now consider if edge $e_1 = [1, 2]$ can be pruned because edges $e_2 = [1, 4]$ and $e_3 = [2, 3]$ exist. Since the nodes have no children, it is easy to compute $c_{\text{ub}}(e_1) = c_{\text{ub}}(f, g) = 3$, $c_{\text{ub}}(e_2) = c_{\text{ub}}(f, f) = 0$, and $c_{\text{ub}}(e_3) = c_{\text{ub}}(g, g) = 0$. Since $C_1 = 1$, we see that Pruning Rule 1 holds and $e_1$ can be safely removed.
Our second pruning rule (already illustrated in Section 3) states that if it is less expensive to delete a node and insert another, we do not need to consider matching the two nodes to each other. More precisely, we state the following:
Pruning Rule 2 If $c_{\text{ub}}(e_1) \geq c_{\text{ub}}(e_2) + c_{\text{ub}}(e_3)$ then prune $e_1$.
Note that the above pruning rules are simpler to apply if we let $e_2$ and $e_3$ be the minimum-cost edge incident on $m$ and $n$, respectively. The following lemma, proved in [CGM97], tells us that the pruning rules are conservative:
Lemma 5.3 Let $\mathcal{E}$ be the set of edges pruned by repeated application of Pruning Rules 1 and 2. Let $K_1$ be any minimal edge cover of the graph $B$. There exists a minimal edge cover $K_2$ such that (1) $K_2 \cap \mathcal{E} = \emptyset$, and (2) $O(K_2) \leq O(K_1)$.
The pruning phase of our algorithm consists of repeatedly applying Pruning Rules 1 and 2. Note that the absence of edges raises the upper bound function, and lowers the upper bound function, thus possibly causing more edges to get pruned. Our algorithm updates the cost bounds for the edges affected by the pruning of an edge whenever the edge is pruned. By maintaining the appropriate data structures, such a cost-update step after an edge is pruned can be performed in $O(\log n)$ time, where $n$ is the number of nodes in the induced graph.
5.4 Computing a Min-Cost Edge Cover
After application of the pruning rules described above, we obtain a pruned induced graph, containing a (typically small)
subset of the edges in the original induced graph. In favorable cases, the remaining edges contain only one minimal edge cover. However, typically, there may be several minimal edge covers possible for the pruned induced graph. We now describe how we select one of these minimal edge covers.
We first approximate the fair cost of every edge $e$ that remains after pruning by its lower bound $e_{\text{LB}}(e)$. (We could have also use the upper bound, or an average of both bounds, since this is only an estimate.) Then, given these constant estimated costs, we compute a minimum-cost edge cover by reducing the edge cover problem to a bipartite weighted matching problem, as suggested in [PS82]. Since the weighted matching problem can be solved using standard techniques, we do not present the details in this paper, noting only that given a bipartite graph with $n$ nodes and $e$ edges, the weighted matching problem can be solved in time $O(ne)$. For our application, $e$ is the number of edges that remain in the induced graph after pruning.
6 Implementation and Performance
In this section, we describe our implementation of MH-DIFF, and discuss its analytical and empirical performance. Figure 9 depicts the overall architecture of our implementation, with rectangles representing the modules (numbered, for reference) of the program, and other shapes representing data. Given two trees $T_1$ and $T_2$ as input, Module 1 constructs the induced graph (Section 3.1). This induced graph is next pruned (Module 2) using the pruning rules of Section 5.2 to give the pruned induced graph. In Module 2, the update cost for each edge in the induced graph is computed using the domain-dependent comparison function for node labels (Section 2.2). The next three modules together compute a minimum-cost edge cover of the pruned induced graph using the reduction of the edge cover problem to a weighted matching problem [PS82]. That is, the pruned induced graph is first translated (by Module 3) into an instance of a weighted matching problem. This weighted matching problem is solved using a package (Module 4) [Rot] based on standard techniques [PS82]. The output of the weighted matching solver is a minimum-cost matching, which is translated by Module 5 into $K_0$, a minimum-cost edge cover of the pruned induced graph. Next, Module 6 uses the minimum-cost edge cover computed, to produce the desired edit script, using the method described in Section 4.2.
Let us now analyze the running time of our program. Let $n$ be the total number of nodes in both input trees $T_1$ and $T_2$. Constructing the induced graph (Module 1, in Figure 9) involves building a complete bipartite graph with $O(n)$ nodes on each side. We also evaluate the domain-dependent label-comparison function for each pair of nodes, and store this cost on the corresponding edge. Thus, building the induced graph requires time $O(kn^2)$, where $k$ is the cost of the domain-dependent comparison function. Next, consider the pruning phase (Module 2). By maintaining a priority queue (based on edge costs) of edges incident on each node of the induced graph, the test to determine whether an edge may be pruned can be performed in constant time. If the edge is pruned, removing it from the induced graph requires constant time, while removing it from the priority queue at each of its nodes requires $O(\log n)$ time. When an edge $[m, n]$ is pruned, we also record the changes to the costs $c_{mc}(m, p(n))$, $c_{mc}(n, p(m))$, $c_{mf}(m, p(n))$, and $c_{mf}(n, p(m))$, which can be done in constant time. Thus, pruning an edge requires $O(\log n)$ time. Since at most $O(n^2)$ are pruned, the total worst case cost of the pruning phase is $O(n^2 \log n)$. Let $e$ be the number of edges that remain in the induced graph after pruning. The minimum-cost edge cover is computed in time $O(ne)$ by Modules 3, 4, and 5. The computation of the edit script from the minimum-cost edge cover can be done in $O(n)$ time by Module 6. (Note that the number of edges
in a minimal edge cover is always $O(n)$.)
The number of edges that remain in the induced graph after pruning (denoted by $e$ above) is an important metric for three main reasons. First, as seen above, a lower number of edges results in faster execution of the minimum-cost edge cover algorithm. Second, a smaller number of edges decreases the possibility of finding a suboptimal edge cover, since there are fewer choices that need to be made by the algorithm. Thirdly, having a smaller number of edges in the induced graph reduces exponentially the size of the space of candidate minimal edge covers that the search module needs to explore.
We have also studied the quality of the initial solution produced by MH-DIFF. In particular, we are interested in finding out in what fraction of cases our method produces suboptimal initial solutions, and by how much the cost of the suboptimal solution exceeds that of the optimal. Given the exponential (in $e$) size of the search space of minimal edge covers of the induced graph, it is not feasible to try exhaustive searches on large datasets. However, we have exhaustively searched the space of minimal edge covers, and corresponding edit scripts, for smaller datasets. We ran 50 experiments, starting with an input tree $T_i$ derived as in the experiments for $e$ above, and using 6 randomly generated edit operations to generate an output tree. We searched the space of minimal edge covers of the pruned induced graph exhaustively for these cases, and found that the MH-DIFF initial solution differed from the minimum-cost one in only 2 cases out of 50. That is, in 96% of the cases MH-DIFF found the minimum cost edit script, and of course it did this in much less time than the exhaustive method. In the two cases where MH-DIFF missed, the resulting script cost about 15% more that the minimum cost possible.

Given the importance of the metric $e$, we have conducted a number of experiments to study the relationship between $e$ and $n$. We start with four "input" trees representing actual results of varying sizes from our Tsimmis system. For each input tree, we generate a batch of "output" trees by applying a number of random edits. The number of random edits is either 10% or 20% of the number of nodes in the input tree.
Then for each output tree, we run MH-DIFF on it and its original input tree. The results are summarized by the graph in Figure 10. The horizontal axis indicates the total number of nodes in the two trees being compared (and hence, in the induced graph). The vertical axis indicates the number of edges that remain after pruning the induced graph. Note that the ideal case (best possible pruning) corresponds to $e = \lfloor n/2 \rfloor$, since we need at least $\lfloor n/2 \rfloor$ edges to cover $n$ nodes, whereas the worst case is $e = n^2$ (no pruning at all). For comparison, we have also plotted $e = n/2$ and $e = n^2$ on the graph in Figure 10. We observe that the relationship between $e$ and $n$ is close to linear, and that the observed values of $e$ are much closer to $n/2$ than to $n^2$.
Note that in Figure 10 we have plotted the results for two different values of $d$, the percentage of random edit operations applied to the input tree. We see that, for a given value of $n$, a higher value of $d$ results in a higher value of $e$, in general. We note that some points with a higher $d$ value seem to have a lower value of $e$ than the general trend. This is because applying $d$ random edits is not the same as having the input and output trees separated by $d$ edits, due to the possibility of redundant edit operations. Thus, some data points, even though they were obtained by applying $d$ random edits, actually correspond to fewer changes in the tree.
7 Related Work
The general problem of detecting changes from snapshots of data has been studied before from different angles. For example, [WF74] defines a string-to-string correction problem as the problem of finding the best sequence of insert, delete, and update operations that transform one string to another. The problem is developed further in [Wag75], which adds the "swap" operation to the list of edit operations. These papers also introduce the structure of a "trace" or a matching between the characters of the strings being compared as a useful tool for computing an edit script. A simpler change detection problem for strings, using only insertions and deletions as edit operations has been studied extensively in [Mye86, WMG90]. The idea of a longest common subsequence replaces the idea of a trace in this simpler problem. A variant of the algorithm presented in [Mye86] for computing the longest common subsequence is implemented in the gnudiff [HHS+] program. All these algorithms work with strings, that is, with flat-file, or relational data, and are not suitable for computing changes in structured data.
In [ZS90], the authors define a change detection problem for ordered trees, using insertion, deletion, and label-update as the edit operations, observing its added difficulty compared to the equivalent problem for strings; they also present an efficient dynamic-programming based algorithm to solve that problem. A proof of the $NP$-hardness of a similar change detection problem (using insertion, deletion, and label-update) for unordered trees is presented in [ZWS95], which also presents an algorithm for a restricted version of the change detection problem. In [ZWWS94], the authors present an enumerative (exponential time) algorithm for the change detection problem for unordered trees, as well as heuristic algorithms based on search techniques such as simulated annealing. An important assumption made by the algorithms in [ZS90, ZWS95, ZWWS94] is that the cost of updating any label to any other label is always less than the cost of deleting a node with the old label and inserting a node with the new label. While this restriction is reasonable for some domains, it does not always lead to
5In these preliminary experiments, we used a slightly different version of the algorithm described in Section 4.1; we believe that the differences do not impact the results significantly.
intuitive results. For example, consider two trees with the same structure, but completely different labels on the nodes (e.g., two trees representing different query results, but with a similar structure). Assuming the cost of label update is always lower than the cost of the corresponding insertion and deletion will result in an edit script that simply updates all the labels in the trees. While this is technically sound, it is not the semantically desirable result for this example.
In [CRGMW96] we defined a variant of the change detection problem for ordered trees, using subtree moves as an edit operation in addition to insertions, deletions, and updates, and presented an efficient algorithm for solving it. That algorithm uses domain characteristics to find a solution efficiently. A major drawback of the algorithm in [CRGMW96] is that it assumes that the number of duplicates (or near duplicates) in the labels found in the input trees is very small. Another drawback of the algorithm in [CRGMW96] is that it assumes each node of the input trees has a special tag that describes its semantics. (For example, an ordered tree representing a document may have tags “paragraph,” “section,” etc.) Furthermore, that algorithm assumes the existence of a total order < on these tags such that a node with tag ti cannot be the child of a node with tag t2 unless ti ≤ t2. While these assumptions are reasonable in a text comparison scenario, there are many domains in which they do not hold.
The work presented in this paper differs from previous work in several important ways. Firstly, we detect the change detection problem for unordered trees, which is inherently harder than the similar problem for ordered trees. Secondly, we consider a rich set of edit operations, including copy and move operations, that make the edit script computed more meaningful and intuitively usable. Furthermore, we do not assume that the nodes of the input trees are “tagged” in a manner required by the algorithm in [CRGMW96], nor do we assume the absence of duplicates (or near duplicates) in the labels of the nodes in the input trees. Finally, we do not assume that the cost of updating any label to any other label is always less than the cost of deletion and insertion.
8 Conclusion
We have described the need for computing semantically meaningful changes in structured data. We have introduced operations such as subtree copy and subtree move that allow us to describe changes to structured data more meaningfully than is possible by using only the traditional insert, delete, and update operations. We have formally defined the problem of computing a minimum-cost edit script, consisting of these operations, between two trees. To solve this problem, we have presented an algorithm that is based on representing an edit script between two trees as an edge cover of a bipartite graph induced by the trees. We have also studied the performance of our algorithm both analytically and empirically. The experimental results, although preliminary, are very encouraging.
References
|
{"Source-Url": "http://www.seas.upenn.edu/~zives/03s/cis650/P026.PDF", "len_cl100k_base": 15689, "olmocr-version": "0.1.53", "pdf-total-pages": 12, "total-fallback-pages": 0, "total-input-tokens": 39926, "total-output-tokens": 17625, "length": "2e13", "weborganizer": {"__label__adult": 0.0003292560577392578, "__label__art_design": 0.0005159378051757812, "__label__crime_law": 0.0004198551177978515, "__label__education_jobs": 0.0019741058349609375, "__label__entertainment": 0.00012218952178955078, "__label__fashion_beauty": 0.00022912025451660156, "__label__finance_business": 0.0006580352783203125, "__label__food_dining": 0.00040340423583984375, "__label__games": 0.0007929801940917969, "__label__hardware": 0.002002716064453125, "__label__health": 0.0008311271667480469, "__label__history": 0.00047898292541503906, "__label__home_hobbies": 0.00022780895233154297, "__label__industrial": 0.0007147789001464844, "__label__literature": 0.00046896934509277344, "__label__politics": 0.00030922889709472656, "__label__religion": 0.0005369186401367188, "__label__science_tech": 0.37060546875, "__label__social_life": 0.00013303756713867188, "__label__software": 0.0225677490234375, "__label__software_dev": 0.5947265625, "__label__sports_fitness": 0.00030303001403808594, "__label__transportation": 0.000644683837890625, "__label__travel": 0.00021922588348388672}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 66494, 0.01839]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 66494, 0.53595]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 66494, 0.9189]], "google_gemma-3-12b-it_contains_pii": [[0, 4510, false], [4510, 11131, null], [11131, 16717, null], [16717, 23394, null], [23394, 28043, null], [28043, 33578, null], [33578, 41450, null], [41450, 47255, null], [47255, 50250, null], [50250, 54280, null], [54280, 60511, null], [60511, 66494, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4510, true], [4510, 11131, null], [11131, 16717, null], [16717, 23394, null], [23394, 28043, null], [28043, 33578, null], [33578, 41450, null], [41450, 47255, null], [47255, 50250, null], [50250, 54280, null], [54280, 60511, null], [60511, 66494, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 66494, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 66494, null]], "pdf_page_numbers": [[0, 4510, 1], [4510, 11131, 2], [11131, 16717, 3], [16717, 23394, 4], [23394, 28043, 5], [28043, 33578, 6], [33578, 41450, 7], [41450, 47255, 8], [47255, 50250, 9], [50250, 54280, 10], [54280, 60511, 11], [60511, 66494, 12]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 66494, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
f411940ef7a8ebf24d41f6eb1a1dd749fe1b3e11
|
[REMOVED]
|
{"len_cl100k_base": 11525, "olmocr-version": "0.1.50", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 56422, "total-output-tokens": 13538, "length": "2e13", "weborganizer": {"__label__adult": 0.0008897781372070312, "__label__art_design": 0.0022449493408203125, "__label__crime_law": 0.0007653236389160156, "__label__education_jobs": 0.407958984375, "__label__entertainment": 0.0002841949462890625, "__label__fashion_beauty": 0.0005850791931152344, "__label__finance_business": 0.0011377334594726562, "__label__food_dining": 0.0011796951293945312, "__label__games": 0.0017461776733398438, "__label__hardware": 0.0017328262329101562, "__label__health": 0.0012845993041992188, "__label__history": 0.0013093948364257812, "__label__home_hobbies": 0.0005040168762207031, "__label__industrial": 0.0010576248168945312, "__label__literature": 0.0017175674438476562, "__label__politics": 0.0008769035339355469, "__label__religion": 0.0014629364013671875, "__label__science_tech": 0.034881591796875, "__label__social_life": 0.000713348388671875, "__label__software": 0.0087127685546875, "__label__software_dev": 0.52587890625, "__label__sports_fitness": 0.0009222030639648438, "__label__transportation": 0.0016880035400390625, "__label__travel": 0.0005626678466796875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 58589, 0.02444]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 58589, 0.8886]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 58589, 0.94614]], "google_gemma-3-12b-it_contains_pii": [[0, 1809, false], [1809, 4132, null], [4132, 7362, null], [7362, 9826, null], [9826, 12812, null], [12812, 15717, null], [15717, 18651, null], [18651, 21605, null], [21605, 24603, null], [24603, 25662, null], [25662, 27153, null], [27153, 29952, null], [29952, 32270, null], [32270, 35058, null], [35058, 37226, null], [37226, 40378, null], [40378, 43437, null], [43437, 46487, null], [46487, 49460, null], [49460, 52393, null], [52393, 55567, null], [55567, 56097, null], [56097, 57674, null], [57674, 58589, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1809, true], [1809, 4132, null], [4132, 7362, null], [7362, 9826, null], [9826, 12812, null], [12812, 15717, null], [15717, 18651, null], [18651, 21605, null], [21605, 24603, null], [24603, 25662, null], [25662, 27153, null], [27153, 29952, null], [29952, 32270, null], [32270, 35058, null], [35058, 37226, null], [37226, 40378, null], [40378, 43437, null], [43437, 46487, null], [46487, 49460, null], [49460, 52393, null], [52393, 55567, null], [55567, 56097, null], [56097, 57674, null], [57674, 58589, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 58589, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 58589, null]], "pdf_page_numbers": [[0, 1809, 1], [1809, 4132, 2], [4132, 7362, 3], [7362, 9826, 4], [9826, 12812, 5], [12812, 15717, 6], [15717, 18651, 7], [18651, 21605, 8], [21605, 24603, 9], [24603, 25662, 10], [25662, 27153, 11], [27153, 29952, 12], [29952, 32270, 13], [32270, 35058, 14], [35058, 37226, 15], [37226, 40378, 16], [40378, 43437, 17], [43437, 46487, 18], [46487, 49460, 19], [49460, 52393, 20], [52393, 55567, 21], [55567, 56097, 22], [56097, 57674, 23], [57674, 58589, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 58589, 0.07326]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
3affaf4301137b64eec6796f5bf810c51cf1446c
|
4.7.5 Libraries and Packages
A VHDL library is a place where the VHDL compiler stores information about a particular design project, including intermediate files that are used in the analysis, simulation, and synthesis of the design. The location of the library within a host computer's file system is implementation dependent. For a given VHDL design, the compiler automatically creates and uses a library named "work".
A complete VHDL design usually has multiple files, each containing different design units including entities and architectures. When the VHDL compiler analyzes each file in the design, it places the results in the "work" library, and it also searches this library for needed definitions, such as other entities. Because of this feature, a large design can be broken up into multiple files, yet the compiler will find external references as needed.
Not all of the information needed in a design may be in the "work" library. For example, a designer may rely on common definitions or functional modules across a family of different projects. Each project has its own "work" library (typically a subdirectory within that project’s overall directory), but it must also refer to a common library containing the shared definitions. Even small projects may use a standard library such as the one containing IEEE standard definitions. The designer can specify the name of such a library using a library clause at the beginning of the design file. For example, we can specify the IEEE library:
```vhdl
library ieee;
```
The clause "library work;" is included implicitly at the beginning of every VHDL design file.
Specifying a library name in a design gives it access to any previously analyzed entities and architectures stored in the library, but it does not give access to type definitions and the like. This is the function of "packages" and "use clauses," described next.
A VHDL package is a file containing definitions of objects that can be used in other programs. The kind of objects that can be put into a package include signal, type, constant, function, procedure, and component declarations.
Signals that are defined in a package are "global" signals, available to any VHDL entity that uses the package. Types and constants defined in a package are known in any file that uses the package. Likewise, functions and procedures defined in a package can be called in files that use the package, and components (described in the next subsection) can be “instantiated” in architectures that use the package.
A design can “use” a package by including a use clause at the beginning of the design file. For example, to use all of the definitions in the IEEE standard 1164 package, we would write
```vhdl
use ieee.std_logic_1164.all;
```
Here, "ieee" is the name of a library which has been previously given in a library clause. Within this library, the file named "std_logic_1164" contains the desired definitions. The suffix "all" tells the compiler to use all of the definitions in this file. Instead of "all", you can write the name of a particular object to use just its definition, for example,
```vhdl
use ieee.std_logic_1164.std_ulogic
```
This clause would make available just the definition of the `std_ulogic` type in Table 4-32 on page 273, without all of the related types and functions. However, multiple "use" clauses can be written to use additional definitions.
Defining packages is not limited to standards bodies. Anyone can write a package, using the syntax shown in Table 4-40. All of the objects declared between "package" and the first "end" statement are visible in any design file that uses the package; objects following the "package body" keyword are local. In particular, notice that the first part includes "function declarations," not definitions. A function declaration lists only the function name, arguments, and type, up to but not including the "is" keyword in Table 4-35 on page 276. The complete function definition is given in the package body and is not visible to function users.
---
**IEEE VHDL STANDARDS**
VHDL has excellent capabilities for extending its data types and functions. This is important, because the language's built-in BIT and BIT_VECTOR actually are quite inadequate for modeling real circuits that also handle three-state, unknown, don't-care, and varying-strength signals.
As a result, soon after the language was formalized as IEEE standard 1076, commercial vendors began to introduce their own built-in data types to deal with logic values other than 0 and 1. Of course, each vendor had different definitions for these extended types, creating a potential "Tower of Babel."
To avoid this situation, the IEEE developed the 1164 standard logic package `std_logic_1164` with a nine-valued logic system that satisfies most designers' needs. This was later followed by standard 1076-3, discussed in Section 5.9.6, which includes several packages with standard types and operations for vectors of `STD_LOGIC` components that are interpreted as signed or unsigned integers. The packages include `std_logic_arith`, `std_logic_signed`, and `std_logic_unsigned`.
By using IEEE standards, designers can ensure a high degree of portability and interoperability among their designs. This is increasingly important, as the deployment of very large ASICs necessitates cooperation not only among multiple designers but also among multiple vendors who may each contribute different pieces of a "system-on-a-chip" design.
4.7.6 Structural Design Elements
We’re finally ready to look at the guts of a VHDL design, the “executable” portion of an architecture. Recall from Table 4-28 on page 271 that the body of an architecture is a series of concurrent statements. In VHDL, each concurrent statement executes simultaneously with the other concurrent statements in the same architecture body.
This behavior is markedly different from that of statements in conventional software programming languages, where statements execute sequentially. Concurrent statements are necessary to simulate the behavior of hardware, where connected elements affect each other continuously, not just at particular, ordered time steps. Thus, in a VHDL architecture body, if the last statement updates a signal that is used by the first statement, then the simulator will go back to that first statement and update its results according to the signal that just changed. In fact, the simulator will keep propagating changes and updating results until the simulated circuit stabilizes; we’ll discuss this in more detail in Section 4.7.9.
VHDL has several different concurrent statements, as well as a mechanism for bundling a set of sequential statements to operate as a single concurrent statement. Used in different ways, these statements give rise to three somewhat distinct styles of circuit design and description, which we cover in this and the next two subsections.
The most basic of VHDL’s concurrent statements is the component statement, whose basic syntax is shown in Table 4-41. Here, component-name is the name of a previously defined entity that is to be used, or instantiated, within the current architecture body. One instance of the named entity is created for
each component statement that invokes its name, and each instance must be
named by a unique label.
The port map keywords introduce a list that associates ports of the named
entity with signals in the current architecture. The list may be written in either of
two different styles. The first is a positional style; as in conventional program-
ning languages, the signals in the list are associated with the entity's ports in the
same order in which they appear in the entity's definition. The second is an
explicit style; each of the entity's ports is connected to a signal using the "=>
operator, and these associations may be listed in any order.
Before being instantiated in an architecture, a component must be declared
in a component declaration in the architecture's definition (see Table 4-28 on
page 271). As shown in Table 4-42, a component declaration is essentially the
same as the port-declaration part of the corresponding entity declaration—it lists
the name, mode, and type of each of its ports.
The components used in an architecture may be ones that were previously
declared as part of a design, or they may be part of a library. Table 4-43 is an
example of a VHDL entity and its architecture that uses components, a "prime-
number detector" that is structurally identical to the gate-level circuit in
Figure 4-30(c) on page 226. The entity declaration names the inputs and the
output of the circuit. The declarations section of the architecture defines all of
the signal names and the components that are used internally. The components,
INV, AND2, AND3, and OR4, are predefined in the design environment in which
this example was created and compiled (Xilinx Foundation 1.5, see References).
Note that component statements in Table 4-43 execute concurrently. Even
if the statements were listed in a different order, the same circuit would be
synthesized, and the simulated circuit operation would be the same.
A VHDL architecture that uses components is often called a structural
description or structural design, because it defines the precise interconnection
structure of signals and entities that realize the entity. In this regard, a pure
structural description is equivalent to a schematic or a net list for the circuit.
In some applications it is necessary to create multiple copies of a particular
structure within an architecture. For example, we'll see in Section 5.10.2 that an
n-bit "ripple adder" can be created by cascading n "full adders." VHDL includes
a generate statement that allows you to create such repetitive structures using a
kind of "for loop," without having to write out all of the component instantia-
tions individually.
library IEEE;
use IEEE.std_logic_1164.all;
entity prime is
port ( N: in STD_LOGIC_VECTOR (3 downto 0);
F: out STD_LOGIC );
end prime;
architecture prime1_arch of prime is
signal N3_L, N2_L, N1_L: STD_LOGIC;
signal N3L_NO, N3L_N2L_N1, N2L_N1_NO, N2_N1L_NO: STD_LOGIC;
component INV port ( I: in STD_LOGIC; O: out STD_LOGIC); end component;
component AND2 port (I0,I1: in STD_LOGIC; O: out STD_LOGIC); end component;
component AND3 port (I0,I1,I2: in STD_LOGIC; O: out STD_LOGIC); end component;
component OR4 port (I0,I1,I2,I3: in STD_LOGIC; O: out STD_LOGIC); end component;
begin
U1: INV port map (N(3), N3_L);
U2: INV port map (N(2), N2_L);
U3: INV port map (N(1), N1_L);
U4: AND2 port map (N3_L, N(0), N3L_NO);
U5: AND3 port map (N3_L, N2_L, N(1), N3L_N2L_N1);
U6: AND3 port map (N2_L, N(1), N(0), N2L_N1_NO);
U7: AND3 port map (N(2), N1_L, N(0), N2_N1L_NO);
U8: OR4 port map (N3L_NO, N3L_N2L_N1, N2L_N1_NO, N2_N1L_NO, F);
end prime1_arch;
The syntax of a simple iterative generate loop is shown in Table 4-44. The identifier is implicitly declared as a variable with type compatible with the range. The concurrent statement is executed once for each possible value of the identifier within the range, and identifier may be used within the concurrent statement. For example, Table 4-45 shows how an 8-bit inverter can be created.
The value of a constant must be known at the time that a VHDL program is compiled. In many applications it is useful to design and compile an entity and its architecture while leaving some of its parameters, such as bus width, unspecified. VHDL's "generic" facility lets you do this.
One or more generic constants can be defined in an entity declaration with a generic declaration before the port declaration, using the syntax shown in Table 4-46. Each of the named constants can be used within the architecture definition for the entity, and the value of the constant is deferred until the entity is instantiated using a component statement within another architecture. Within that component statement, values are assigned to the generic constants using a generic map clause in the same style as the port map clause. Table 4-47 is an example that combines generic and generate statements to define a "bus inverter" with a user-specifiable width. Multiple copies of this inverter, each with a different width, are instantiated in the program in Table 4-48.
library IEEE;
use IEEE.std_logic_1164.all;
table 4-44
Syntax of a VHDL for-generate loop.
entity inv8 is
port ( X: in STD_LOGIC_VECTOR (1 to 8);
Y: out STD_LOGIC_VECTOR (1 to 8) );
end inv8;
architecture inv8_arch of inv8 is
component INV port ( I: in STD_LOGIC; O: out STD_LOGIC); end component;
begin
g1: for b in 1 to 8 generate
U1: INV port map (X(b), Y(b));
end generate;
end inv8_arch;
entity entity-name is
generic ( constant-names : constant-type;
constant-names : constant-type;
... constant-names : constant-type);
port ( signal-names : mode signal-type;
signal-names : mode signal-type;
... signal-names : mode signal-type);
end entity-name;
library IEEE;
use IEEE.std_logic_1164.all;
table 4-45
VHDL entity and architecture for an 8-bit inverter.
entity businv is
generic ( WIDTH: positive);
port ( X: in STD_LOGIC_VECTOR (WIDTH-1 downto 0);
Y: out STD_LOGIC_VECTOR (WIDTH-1 downto 0) );
end businv;
architecture businv_arch of businv is
component INV port ( I: in STD_LOGIC; O: out STD_LOGIC); end component;
begin
g1: for b in WIDTH-1 downto 0 generate
U1: INV port map (X(b), Y(b));
end generate;
end businv_arch;
Table 4-46
Syntax of a VHDL generic declaration within an entity declaration.
Table 4-47
VHDL entity and architecture for an arbitrary-width bus inverter.
library IEEE;
use IEEE.std_logic_1164.all;
entity businv_example is
port ( IN8: in STD_LOGIC_VECTOR (7 downto 0);
OUT8: out STD_LOGIC_VECTOR (7 downto 0);
IN16: in STD_LOGIC_VECTOR (15 downto 0);
OUT16: out STD_LOGIC_VECTOR (15 downto 0);
IN32: in STD_LOGIC_VECTOR (31 downto 0);
OUT32: out STD_LOGIC_VECTOR (31 downto 0) );
end businv_example;
architecture businv_ex_arch of businv_example is
component businv
generic (WIDTH: positive);
port ( X: in STD_LOGIC_VECTOR (WIDTH-1 downto 0);
Y: out STD_LOGIC_VECTOR (WIDTH-1 downto 0) );
end component;
begin
U1: businv generic map (WIDTH=>8) port map (IN8, OUT8);
U2: businv generic map (WIDTH=>16) port map (IN16, OUT16);
U3: businv generic map (WIDTH=>32) port map (IN32, OUT32);
end businv_ex_arch;
4.7.7 Dataflow Design Elements
If component statements were its only concurrent statements, then VHDL would be little more than a strongly typed, hierarchical net-list description language. Several additional concurrent statements allow VHDL to describe a circuit in terms of the flow of data and operations on it within the circuit. This style is called a dataflow description or dataflow design.
Two additional concurrent statements used in dataflow designs are shown in Table 4-49. The first of these is the most often used and is called a concurrent signal-assignment statement. You can read this as “signal-name gets expression.” Because of VHDL’s strong typing, the type of expression must be compatible with that of signal-name. In general, this means that either the types must be identical or expression’s type is a subtype of signal-name’s. In the case of arrays, both the element type and the length must match; however, the index range and direction need not match.
Table 4-49
Syntax of VHDL concurrent signal-assignment statements.
signal-name <= expression;
signal-name <= expression when boolean-expression else expression when boolean-expression else ...
......
expression when boolean-expression else expression;
architecture prime2_arch of prime is
signal N3L_NO, N3L_N2L_N1, N2L_N1_NO, N2_N1L_NO: STD_LOGIC;
begin
N3L_NO <= not N(3) and N(0);
N3L_N2L_N1 <= not N(3) and not N(2) and N(1);
N2L_N1_NO <= not N(2) and N(1) and N(0);
N2_N1L_NO <= N(2) and not N(1) and N(0);
F <= N3L_NO or N3L_N2L_N1 or N2L_N1_NO or N2_N1L_NO;
end prime2_arch;
Table 4-50
Dataflow VHDL architecture for the prime-number detector.
<table>
<thead>
<tr>
<th>Conditional signal-assignment statement</th>
</tr>
</thead>
<tbody>
<tr>
<td>when</td>
</tr>
<tr>
<td>else</td>
</tr>
<tr>
<td>relational operators</td>
</tr>
<tr>
<td>=, /=, >, > =, <, <=</td>
</tr>
</tbody>
</table>
Table 4-51
Prime-number-detector architecture using conditional assignments.
architecture prime3_arch of prime is
signal N3L_NO, N3L_N2L_N1, N2L_N1_NO, N2_N1L_NO: STD_LOGIC;
begin
N3L_NO <= '1' when N(3)'0' and N(0)'1' else '0';
N3L_N2L_N1 <= '1' when N(3)'0' and N(2)'0' and N(1)'1' else '0';
N2L_N1_NO <= '1' when N(2)'0' and N(1)'1' and N(0)'1' else '0';
N2_N1L_NO <= '1' when N(2)'1' and N(1)'0' and N(0)'1' else '0';
F <= N3L_NO or N3L_N2L_N1 or N2L_N1_NO or N2_N1L_NO;
end prime3_arch;
Table 4-52
Syntax of VHDL selected signal-assignment statement.
```
with expression select
signal-name <= signal-value when choices,
signal-value when choices,
...
signal-value when choices;
```
may be a single value of *expression* or a list of values separated by vertical bars (|). The *choices* for the entire statement must be mutually exclusive and all inclusive. The keyword *others* can be used in the last when clause to denote all values of *expression* that have not yet been covered.
Table 4-53 is an architecture for the prime-number detector that uses a selected signal-assignment statement. All of the *choices* for which F is '1' could have been written in a single when clause, but multiple clauses are shown just for instructional purposes. In this example, the selected signal-assignment statement reads somewhat like a listing of the on-set of the function F.
We can modify the previous architecture slightly to take advantage of the numeric interpretation of N in the function definition. Using the `CONV_INTEGER` function that we defined previously, Table 4-54 writes the *choices* in terms of integers, which we can readily see are prime as required. We can think of this version of the architecture as a “behavioral” description, because it describes the desired function in such a way that its behavior is quite evident.
Table 4-53
Prime-number detector architecture using selected signal assignment.
```
architecture prime4_arch of prime is
begin
with N select
F <= '1' when "0001",
'1' when "0010",
'1' when "0011" | "0101" | "0111",
'1' when "1011" | "1101",
'0' when others;
end prime4_arch;
```
**COVERING ALL THE CASES**
Conditional and selected signal assignments require all possible conditions to be covered. In a conditional signal assignment, the final “*else expression*” covers missing conditions. In a selected signal assignment, “*others*” can be used in the final when clause to pick up the remaining conditions.
In Table 4-53, you might think that instead of writing “*others*” in the final when clause, we could have written the nine remaining 4-bit combinations, "0000", "0100", and so on. But that’s not true! Remember that STD_LOGIC is a nine-valued system, so a 4-bit STD_LOGIC_VECTOR actually has $9^4$ possible values. So “*others*” in this example is really covering 6,554 cases!
architecture prime5_arch of prime is
begin
with CONV_INTEGER(N) select
F <= '1' when 1 | 2 | 3 | 5 | 7 | 11 | 13,
'0' when others;
end prime5_arch;
4.7.8 Behavioral Design Elements
As we saw in the last example, it is sometimes possible to directly describe a desired logic-circuit behavior using a concurrent statement. This is a good thing, as the ability to create a behavioral design or behavioral description is one of the key benefits of hardware-description languages in general and VHDL in particular. However, for most behavioral descriptions, we need to employ some additional language elements described in this subsection.
VHDL's key behavioral element is the "process." A process is a collection of "sequential" statements (described shortly) that executes in parallel with other concurrent statements and other processes. Using a process, you can specify a complex interaction of signals and events in a way that executes in essentially zero simulated time during simulation and that gives rise to a synthesized combinational or sequential circuit that performs the modeled operation directly.
A VHDL process statement can be used anywhere that a concurrent statement can be used. A process statement is introduced by the keyword process and has the syntax shown in Table 4-55. Since a process statement is written within the scope of an enclosing architecture, it has visibility of the types, signals, constants, functions, and procedures that are declared or are otherwise visible in the enclosing architecture. However, you can also define types, variables, constants, functions, and procedures that are local to the process.
Note that a process may not declare signals, only "variables." A VHDL variable keeps track of the state within a process and is not visible outside of the process. Depending on its use, it may or may not give rise to a corresponding signal in a physical realization of the modeled circuit. The syntax for defining a
<table>
<thead>
<tr>
<th>process (signal-name, signal-name, ..., signal-name)</th>
</tr>
</thead>
<tbody>
<tr>
<td>type declarations</td>
</tr>
<tr>
<td>variable declarations</td>
</tr>
<tr>
<td>constant declarations</td>
</tr>
<tr>
<td>function definitions</td>
</tr>
<tr>
<td>procedure definitions</td>
</tr>
<tr>
<td>begin</td>
</tr>
<tr>
<td>sequential-statement</td>
</tr>
<tr>
<td>...</td>
</tr>
<tr>
<td>sequential-statement</td>
</tr>
<tr>
<td>end process;</td>
</tr>
</tbody>
</table>
Table 4-54
A more behavioral description of the prime-number detector.
Table 4-55
Syntax of a VHDL process statement.
variable within a process is similar to the syntax for a signal declaration within an architecture, except that the keyword `variable` is used:
```vhdl
variable variable-names : variable-type;
```
A VHDL process is always either `running` or `suspended`. The list of signals in the process definition, called the `sensitivity list`, determines when the process runs. A process initially is suspended; when any signal in its sensitivity list changes value, the process resumes execution, starting with its first sequential statement and continuing until the end. If any signal in the sensitivity list changes value as a result of running the process, it runs again. This continues until the process runs without any of these signals changing value. In simulation, all of this happens in zero simulated time.
Upon resumption, a properly written process will suspend after one or a few runs. However, it is possible to write an incorrect process that never suspends. For example, consider a process with just one sequential statement, “`X <= not X`” and a sensitivity list of “`(X)`”. Since `X` changes on every pass, the process will run forever in zero simulated time—not very useful! In practice, simulators have safeguards that normally can detect such unwanted behavior, terminating the misbehaving process after a thousand or so passes.
The sensitivity list is optional; a process without a sensitivity list starts running at time zero in simulation. One application of such a process is to generate input waveforms in a test bench, as in Table 4-65 on page 296.
VHDL has several kinds of sequential statements. The first is a `sequential signal-assignment statement`; this has the same syntax as the concurrent version (`signal-name <= expression;`), but it occurs within the body of a process rather than an architecture. An analogous statement for variables is the `variable-assignment statement`, which has the syntax “`variable-name := expression;`”. Notice that a different assignment operator, `:=`, is used for variables.
For instruction purposes, the dataflow architecture of the prime-number detector in Table 4-50 is rewritten as a process in Table 4-56. Notice that we’re still working off the same original entity declaration of `prime` that appeared in
<table>
<thead>
<tr>
<th>Table 4-56</th>
</tr>
</thead>
<tbody>
<tr>
<td>Process-based dataflow VHDL architecture for the prime-number detector.</td>
</tr>
</tbody>
</table>
```vhdl
architecture prime6_arch of prime is
begin
process(N)
variable N3L_N0, N3L_N2L_N1, N2L_N1_N0, N2_N1L_N0: STD_LOGIC;
begin
N3L_N0 := not N(3) and N(0);
N3L_N2L_N1 := not N(3) and not N(2) and N(1);
N2L_N1_N0 := not N(2) and N(1) and N(0);
N2_N1L_N0 := N(2) and not N(1) and N(0);
F <= N3L_N0 or N3L_N2L_N1 or N2L_N1_N0 or N2_N1L_N0;
end process;
end prime6_arch;
```
WEIRD BEHAVIOR
Remember that the statements within a process are executed sequentially. Suppose that for some reason we wrote the last statement in Table 4-56 (the signal assignment to F) as the first. Then we would see rather weird behavior from this process.
The first time the process was run, the simulator would complain that the values of the variables were being read before any value was assigned to them. On subsequent resumptions, a value would be assigned to F based on the previous values of the variables, which are remembered while the process is suspended. New values would then be assigned to the variables and remembered until the next resumption. So the circuit's output value would always be one input-change behind.
Table 4-43. Within the new architecture (prime6_arch), we have just one concurrent statement, which is a process. The process sensitivity list contains just N, the primary inputs of the desired combinational logic function. The AND-gate outputs must be defined as variables rather than signals, since signal definitions are not allowed within a process. Otherwise, the body of the process is very similar to that of the original architecture. In fact, a typical synthesis tool would probably create the same circuit from either description.
Other sequential statements, beyond simple assignment, can give us more creative control in expressing circuit behavior. The if statement, with the syntax shown in Table 4-57, is probably the most familiar of these. In the first and simplest form of the statement, a boolean-expression is tested, and a sequential-statement is executed if the expression's value is true. In the second form,
architecture prime7_arch of prime is
begin
process(N)
variable NI: INTEGER;
begin
NI := CONV_INTEGER(N);
if NI=1 or NI=2 then F <= '1';
elsif NI=3 or NI=5 or NI=7 or NI=11 or NI=13 then F <= '1';
else F <= '0';
end if;
end process;
end prime7_arch;
we've added an "else" clause with another sequential-statement that's executed if the expression's value is false.
To create nested if-then-else statements, VHDL uses a special keyword elsif, which introduces the "middle" clauses. An elsif clause's sequential-statement is executed if its boolean-expression is true and all of the preceding boolean-expressions were false. The optional final else-clause's sequential-statement is executed if all of the preceding boolean-expressions were false.
Table 4-58 is a version of the prime-number-detector architecture that uses an if statement. A local variable NI is used to hold a converted, integer version of the input N, so that the comparisons in the if statement can be written using integer values.
The boolean expressions in Table 4-58 are nonoverlapping; that is, only one of them is true at a time. For this application we really didn't need the full power of nested if statements. In fact, a synthesis engine might create a circuit that evaluates the boolean expressions in series, with slower operation than might otherwise be possible. When we need to select among multiple alternatives based on the value of just one signal or expression, a case statement is usually more readable and may yield a better synthesized circuit.
Table 4-59 shows the syntax of a case statement. This statement evaluates the given expression, finds a matching value in one of the choices, and executes the corresponding sequential-statements. Note that one or more sequential statements can be written for each set of choices. The choices may take the form of a single value or of multiple values separated by vertical bars (|). The choices must be mutually exclusive and include all possible values of expression's type; the keyword others can be used as the last choices to denote all values that have not yet been covered.
<table>
<thead>
<tr>
<th>Table 4-59</th>
<th>Syntax of a VHDL case statement.</th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td>case expression is</td>
</tr>
<tr>
<td></td>
<td>when choices => sequential-statements</td>
</tr>
<tr>
<td></td>
<td>when choices => sequential-statements</td>
</tr>
<tr>
<td></td>
<td>end case;</td>
</tr>
</tbody>
</table>
architecture prime8_arch of prime is
begin
process(N)
begin
case CONV_INTEGER(N) is
when 1 => F <= '1';
when 2 => F <= '1';
when 3 | 5 | 7 | 11 | 13 => F <= '1';
when others => F <= '0';
end case;
end process;
end prime8_arch;
Table 4-60 is yet another architecture for the prime-number detector, this time coded with a case statement. Like the concurrent version, the select statement in Table 4-54 on page 289, the case statement makes it very easy to see the desired functional behavior.
Another important class of sequential statements are the loop statements. The simplest of these has the syntax shown in Table 4-61 and creates an infinite loop. Although infinite loops are undesirable in conventional software programming languages, we’ll show in Section 7.12 how such a loop can be very useful in hardware modeling.
loop
sequential-statement
...
sequential-statement
end loop;
A more familiar loop, one that we’ve seen before, is the for loop, with the syntax shown in Table 4-62. Note that the loop variable, identifier, is declared implicitly by its appearance in the for loop and has the same type as range. This variable may be used within the loop’s sequential statements, and it steps through all of the values in range, from left to right, one per iteration.
Two more useful sequential statements that can be executed within a loop are “exit” and “next”. When executed, exit transfers control to the statement immediately following the loop end. On the other hand, next causes any remaining statements in the loop to be bypassed and begins the next iteration of the loop.
for identifier in range loop
sequential-statement
...
sequential-statement
end loop;
Table 4-62 Syntax of a VHDL for loop.
library IEEE;
use IEEE.std_logic_1164.all;
entity prime9 is
port ( N: in STD_LOGIC_VECTOR (15 downto 0);
F: out STD_LOGIC);
end prime9;
architecture prime9_arch of prime9 is
begin
process(N)
variable NI: INTEGER;
variable prime: boolean;
begin
NI := CONV_INTEGER(N);
prime := true;
if NI=1 or NI=2 then null; -- take care of boundary cases
else for i in 2 to 253 loop
if NI mod i = 0 then
prime := false; exit;
end if;
end loop;
end if;
if prime then F <= '1'; else F <= '0'; end if;
end process;
end prime9_arch;
Our good old prime-number detector is coded one more time in Table 4-63, this time using a for loop. The striking thing about this example is that it is truly a behavioral description—we have actually used VHDL to compute whether the input N is a prime number. We’ve also increased the size of N to 16 bits, just to emphasize the fact that we were able to create a compact model for the circuit without having to explicitly list hundreds of primes.
BAD DESIGN
Table 4-63 has a good example of a for loop, but is a bad example of how to design a circuit. Although VHDL is a powerful programming language, design descriptions that use its full power may be inefficient or unsynthesizable.
The culprit in Table 4-63 is the mod operator. This operation requires an integer division, and most VHDL tools are unable to synthesize division circuits except for special cases, such as division by a power of two (realized as a shift).
Even if the tools could synthesize a divider, we wouldn’t want to specify a prime number detector in this way. The description in Table 4-63 implies a combinational circuit, and the tools would have to create 252 combinational dividers, one for each value of i, to “unroll” the for loop and realize the circuit!
while boolean-expression loop
sequential-statement
... sequential-statement
end loop;
Table 4-64
Syntax of a VHDL while loop.
The last kind of loop statement is the while loop, with the syntax shown in Table 4-64. In this form, boolean-expression is tested before each iteration of the loop, and the loop is executed only if the value of the expression is true.
We can use processes to write behavioral descriptions of both combinational and sequential circuits. Many more examples of combinational-circuit descriptions appear in the VHDL subsections of Chapter 5. A few additional language features are needed to describe sequential circuits; these are described in Section 7.12, and sequential examples appear in the VHDL subsections of Chapter 8.
4.7.9 The Time Dimension and Simulation
None of the examples that we’ve dealt with so far models the time dimension of circuit operation—everything happens in zero simulated time. However, VHDL has excellent facilities for modeling the time, and it is indeed another significant dimension of the language. In this book we won’t go into detail on this subject, but we’ll introduce just a few ideas here.
VHDL allows you to specify a time delay using the keyword after in any signal-assignment statement, including sequential, concurrent, conditional, and selected assignments. For example, in the inhibit-gate architecture of Table 4-26 on page 269 you could write
\[ Z <= '1' \] after 4 ns when \( X='1' \) and \( Y='0' \) else '0' after 3 ns;
This allows you to model an inhibit gate that has 4 ns of delay on a 0-to-1 output transition and only 3 ns on a 1-to-0 transition. In typical ASIC design environments, the VHDL models for all of the low-level components in the component library include such delay parameters. Using these estimates, a VHDL simulator can predict the approximate timing behavior of a larger circuit that uses these components.
Another way to invoke the time dimension is with wait, a sequential statement. This statement can be used to suspend a process for a specified time period. Table 4-65 is an example program that uses wait to create simulated input waveforms to test the operation of the inhibit gate for four different input combinations at 10-ns time steps.
Once you have a VHDL program whose syntax and semantics are correct, you can use a VHDL simulator to observe its operation. Although we won’t go into great detail, it’s useful to have a basic understanding of how such a simulator works.
|
{"Source-Url": "http://eelinux.ee.usm.maine.edu/courses/ele373/Section4.7B.pdf", "len_cl100k_base": 8376, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 18880, "total-output-tokens": 9126, "length": "2e13", "weborganizer": {"__label__adult": 0.0005016326904296875, "__label__art_design": 0.0007777214050292969, "__label__crime_law": 0.00033164024353027344, "__label__education_jobs": 0.0005369186401367188, "__label__entertainment": 0.00010442733764648438, "__label__fashion_beauty": 0.0002081394195556641, "__label__finance_business": 0.0002073049545288086, "__label__food_dining": 0.00037598609924316406, "__label__games": 0.0007925033569335938, "__label__hardware": 0.01300048828125, "__label__health": 0.0005059242248535156, "__label__history": 0.0003476142883300781, "__label__home_hobbies": 0.00017023086547851562, "__label__industrial": 0.0013723373413085938, "__label__literature": 0.0001838207244873047, "__label__politics": 0.00030350685119628906, "__label__religion": 0.0008306503295898438, "__label__science_tech": 0.097412109375, "__label__social_life": 6.55055046081543e-05, "__label__software": 0.00904083251953125, "__label__software_dev": 0.87158203125, "__label__sports_fitness": 0.00037384033203125, "__label__transportation": 0.0008692741394042969, "__label__travel": 0.00024378299713134768}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 35236, 0.04043]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 35236, 0.69959]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 35236, 0.89054]], "google_gemma-3-12b-it_contains_pii": [[0, 2762, false], [2762, 5498, null], [5498, 7232, null], [7232, 9906, null], [9906, 12328, null], [12328, 13684, null], [13684, 15741, null], [15741, 16913, null], [16913, 19304, null], [19304, 22085, null], [22085, 24874, null], [24874, 26546, null], [26546, 29008, null], [29008, 30825, null], [30825, 32738, null], [32738, 35236, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2762, true], [2762, 5498, null], [5498, 7232, null], [7232, 9906, null], [9906, 12328, null], [12328, 13684, null], [13684, 15741, null], [15741, 16913, null], [16913, 19304, null], [19304, 22085, null], [22085, 24874, null], [24874, 26546, null], [26546, 29008, null], [29008, 30825, null], [30825, 32738, null], [32738, 35236, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 35236, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 35236, null]], "pdf_page_numbers": [[0, 2762, 1], [2762, 5498, 2], [5498, 7232, 3], [7232, 9906, 4], [9906, 12328, 5], [12328, 13684, 6], [13684, 15741, 7], [15741, 16913, 8], [16913, 19304, 9], [19304, 22085, 10], [22085, 24874, 11], [24874, 26546, 12], [26546, 29008, 13], [29008, 30825, 14], [30825, 32738, 15], [32738, 35236, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 35236, 0.072]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
32248ab3c2d296ada3c45714db73930282f0f1cc
|
Transformations in Information Supply
B. van Gils, H. A. Proper, P. van Bommel, Th. P. van der Weide
University of Nijmegen* Sub-faculty of Informatics, IRIS Group,
Toernooiveld 1, 6525 ED Nijmegen, The Netherlands
basvg@acm.org, erikp@acm.org, pvb@cs.kun.nl, tvdw@cs.kun.nl
Published as:
Abstract. In this article, we present a model for transformation of resources in information supply. These transformations allow us to reason more flexibly about information supply, and in particular its heterogeneous nature. They allow us to change the form (e.g. report, abstract, summary) and format (e.g. PDF, DOC, HTML) of data resources found on the Web. In a retrieval context these transformations may be used to ensure that data resources are presented to the user in a form and format that is apt at that time.
1 Introduction
The Web today can be seen as an information market, on which information supply meets information demand: information is offered via the Web in the form of resources, which can be accessed (sometimes at a cost) by anyone interested in these resources. Information supply can be said to be heterogeneous because:
- there are many different ways to represent information. For example using a webpage, a document, an image or some interactive form.
- there are many different formats that may be used to represent information on the Web. For example, using formats such as PDF, HTML, GIF.
The following example illustrates this heterogeneity. Suppose you are browsing the Web from a PDA over a mobile-phone connection. You are on your way to an important meeting with stockholders of your company and need some last minute information on the price of your stock and that of your most important competitors. Using your favorite search engine you find a large spreadsheet with not only the latest stock price, but also their respective history, several graphs and predictions for the near future. In itself, this is a very useful resource. However, several problems occur at this point. First of all, the document is rather large which is inconvenient because you are on a slow (and possibly buggy) connection. Secondly, it may be that your PDA does not have the proper software to view this spreadsheet. Last but not least, you may not have the time
* The investigations were partly supported by the Dutch Organization for Scientific Research (NWO).
to study a complex spreadsheet, hence the form of the resource is off too. We hypothesize that transformations may cure this type of problems, for example by integrating a "transformation broker" in the retrieval engine in such a way that resources are transformed in a desirable format before sending them back to the user. The transformations in this article are considered in the context of web resources. As such they are not particularly tailored to database transformations (see e.g. our earlier work on transformations in [1, 2]).
The above mentioned forms of heterogeneity may pose problems in a retrieval setting if there is a mismatch between the user’s wishes on the one hand and the form and/or format of resources on the other hand. In order to investigate the problem area more closely we have developed a conceptual model for information supply [3, 4]. This model may contribute to more insights in this complex area. Furthermore it is the basis for a prototype implementation of a retrieval engine which we will discuss briefly\(^1\). The main contribution of this article is twofold. We firstly extend our model with a **typing mechanism**, which is a prerequisite for the second contribution: a formal model for transformations on in the information market. With transformations we will be able to deal with the form/format issues described above.
The remainder of this article is organized as follows: we start by introducing our model for information supply in Section 2. In Section 3 we formalize the (relevant) parts of this model. A more elaborate overview is presented in [3]. Section 4 formally introduces the typing mechanism that we use in our model. This typing mechanism is also the basis for Section 5 in which we discuss transformations in detail. In Section 6 we present our conclusions.
### 2 The model
In this section we present our model in two steps. We start out by informally introducing our model (Section 2.1) after which we constrain it by presenting its formal properties in Section 3.
#### 2.1 Overview
Our model of information supply is based on the distinction between data and information. The entities found on the Web, which can be identified by means of a **URI** [6], are **data resources**. These data resources are "information", if and only if they are relevant with regard to a given information need as it is harbored by some user. Data resources may, at least partially, convey the same information for some information need. Hence, we define **information resources** to be the abstract entities that make up information supply. Each information resource has at least one data resource associated to it. Consider for example the situation in which we have two data resources: the painting Mona Lisa, and a very detailed description of this painting. Both adhere to the same information resource in the sense that a person seeking for information on 'the Mona Lisa' will consider both to be relevant.
In a way, data resources **implement** information resources; a notion similar to that reported in [7] where 'facts' in the document subspace are considered to be 'proof' for hypotheses in the knowledge subspace. Note that each data resource may implement the information resource in a different way. One data resource may be a "graphical representation" of an information resource whereas another data resource may be a "textual representation" of the same information resource. We define a **representation** to be the combination of a data resource and an information
\(^1\) For a detailed discussion on this architecture the reader is referred to [5, 3]
resource, and a *representation type* to indicate exactly how this data resource implements the information resource it is associated to. Examples of representation types are: full-content, abstract, keyword-list, extract, audio-only etcetera.
As an example, consider the information resource called Mona Lisa which has two data resources associated to it. One of these resources is a photograph of this famous painting whereas another may be a very detailed description of the Mona Lisa. For the former data resource the representation type would be "graphical full-content" whereas the other would have representation type "description".
Many different types of data resources can be distinguished on the Web today, such as documents in different formats (HTML, PDF, etc.), databases and interactive Web-services. This is reflected in our model by the fact that each data resource has a *data resource type*. Furthermore, data resources may have several attributes such as a price or a measurement for its quality. Such attributes can be defined in terms of an *attribute type* and the actual value that a data resource has for this given attribute type.
Last but not least, data resources can be interrelated. The most prominent example of this interrelatedness on the Web is the notion of *hyperlinks* [8,9], but other types of relations between data resources exist as well. Examples are: an image may be part of a webpage and a scientific article may refer to other articles.
The following summarizes our model:
- Information Resources have at least one Data Resource associated to them;
- A Representation denotes the unique combination of an Information Resource and a Data Resource;
- Representations have at least one Representation Type;
- Data Resources have at least one Data Resource Type;
- Data Resources are related via Relations with a source and a destination;
- Relations have at least one Relation Type;
- Data Resources may have attributed values which are typed;
- An Attribute denotes the combination of a Data Resource and a Data Value;
- Attributes have at least one Attribute Type.
### 3 Formalization of resource space
As discussed in the previous sections, *resource space* consists of two types of resources: *information resources* and *data resources*. Information resources form an abstract landscape presenting the "semantics"; the "things we know something about". Data resources, on the other hand, are information that is "physically" stored in one way or the other. The representations relation, as discussed above, forms a bridge between these two worlds. Furthermore, in the data resource world we distinguish two types of relations: *attributions*, which couple a data value to a data resource, and *relations* between data resources. Formally, the basic concepts of our model are: information resources, representations, data resources, attributions and relations. They are represented by the following sets:
\[
\begin{align*}
\text{information resources: } & \mathcal{IR} \\
\text{data resources: } & \mathcal{DR} \\
\text{data values: } & \mathcal{DV} \\
\text{representations: } & \mathcal{RP} \\
\text{attributions: } & \mathcal{AT} \\
\text{relations: } & \mathcal{RC}
\end{align*}
\]
Because we consider these to be elementary (for example, it does not make sense if something is a relation and at the same time also a data resource), these sets must be disjoint:
**Axiom 1 (Disjoint Base Sets)** \(\mathcal{TR}, \mathcal{RP}, \mathcal{DR}, \mathcal{DV}, \mathcal{AT}, \mathcal{RL}\) are disjoint sets
Collectively, the data values and data resources are referred to as data elements:
\(\mathcal{DL} \triangleq \mathcal{DR} \cup \mathcal{DV}\)
Attributions connect data values to their respective data resources, and relations are used to interconnect data resources. Hence, attributions and relations form all possible connections between the data elements. Let \(\mathcal{CN}\) be the set of all these connections:
\(\mathcal{CN} \triangleq \mathcal{RL} \cup \mathcal{AT}\)
The sources and destinations of connections between data elements are yielded by the functions \(\text{Src}, \text{Dst} : \mathcal{CN} \rightarrow \mathcal{DL}\) respectively. Since these are total functions it follows that if a \(c \in \mathcal{CN}\) exists then its source and destination can not be void. Even more, we state that the source and destination can not be the same element:
**Axiom 2 (Source and Destination of connections)**
\[c \in \mathcal{CN} \implies \exists_{e_1, e_2 \in \mathcal{DL}} [\text{Src}(c) = e_1 \land \text{Dst}(c) = e_2 \land e_1 \neq e_2]\]
The destination of an attribution should be a data value:
**Axiom 3 (Attribute Values)**
\[\forall_{a \in \mathcal{AT}} [\text{Src}(a) \in \mathcal{DR} \land \text{Dst}(a) \in \mathcal{DV}]\]
Similarly, the destination of a relation should be a data resource:
**Axiom 4 (Relations)**
\[\forall_{r \in \mathcal{RL}} [\text{Src}(r) \in \mathcal{DR} \land \text{Dst}(r) \in \mathcal{DR}]\]
As an abbreviation we introduce:
\[s \bowtie d \triangleq \text{Src}(c) = s \land \text{Dst}(c) = d\]
\[s \bowtie d \triangleq \exists_{c} [s \bowtie d]\]
For example, a.zip \(\bowtie\) b.doc denotes that a.zip and b.doc are related via some relation (for example, the document may be part of the ZIP archive). Another example is x.html \(\bowtie\) UTF-8, which denotes that x.html uses the UTF-8 encoding.
Recall that a representation is the combination of an information resource and a data resource. They form the bridge between the abstract world of information resources and the concrete world of data resources. Hence we define \(\text{IRes} : \mathcal{RP} \rightarrow \mathcal{TR}\) to be a function yielding the information resource that is associated to a representation and \(\text{DRes} : \mathcal{RP} \rightarrow \mathcal{DR}\) to be a function providing the data resource associated to a representation.
In sum, we define resource space to be defined by the following signature:
\[\Sigma_r \triangleq \langle \mathcal{TR}, \mathcal{RP}, \mathcal{DR}, \mathcal{DV}, \mathcal{AT}, \mathcal{RL}, \text{IRes}, \text{DRes}, \text{Src}, \text{Dst} \rangle\]
4 Typing mechanism for descriptive elements
Before we are able to discuss transformations on data resources, we first need to introduce a typing mechanism on resource space. This typing mechanism allows us to limit the applicability of transformations to specific types of resources. In this section we therefore aim to extend resource space $\Sigma_r$ with a typing mechanism.
All elements in resource space can be typed. Let $RE$ therefore be the set of all elements in resource space:
$$ RE \triangleq DR \cup RP \cup DR \cup RL \cup AT \cup DV $$
The resource space elements form basis for a uniform typing mechanism. Data resources are allowed to have a type that is either "basic" or "complex". This is explained in more detail in Section 4.2.
Let $TP$ to be the set of all types and HasType $\subseteq RE \times TP$ be the relation for typing descriptive elements in our model. Our typing mechanism is inspired by abstract data types as introduced in e.g. [10]. This implies that we can perform operations on the instances of these types. Note that such a strategy can deal with both static as well as dynamic resources. For example, the approach as described in [11] actually uses many-sorted algebra’s to formalize the behavior of objects as used in object-oriented approaches. In the case of data resources, examples of these operations/methods are:
- give me the first byte,
- give me the n’th character,
- (in the case of an XML document) give me the first node in the DOM-tree.
4.1 Types and population
Given some element from resource space, we can use HasType to determine the set of types of this element. For example, the types of a given file may be XML, SGML and file or, the type of a relation may be “part of” or “refers to”. Conversely, we can also determine the set of elements of a given type. Formally, we use the functions $\tau$ and $\pi$ respectively to yield these sets:
$$ \tau(e) \triangleq \{ t \mid e \text{ HasType } t \} \quad \pi(t) \triangleq \{ e \mid e \text{ HasType } t \} $$
These functions may be generalized to sets of elements and types respectively:
$$ \tau(E) \triangleq \bigcup_{e \in E} \tau(e) \quad \pi(T) \triangleq \bigcup_{t \in T} \pi(t) $$
If $X$ is one of the base sets, such as $RL, DR$, then we will abbreviate $\tau(X)$ as $X_r$.
Using the definitions of $\tau$ it follows that an element may have more than one type. An example from the domain of data resources illustrates this. Suppose that $E = \{ 1\.htm, 2\.xml \}$ such that 1\.htm HasType HTML, 1\.htm HasType XML and 2\.xml HasType XML. In this case $\tau(E) = \{ HTML, XML \}$. We now have:
$$ \pi(HTML) = \{ 1\.htm \} \quad \tau(\pi(HTML)) = \{ HTML \} $$
$$ \pi/XML) = \{ 1\.htm, 2\.xml \} \quad \tau(\pi(XM)) = \{ HTML, XML \} $$
This example also shows that $\tau(\pi(HTML)) \subset \tau(\pi(XM))$. We will get back to this when we discuss subtyping in Section 4.3.
We assume that all elements have a type:
Axiom 5 (Total typing) \( \tau(e) \neq \emptyset \)
Conversely, in our model we presume types to exist only when they have a population:
Axiom 6 (Existential typing) \( \pi(t) \neq \emptyset \)
In the approach we take, typing of resource space is derived from the available resources. In other words, a new type of resources can only be introduced to the model if and only if instances (data elements) of this (new) type exist. This is particularly convenient since our model has to “fit” on an existing situation: the Web. In the case of database design, for example, the opposite holds: first the schema is defined, then it is populated with instances.
The partitioning of elements from resource space over \( TR, RP, DR, DV, AT, RL \) should be obeyed by their types as well:
Axiom 7 \( TR, RP, DR, DV, AT, RL \) form a partition of \( TP \)
4.2 Complex data resources
Data resources may depend on the existence of other elements from resource space. For example, some data resource may be constructed in terms of other data resources, and/or it may have some data value associated to it as an attribute. A data resource that is dependent on the existence of other elements is called a complex data resource.
In the case of a data resource which is considered to be (partially) constructed by means of other data resources, we are essentially dealing with a subset of the relations in \( RL \) which we regard as being compositions. Let therefore \( CM \subseteq RL \) be the set of relations that are considered to be compositions of complex data resources.
The compositions, in conjunction with the attributions, are the only ways of constructing complex data resources. The compositions and attributions used to construct the complex data resources are referred to as accessors; they offer access to the underlying composing elements. We define the set of accessors formally as:
\[ AC \triangleq CM \cup AT \]
The types of complex data resources, the underlying data resources/values, and the composition/attribution relations between them, have a special relationship: at the instance level, accessors can be thought of as “handles” which provide access to the data elements that were used to create the instance of a complex type. At the typing level, these “handles” are reflected by the accessor types. For example, a ZIP-file may have an accessor (with type “payload”), which offers access to the files that were used to create this specific Zip archive.
The construction of instances of complex types is restricted in the sense that cyclic behavior is forbidden: it is considered illegal if an instance \( a \) is used to construct \( b \) while at the same time \( b \) is used to construct \( a \):
Axiom 8 (Acyclic construction) The relation \( R \) defined as \( e_1 R e_2 \triangleq \exists a \in AC \left[ e_1 \xrightarrow{a} e_2 \right] \) is acyclic.
Not all types of complex data resources, such as "ZIP-file" and "multi-part E-mail", will have a "payload". For example, in the case of a complex type such as "postal address" it does not make sense to use an accessor of type "payload" on its instances. This kind of restriction must be reflected at the typing level, and pertains to the fact that only instances of a specific type may be involved in an accessor. To formally represent this, we introduce the relation:
\[ \_ \rightarrow \subseteq TP \times \mathcal{A} \times TP \]
If \( s \rightarrow t \), then the intuition is that complex type \( s \) has, via accessor type \( u \), at its base the type \( t \).
As an example, let \( t_1 = ZIP \), \( \alpha = \text{‘payload’} \) and \( t_2 = \text{file} \), then \( t_1 \rightarrow t_2 \) represents the fact that ZIP-files have a payload consisting of files.
Using the definition of \( \rightarrow \) we define the set of complex types to be:
\[ TP_{c} \triangleq \left\{ t_1 \in TP \mid \exists_{a \in \mathcal{A}, t_2 \in TP} \left[ t_1 \rightarrow t_2 \right] \right\} \]
At the instance level, accessors should behave as stipulated at the type level:
**Axiom 9 (Correct types)**
\[ e_1 \overset{\alpha}{\rightarrow} e_2 \implies \exists_{t_1 \in \tau(e_1), t_2 \in \tau(\alpha), t_2 \in \tau(e_2)} \left[ t_1 \overset{\alpha}{\rightarrow} t_2 \right] \]
The set of accessors that is associated to a complex type is defined by:
\[ \text{Acc}(t_1) \triangleq \left\{ t \in \mathcal{A}_r \mid \exists_{t_2} \left[ t_1 \overset{\alpha}{\rightarrow} t_2 \right] \right\} \]
This definition can be generalized to the instance level:
\[ \text{Acc}(e) \triangleq \bigcup_{t \in \tau(e)} \text{Acc}(t) \]
Note that it may be the case that some of the accessor types in an instance of a complex type are unused. For example, not every ZIP file has a comment or a password associated to it.
If two complex types have the same set of accessor types, such that the types at the base of these accessor types are the same, then the two complex types are really the same:
**Axiom 10 (Equality of Complex Types)** If \( \text{Acc}(s_1) = \text{Acc}(s_2) \), then:
\[ \forall_{a \in \text{Acc}(s_1), t \in TP} \left[ s_1 \overset{a}{\rightarrow} t \iff s_2 \overset{a}{\rightarrow} t \right] \implies s_1 = s_2 \]
As an example of how the accessor mechanism works in practice, consider the following example: suppose \( x.zip \) is a ZIP-file, while it's payload consists of three files, \( a.doc, b.ps \) and \( c.pdf \). They can be accessed via their respective accessor \( a_1, a_2 \) and \( a_3 \) which all have accessor type "payload". Note that this accessor type is really a composition (CM). Furthermore, there is a comment and a password attached to the ZIP-file which are accessed via accessors \( a_4 \) and \( a_5 \).
which have accessor types "comment" and "password" respectively. These accessor types originate from attributions. More formally:
\[ \pi(DR) = \{x.zip, a.doc, b.ps, c.pdf\} \]
\[ \pi(DR^-) = \{ZIP, DOC, PS, PDF, file\} \]
\[ \pi(DV) = \{"some comment", "secret"\} \]
\[ \pi(DT) = \{String\} \]
\[ \pi(CM) = \{a_1, a_2, a_3\} \]
\[ \pi(CM^-) = \{payload\} \]
\[ \pi(AT) = \{a_4, a_5\} \]
\[ \pi(AT^-) = \{"comment", "password"\} \]
Note that for \( a \in \{a_1, a_2, a_3\} \) it holds that ZIP \( \xrightarrow{a} file \). Similarly, for \( a \in \{a_4, a_5\} \) it holds that ZIP \( \xrightarrow{a} String \).
Figure 1 provides a graphical depiction of the above sketched situation. The left-hand side of the figure is at the instance level, whereas the right-hand side is at the typing level.

### 4.3 Subtyping
We assume the existence of subtyping. Let \( \text{SubOf} \subseteq TP \times TP \) therefore define a subtyping relationship, where \( s \text{ SubOf } t \) indicates that type \( s \) is a subtype of, or equal to type \( t \). Based on this definition, we introduce the notion of proper subtypes:
\[ s \text{ SubOf } t \triangleq s \text{ SubOf } t \land \neg t \text{ SubOf } s \]
We presume \( \text{SubOf} \) to be transitive, reflexive and antisymmetric:
**Axiom 11 (Behavior of SubOf)**
\[ t \in TP \implies t \text{ SubOf } t \]
\[ t \text{ SubOf } s \land s \text{ SubOf } t \implies t = s \]
\[ s \text{ SubOf } t \text{ SubOf } u \implies s \text{ SubOf } u \]
\(^2\) The notion of subtyping is introduced in Section 4.3.
From this we can prove:
**Lemma 1** SubOf is irreflexive, asymmetric and transitive
At the instance level, if \( s \) SubOf \( t \) then the population of \( s \) must be a subset of, or equal to the population of \( t \):
**Axiom 12 (Population and SubOf)**
\[ s \text{ SubOf } t \implies \pi(s) \subseteq \pi(t) \]
From this we can prove that:
**Lemma 2** \( s \) SubOf \( t \implies \pi(s) \subset \pi(t) \)
For example, if XML SubOf SGML and \( x \in \pi(\text{XML}) \) then Lemma 2 states that also \( x \in \pi(\text{SGML}) \). Recall that, at the instance level, the type of a resource can be seen as the interface with which instances can be accessed. Hence, an instance with type XML can also be accessed via an “SGML-interface”.
If a complex type has a subtype then the accessor types of the supertype are inherited:
**Axiom 13 (Inheritance of accessor types)**
\[ s_1 \text{ SubOf } s_2 \implies \text{Acc}(s_1) \subseteq \text{Acc}(s_2) \]
This axiom forbids the situation that a type with 2 accessor types is a subtype of another type with 3 accessor types (the converse is allowed, and is akin to specialization in object-orientation).
Types that are at the base of a specific accessor type (in the context of a single complex type) should be subtypes:
**Axiom 14 (Subtyping of accessor bases)**
\[ s \leftarrow t_1 \land s \leftarrow t_2 \implies t_1 \text{ SubOf } t_2 \lor t_2 \text{ SubOf } t_1 \]
Even more, the set of types that are at the base of an accessor type comprises all relevant super types:
**Axiom 15 (Inclusion of super types)**
\[ s \leftarrow t_1 \land t_1 \text{ SubOf } t_2 = \exists t_1, t_2 \left( s \leftarrow t_1 \land s \leftarrow t_2 \implies t_1 \text{ SubOf } t_2 \right) \]
If a complex type has a subtype then the underlying base types must obey this subtyping as well:
**Axiom 16 (Base types obey subtyping)**
\[ s_1 \text{ SubOf } s_2 \land s_1 \leftarrow t_1 \land s_2 \leftarrow t_2 \implies t_1 \text{ SubOf } t_2 \]
From the above Axiom, in combination with Axiom 10, it follows that if two complex types are proper subtypes, then there is at least one accessor type whose base types show this proper subtyping:
**Lemma 3** \( s_1, s_2 \in TP_c \land s_1 \text{ SubOf } s_2 \implies \exists u, t_1, t_2 \left[ s_1 \leftarrow u \land s_2 \leftarrow u \implies t_1 \land t_2 \text{ SubOf } t_2 \right] \)
4.4 Typed resource space
In sum, we define a typed resource space to be defined by the following signature:
\[ \Sigma^r \triangleq (\Sigma, TP, CM, \text{HasType}) \]
5 Transformations
In this section we introduce transformations, a way to change the nature / structure of instances. These transformations can be very used in practice to solve several problems. For example:
- Suppose we have an image in EPS file that we want to view. Unfortunately we don’t have a viewer for this file-type. We do have a viewer for JPEG files, though. By means of a transformation we may be able to transform the EPS file to JPEG and thus access the information we need.
- Managers of large organizations often have to read many lengthy reports. Because of time constraints it is not always possible to read all these reports. Again, transformations may help. Transformations exists to generate abstracts of these documents.
In other words, transformations help us to have a more flexible view on the information landscape. In general, one can distinguish between an extensional database and intentional database [12,13]. The extensional database corresponds to the a set of basic facts known about the world, whereas the intentional database represents the facts that may be derived from the extensional database by applying inference rules. The transformations can be regarded as inference rules on the extensional database (information supply as we know it), resulting in a larger intentional database.
The remainder of this section is organized as follows. In Section 5.1 we define what transformations are and show their basic properties. Section 5.2 elaborates and presents complex transformations.
5.1 Basic Properties
Recall that IRes finds the unique information resource associated to a representation, and that DRes finds the unique data resource associated to a representation. Essentially, a representation is information represented on a medium, and the representation type expresses how / to what extent this is done.
As was stated before, with transformations we can transform data resources. This paper does not present a language for specifying what a specific transformation does / a language for composing transformations. We focus on general properties of transformations and, hence, view them as a “black box“ for the time being.
Let \( TR \) be the set of all transformations. The semantics of a transformation \( T \in TR \) is given by the function:
\[ \text{SEM} : TR \rightarrow (DR \rightarrow DR) \]
In other words, transformations transform a representation to another. As an abbreviation, let $T \triangleq \text{SEM}(T), T \in \mathcal{TR}$. Furthermore, let $i \models d$ denote that data resource $d$ is associated to information resource $i$ via some representation:
$$i \models d \triangleq \exists r \in \mathcal{R} \left[ \text{IRes}(r) = i \land \text{DRes}(r) = d \right]$$
If a data resource is transformed, then the resulting data resource is associated to the same information resource as the original information resource.
**Axiom 17 (IR neutral transformations)**
$$i \models d \land T(d) = d' \implies i \models d'$$
Any given transformation has a fixed input and output for which it is defined, similar to the notion of mathematical functions having a domain and a range: Input, Output : $\mathcal{TR} \rightarrow \tau(\mathcal{DR})$. Let $t \rightarrow u$ denote the fact that transformation $T \in \mathcal{TR}$ can be applied on instances of type $t$ and results in instances of type $u$:
$$t \rightarrow u \triangleq \text{Input}(T) = t \land \text{Output}(T) = u$$
Any given transformation is only defined for all instances that are of the correct input-format. Even more so, it can only produce instances of its output-format:
**Axiom 18 (I/O of Transformations)**
If $t \rightarrow u$ then $T : \pi(t) \rightarrow \pi(u)$
This allows us to define how a transformation $T$ can be applied to a set of data resources. Let $E \subseteq \mathcal{DR}$ be a set of data resources. Then:
$$\overline{T}(E) \triangleq \left\{ e \mid e \in E \land e \notin \text{Input}(T) \right\} \cup \left\{ \overline{T}(e) \mid e \in E \land e \in \text{Input}(T) \right\}$$
Another property of transformations is the fact that they are transitive:
**Axiom 19 (Transitivity of Transformations)**
$$e \overset{T_1}{\rightarrow} f \land f \overset{T_2}{\rightarrow} g \implies \exists T_3 \left[ e \overset{T_3}{\rightarrow} g \land T_3 \circ T_2 = T_1 \right]$$
This property can be used to transform data resources into an appropriate format even if there is no 1-step transformation is available. It is, for example, possible to generate an abstract of a large ASCII-file and transform that to PS by sequencing the two transformations.
### 5.2 Complex Transformations
In the previous section we presented a framework for transformations and showed how transformations can be composed by sequencing them using the $\circ$ operator. In this section we discuss a more complex way of composing transformations, relying heavily on the accessor types presented in previous sections. We define a transformation to be complex if the transformation operates on instances that were used to create an instance of a complex type (that is, instances at the base of an instance of a complex type). There are two types of complex transformations which, like all transformations, may be sequenced using the $\circ$ operator.
The first complex transformation is used to *remove* an accessor and the instance(s) at its base. For example, it may be desirable to remove a comment from a ZIP-file, or to remove an attachment from an E-mail. Such transformation:
– takes an instance with a complex type as input;
– removes a specified accessor and its base from an instance with a complex type;
– leaves other accessors (and their bases) untouched.
More formally, Let $e$ be an instance with a complex type and $a \in \text{Acc}(\tau(e))$:
$$\varrho_a(e) = e' \triangleq e' \bowtie a = \emptyset \land \forall_{b \neq a} [e \bowtie b = e' \bowtie b]$$
In the above definition we have used the following shorthand notation:
$$c \bowtie t \triangleq \left\{ d \mid c \bowtie d \land a \in \pi(t) \right\}$$
The intuition behind this shorthand is that $c \bowtie ad$ retrieves all data elements that are used in constructing complex data resources $c$ via accessors of type $t$.
This type of transformations can be performed on each instance with a complex type, since such an instance must have at least one accessor. If the last accessor of an instance is removed then $\varrho$ is said to destruct the instance.
**Axiom 20 (Existence of $\varrho$)**
$$\text{if } t \in TP_c, a \in \text{Acc}(T) \text{ then } \exists_{\varrho \in TR} [t \stackrel{T}{\Rightarrow} t \bowtie \overline{T} = \varrho_a]$$
The second class of complex transformations does a little more work; they are deep transformations in the sense that instances at the base of a complex type are transformed. For example, all DOC files in a ZIP archive may be transformed to PDF. These transformations:
– takes an instance with a complex type as input, and returns an instance with a (possibly different) complex type;
– Transform the instances at the base of an accessor;
– leave other accessors (and their bases) untouched.
More formally, Let $e$ be an instance of a complex type, $a \in \text{Acc}(\tau(e))$ and $T \in TR$:
$$\alpha_{a,T}(e) = e' \triangleq e' \bowtie a = T(e \bowtie a) \land \forall_{b \neq a} [e \bowtie b = e' \bowtie b]$$
These transformations are defined for all types $t_1$, $t_2$ as long as they have the same accessor types. Even more, transformation $T$ must at least be defined for the instances at the base of the specified accessor:
**Axiom 21 (Existence of $\alpha$)**
$$\text{if } \text{Acc}(t_1) = \text{Acc}(t_2) \land a \in \text{Acc}(t_1) \land \exists_{b_1, b_2} \left[ t_1 \stackrel{a}{\Rightarrow} b_1 \land t_2 \stackrel{a}{\Rightarrow} b_2 \land b_1 \stackrel{T}{\Rightarrow} b_2 \right] \text{ then } \exists_{T' \in TR} \left[ t_1 \stackrel{T'}{\Rightarrow} t_2 \bowtie \overline{T'} = \alpha_{a,T} \right]$$
To illustrate how such a deep transformation can be used to transform an instance from complex type $t_1$ to complex type $t_2$, consider the following situation. $t_1$ is the format for an E-mail for which the body is in UTF-8 encoding, and $t_2$ has its body in UTF-16 encoding. That is, $t_1$ has an accessor with type UTF-8 and some text formatted accordingly at its base and the same accessor has, in the context of type $t_2$, accessor type UTF-16. If $T$ is a transformation capable of transforming text in UTF-8 encoding to UTF-16 encoding then Axiom 21 dictates that a $T''$ must exist such that $t_1 \stackrel{T'}{\Rightarrow} T_2$.
5.3 Example
In this section we present an example that relies on Axioms 19, 20 and 21. Consider the following: Let backup.zip be a ZIP archive. Two files (report.doc and letter.doc) form the payload of this archive. Also, a comment ("backup") and a password ("secret") are associated to it. In other words:
\[
\tau(\text{backup.zip}) = \text{ZIP} \\
\text{Acc(backup.zip)} = \{\text{payload, comment, password}\} \\
\text{backup.zip \times payload} = \{\text{report.doc, letter.doc}\} \\
\text{backup.zip \times comment} = \text{"backup"} \\
\text{backup.zip \times password} = \text{"secret"}
\]
Now, let \( T_1 \) be a transformation with \( \text{Input}(T) = \text{DOC} \) and \( \text{Output}(T) = \text{PDF} \). Then, \( \alpha_{\text{payload}} \circ T_1 \) is a transformation that transforms the documents in the payload of any ZIP archive to PDF. Let \( \alpha_{\text{password}} \) be a transformation that removes the password of a ZIP archive.
If we want to transform backup.zip such that the documents in its payload are transformed to PDF and its password is removed then we can achieve this as follows:
\[
T = \alpha_{\text{payload}} \circ T_1 \circ \alpha_{\text{password}} \\
T(\text{backup.zip}) = \text{new.zip}
\]
The result of this transformation is a new archive new.zip such that:
\[
\tau(\text{new.zip}) = \text{ZIP} \\
\text{Acc(new.zip)} = \{\text{payload, comment}\} \\
\text{new.zip \times payload} = \{\text{report.pdf, letter.pdf}\} \\
\text{new.zip \times comment} = \text{"backup"}
\]
5.4 Open issues
In this section we have presented a theoretical framework for transformations and their basic properties. This framework allows us to reason more efficiently about the information that is supplied to us via the Web. In [5] we have presented a retrieval architecture called \textit{Vimes} that makes use of these transformations in a retrieval-setting. The main idea behind \textit{Vimes} is that data resources on the Web may be transformed in a format suitable for the user.
What is missing still, though, is a mechanism to examine the effects of transformations, and transformation paths in particular. Suppose a transformation from \( p \) to \( q \) is needed, and two sequences of transformations are possible to achieve this. Which sequence is "best"? Based on which properties / quality attributes can such a decision be made? Devising a mechanism is part of future research.
6 Conclusion
In this article we set out to do two things: present a formal model for information supply, the totality of information available to us via the Web, and present a framework of transformations to add flexibility to this model.
The basic model stems from earlier work [3, 4] with basic elements: data resource, information resource, representation, value, attribution and relation. In this article we extended it with an extensive typing mechanism with an explicit distinction between basic and complex types. An instance is said to be complex if other instances (data resources or attributed values) were used to construct it. An example is a ZIP-file with several documents, a password and a comment associated to it.
For our transformation framework we defined that transformations work on data resources. A distinction is made between the semantics of a transformation (pertaining to its signature), and its actual application on real instances. Transformations have a fixed input type and output type similar to mathematical functions having a domain and a range.
We distinguish two types of transformations: transformations on instances of simple types and deep transformations (which operate on instances used to construct the instance of a complex type). Furthermore, a property of all transformations is that they may be transitively nested.
Even though our model covers both "simple" and "complex" transformations, much work needs to be done still. First of all, the effects of transformations must be studied still. That is, by performing a transformation on a data resource its (perceived) quality may change. Even more so, if a transformation from one type to another may be achieved via two possible sequences of transformation, a choice must be made: which one is the best, and why? Last but not least, a language to constrain our model and transformations in this model must be developed still. Last but not least, we are currently working on an implementation of our transformation framework and refer the interested reader to [5, 3] for details.
References
|
{"Source-Url": "http://repository.ubn.ru.nl/bitstream/handle/2066/60336/60336.pdf?sequence=1", "len_cl100k_base": 9673, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 32851, "total-output-tokens": 11498, "length": "2e13", "weborganizer": {"__label__adult": 0.00037169456481933594, "__label__art_design": 0.0008306503295898438, "__label__crime_law": 0.00057220458984375, "__label__education_jobs": 0.00429534912109375, "__label__entertainment": 0.00018787384033203125, "__label__fashion_beauty": 0.00027108192443847656, "__label__finance_business": 0.0010709762573242188, "__label__food_dining": 0.0005178451538085938, "__label__games": 0.0006608963012695312, "__label__hardware": 0.0009002685546875, "__label__health": 0.0010585784912109375, "__label__history": 0.0005631446838378906, "__label__home_hobbies": 0.0001697540283203125, "__label__industrial": 0.0006413459777832031, "__label__literature": 0.0012598037719726562, "__label__politics": 0.0004074573516845703, "__label__religion": 0.0005679130554199219, "__label__science_tech": 0.367919921875, "__label__social_life": 0.00022614002227783203, "__label__software": 0.044219970703125, "__label__software_dev": 0.572265625, "__label__sports_fitness": 0.00023472309112548828, "__label__transportation": 0.0006198883056640625, "__label__travel": 0.00025844573974609375}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40723, 0.01795]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40723, 0.84366]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40723, 0.84921]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2813, false], [2813, 6436, null], [6436, 9676, null], [9676, 12617, null], [12617, 15563, null], [15563, 18447, null], [18447, 21290, null], [21290, 22877, null], [22877, 25254, null], [25254, 27780, null], [27780, 30943, null], [30943, 34061, null], [34061, 36726, null], [36726, 40723, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2813, true], [2813, 6436, null], [6436, 9676, null], [9676, 12617, null], [12617, 15563, null], [15563, 18447, null], [18447, 21290, null], [21290, 22877, null], [22877, 25254, null], [25254, 27780, null], [27780, 30943, null], [30943, 34061, null], [34061, 36726, null], [36726, 40723, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40723, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40723, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2813, 2], [2813, 6436, 3], [6436, 9676, 4], [9676, 12617, 5], [12617, 15563, 6], [15563, 18447, 7], [18447, 21290, 8], [21290, 22877, 9], [22877, 25254, 10], [25254, 27780, 11], [27780, 30943, 12], [30943, 34061, 13], [34061, 36726, 14], [36726, 40723, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40723, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
5ed9c145dce886287a5827937ae67b067e4f7a10
|
Membership agreement
The PHARO Consortium
By and between:
L’Institut national de recherche en informatique et en automatique
French Scientific and Technological Public Institute (EPST), whose registered office is at Domaine de Voluceau - Rocquencourt - B.P. 105 - 78153 Le Chesnay Cedex, France.
Represented by Bruno SPORTISSE, acting on his capacity of Chairman and Chief Executive Officer, who has delegated his authority for the purposes of this document to François CUNY, Deputy CEO for Innovation.
Hereinafter designated as Inria or the “Coordinator”
And:
Located at
Represented by . . .
Intercommunity VAT:
Hereinafter designated as the Member
Individually referred as the Party and jointly as the Parties.
WHEREAS:
The Inria “RMOD” team, a research team from Lille research center, has developed a software platform named PHARO available under the MIT license. It wants to create a community of users and contributors to this platform by letting organizations join a consortium created for this purpose.
The Member, user of and/or contributor to PHARO, wishes to take part in the PHARO Consortium to promote, sustain, and develop the software platform PHARO, to ensure its continuity.
The Member's participation in the Consortium and its cooperation with Inria pursuant to the term of this agreement will advance Inria's research objectives in accordance with the needs of major users of PHARO.
The terms of this membership agreement cannot be subject to negotiation in order to ensure equal treatment between the different Members of the consortium.
THE FOLLOWING HAS BEEN AGREED:
Article 1: Definitions
For purposes of enforcement and interpretation of this Agreement, the following terms have the following meanings:
PHARO Team: Inria “RMOD” team and all new and future Inria research team in charge of the development of PHARO.
PHARO: an open-source programming environment inspired by the “smalltalk” language. This is an attractive platform to build and deploy software applications and tools. The release of this platform already contains many tools and applications.
MIT License: The MIT License is a free software license originating at the Massachusetts Institute of Technology (MIT). It is a permissive free software license, meaning that it permits reuse within proprietary software provided all copies of the licensed software include a copy of the MIT License terms.
Release: new versions of PHARO containing improvements, new tools, etc. managed with the cooperation of the PHARO Team and published under the MIT License.
Agreement: the present membership agreement and its appendix.
Consortium: Community of users and contributors to the platform PHARO who have signed this membership agreement to participate in PHARO’s promotion and development according to the conditions below.
Support: On a member’s request, and within the limits specified in Article 7, Inria provides consulting on PHARO, giving advice and recommendations to the Member to help implement a technical solution to a problem encountered regarding the integration of tools...
and applications in PHARO. In addition PHARO bugs will be considered without any obligation to fix them.
**Specific Consulting or Development:** On a Platinum or Gold member’s written request to consortium-adm@pharo.org, and within the limits specified in Article 7, Inria provides specific consulting or development in connection with the Member business work with PHARO, giving advice and recommendations to the Member to help implement a technical solution to a problem encountered regarding its own software or to help for fixing a bug in its own software which can prevent proper use or generate dysfunction, failure when used with PHARO.
**Year:** Calendar year
**PHARO Consortium Website:** a web site hosting the consortium. This website is available at the following address: http://consortium.pharo.org
All training, offers and information will be posted on this website.
The Member will receive by email a login and password to connect to this website.
**Article 2: Purpose**
The purpose of this Agreement is to define and organize the terms and conditions of access by the Member to the PHARO Consortium.
By signing this Agreement, the Member undertakes to participate in the PHARO Consortium, and to abide by all its rules, both organisational and operational, as defined by this Agreement.
The purpose of the PHARO Consortium is described in the presentation sheet appended to this Agreement (appendix 1).
The Agreement reflects the entirety of the Parties’ consent on its purpose and cancels and replaces in their entirety any proposals or oral or written commitments (not including any confidentiality agreements signed between the Parties), previously exchanged between the Parties on the same subject. Any amendment to the Agreement will be written and signed by the Parties.
The Parties acknowledge that their mutual approach as described in this Agreement is not intended to form a company, legal person or other judicial entity whatsoever and that any intention to share in any profits and contribute to any losses are thus hereby formally excluded. The “affectio societatis” is strictly excluded.
**Article 3: Membership levels**
The PHARO consortium is composed of the following categories of members.
- Bronze members
- Silver members
- Gold members
- Platinum members
- Academic members
Only public and non-profit organizations or institutions aiming at conducting research works or teaching activities are eligible to the Academic membership level.
Bronze, Silver, Gold and Platinum membership levels are jointly referred to as Standard Membership levels. Members of the consortium at these membership levels are referred to as Standard Members. Each Member shares mutual benefits and has also specific benefits depending on its membership level as described in Article 6 and Article 7 below.
For governance purposes, Inria shall be considered as a member of the consortium at Platinum level.
**Article 4: Duration**
This Agreement shall enter into force from its date of signature by the Member. It is tacitly renewed each year unless terminated by the Member or by Inria as described in Article 13.
**Article 5: Financial Terms**
5.1 Annual Membership Fees
To be considered a member of PHARO consortium, the Member needs to pay Inria an annual fee for each Year. The fee depends on the membership level chosen. On January 1st 2018, the fee for each membership category is the following:
- Bronze members: 1 000 euros net of taxes (without VAT)
- Silver members: 2 000 euros net of taxes (without VAT)
- Gold members: 4 000 euros net of taxes (without VAT)
- Platinum members: from 8 000 euros net of taxes (without VAT)
- Academic members: no fee, but they must fulfil commitments as described in article 8.3.
Inria shall send to the Member an invoice corresponding to its annual fee according to provisions of this article. The first invoice (first Year) shall be sent by Inria to the Member after signature of this Agreement by both Parties.
5.2 Fee Revisions
The fees will be revised every year, on January 1st, to take into account changes in the cost of manpower. They will be revised using the index published by Syntec, a French organisation federating digital service companies. Syntec’s index is a valid reference index as recognized by French authorities since 1974-03-11. The revision formula is \( F_t = F_0 \times \left( \frac{S_t}{S_0} \right) \), where \( F_t \) is the revised fee, \( F_0 \) the initial fee as published in Appendix B, \( S_t \) the last published index at the date the fee is revised and \( S_0 \) the index for the month of January 2018.
5.3 Partial Fees for New Members
If the Member joins during the course of the Year, the membership fee for that particular Year is to be calculated using the following rules:
- 100% of the annual fee for a Member joining between January 1st and June 30th
- 50% of the annual fee for a Member joining between July 1st and October 31st
- 15% of the annual fee for a Member joining between November 1st and December 31st
In this last case, the annual fee for the following year will be requested at the same time as the membership fee for the Year during which he joined the consortium. Therefore he will pay his membership fee for the next year before its amount is revised. Nor The Member, nor Inria will request compensation for the difference in membership fees for that year once the fees are revised.
This fee will be calculated by Inria. The starting point will be the date of signature of this Agreement by the Member.
5.4 Choice of membership level
On the signature page of this Agreement, the Member will make its choice of membership level by checking the box corresponding to the selected membership category.
5.5 Change in Membership level
The Member can change his membership level at any time, by sending a notification to Inria as defined in Article 14 by sending an updated signature page of this agreement to Inria, complete with his signature. Inria will then recalculate fees dues for the new membership level. If they are higher that the fees already paid, Inria will send a new invoice. If they are lower, Inria will not refund the Member for the current Year.
5.6 Payment conditions
Payments shall be made within thirty (30) days from the date of receipt of Inria’s invoice.
Article 6: Common Benefits
By signature of the present Agreement and payment of the annual fees, a Member shall have:
- Direct access to PHARO core developers via an automatic subscription to a specific mailing list.
- The right to propose to the PHARO Technical Board (see Article 9.3) development priorities.
- The possibility to propose and participate in collaborative projects for the development of PHARO applications that are of interest to the Member.
- Access to PHARO documents and courses.
In addition to the benefits above, Standard Members shall have:
- Two days per Year of training provided by PHARO Team at special prices.
- For specific developments, the Member has access to a list of PHARO experts (other than staff of PHARO Team). Note that Inria will give only contact details. It shall not
be held responsible for any troubles resulting from the use by the Member of expert’s services.
- Its logo posted on most of the PHARO website pages.
All these benefits and offers will be accessible via the PHARO Consortium Website. The Member will subscribe to all these benefits on PHARO Consortium Website.
**Article 7: Specific Benefits**
7.1 Benefits by membership level
Depending on the membership category chosen, the Member has specific advantages reserved according to its status.
7.1.1 “Academic” member:
- Its logo posted on the PHARO Website Academic pages
7.1.2 “Bronze” member:
- one day per Year of Support;
- gets to nominate one (1) item for roadmap prioritization (see section 9.3 for an overview of the process).
7.1.3 “Silver” member:
- two days per Year of Support;
- ability to post job offers or other news related to PHARO on the PHARO Consortium Website;
- gets to nominate two (2) items for roadmap prioritization (see section 9.3 for an overview of the process).
7.1.4 “Gold” member:
- four days per Year of Support;
- ability to post job offers or other news related to PHARO on the PHARO Consortium Website, and have them relayed on the front page or by other means by the PHARO Technical Board;
- ability to request specific development or support contracts to Inria.
- Possibility to request that Inria takes up one trainee on PHARO topics that the Member wants to see developed in the consortium, provided internship fees are covered by the member in addition of the annual fee dues. Detailed condition are described in section 7.4;
- gets to nominate three (3) items for roadmap prioritization (see section 9.3 for an overview of the process).
7.1.5 “Platinum” member:
- ten days per Year of Support or of Specific Consulting or Development. These days can be divided by the Member, as it wants, to allow him to have both Support days and Specific Consulting or Development days. Additional days of the same type can be purchased by the Member as part of his annual fee, and declared as such on the signature page. For every 25% of the fee for a Platinum Member, it is entitled to get four additional days of Support or of Specific Consulting or Development.
- ability to request specific development or support contracts to Inria.
- ability to post job offers or other news related to PHARO on the PHARO Consortium Website, and have them relayed on the front page or by other means by the PHARO Technical Board;
- Possibility to request that Inria takes up to two trainees on PHARO topics that the Member wants to see developed in the consortium, provided internship fees are covered by the member in addition of the annual fee dues. Detailed condition are described in section 7.4;
- gets to nominate four (4) items for roadmap prioritization (see section 9.3 for an overview of the process).
7.2 Conditions for Support
Any unused Support day in a Year is lost without any possibility to transfer them on next Year.
If the Member joins during the course of the Year, the days of Support for that particular Year are to be calculated and defined by Inria on a pro rata basis according to the membership fees paid.
Outside of this Consortium, if Members want extra Support days, they have to make a written request to Inria and to the extent that is possible, a service provision contract will be established at Inria prices
7.3 Conditions for Support and/or Specific Consulting or Development (Platinum member only)
The Specific Consulting or Development performed by Inria for a « Gold or Platinum » member will be considered as “other results” according to article 12.4 of this Agreement. As such, the Member shall have ownership of them.
The Specific Consulting or Development performed by Inria for a « Gold or Platinum » member will be provided “as is”, without warranty of any kind. Inria notably excludes all warranties, expressed or implied, relating to commercial or industrial use of these task results, their safety, their sufficiency, compatibility or fitness for the Member needs, absence of errors or defects. The Member shall in all cases be entirely and solely liable for the use to which it puts such results and consequently waives all recourse against Inria, in any capacity whatsoever of for any reason whatsoever due to the use of them.
Inria is allowed to subcontract to third parties, in particular to those employing members of the PHARO Team to fulfil its obligations.
Any unused Support and/or Specific Consulting or Development days in a Year are lost without any possibility to transfer them on next Year.
If the Member joins during the course of the Year, the days of Support and/or Specific Consulting or Development for that particular Year are to be calculated and defined by Inria on a pro rata basis according to the membership fees paid.
Outside of this Consortium, if Members want extra Support or Specific Consulting or Development days, they have to make a written request to Inria and to the extent that is possible, a service provision contract will be established at Inria prices.
7.4 Conditions for trainee (Gold and Platinum member only)
A Member can request that a trainee be hosted by Inria. Inria is allowed to delegate hosting of the trainees to the PHARO Team.
To benefit of this offer, the member has to sign a request made following the template attached to the present Agreement (see appendix 3) and send it to Inria following the notification rules described in Article 14.
This request shall specify the amount paid for the internship and the desired subject. The trainee will be chosen and supervised by Inria or the PHARO team, at their choice. The organization chosen to host the trainee will make its best effort to find and take a trainee in the Year but it will not be required to meet a certain deadline. The duration of the internship will be decided by Inria and will depend on the additional amount paid by the Member. In all cases, the trainee period may not exceed six (6) months.
Inria shall integrate the contributions of the trainee in the PHARO Release if it is considered ready by the Pharo technical board.
Article 8: Commitments
8.1 Inria commitments
8.1.1 Inria shall employ its best efforts to develop PHARO in accordance with the Consortium's objectives.
8.1.2 Inria shall lead the development of the PHARO Consortium Website (accessible to all Members). It shall post all necessary information to enable Members to subscribe to their mutual and specific benefits.
8.1.3 Inria shall employ its best efforts to provide the technical and administrative coordination for the Consortium's actions. It shall particularly work to group together on the PHARO Consortium website the scientific contributions to the PHARO platform made by third parties or by the Members that are considered to be of general interest by the General Assembly, and incorporated into the Release in accordance with the provisions of Article 12 of this Agreement.
8.1.4 Inria shall ensure monitoring of the financial fees and shall use them to bring forward the Consortium's objectives as defined by the General Assembly. In particular, it commits to recruit engineers for integration of the contributions to the PHARO Release.
8.1.5 Inria shall guarantee to the Member that the other members of the Consortium have signed an agreement with Inria under the same terms as this Agreement. Only addresses and contact information can be changed if necessary.
8.2 The Member's Commitments
8.2.1 The Member shall renew its financial fee each Year, under the conditions set forth in Article 5. Failing renewal, it shall be excluded from the Consortium according to article 13.1.
8.2.2 The Member undertakes to inform the chairman of the General Assembly in writing of any change concerning the structure of its company during its participation in the Consortium and liable to have direct consequences on the Member's execution of its obligations pursuant to this Agreement according to Article 14.
8.2.3 No provision in this Agreement shall oblige the Member to use PHARO or any feature, specifications, version or application of PHARO produced within the framework of the Consortium, or to refrain from using any other platform with languages other than PHARO.
8.2.4 The Member authorizes Inria to contract with third parties for work or services around PHARO, provided that revenues from these contracts are handled as any other revenue for the consortium, under the supervision of the General Assembly, and that the nature of the contract and its impact on PHARO development are also submitted for comments to the General Assembly.
8.3 Specific commitments for Academic Members
Academic Members must follow the following commitments to stay member.
- Put a link to PHARO Consortium Website from its institutional website.
- When using PHARO to teach, create web pages with documents and courses related to PHARO.
- Provide Inria with an annual report by email of at most half a page of its actions to promote and sustain PHARO.
As member of the PHARO Consortium, the Academic Member shall make its best efforts to:
- Give courses on PHARO or related topics to its students.
- Participate to the development of open source software libraries in PHARO.
- Participate to selected PHARO mailing lists: pharo-dev@lists.pharo.org and/or pharo-users@lists.pharo.org.
- Participate in the authoring of open-source books on PHARO and related topics.
Article 9: Governance
9.1 General Assembly
A General Assembly shall be set up.
9.1.1 Composition of the General Assembly
Each Member shall appoint a representative to the General Assembly and a possible substitute. The Member shall reserve the right to appoint a new representative during the execution of the present membership Agreement, after having informed in writing the chairman of the General Assembly.
An Inria representative shall act as the chairman of the General Assembly.
On the date this membership Agreement comes into force, Inria’s representative shall be Stéphane Ducasse.
In the event of a change, Inria shall appoint a successor and shall inform the other Members in writing.
The General Assembly secretariat services shall be provided by Inria.
9.1.2 Periodicity
The chairman shall organise at least one (1) meeting of the General Assembly each Year for which he shall set the agenda. This agenda will be send to the Members one week before the meeting. The General Assembly shall also meet if so requested by at least two (2) of the representatives who shall propose an agenda to the chairman.
The meetings will be remotely accessible, and representatives will be able to either vote in advance or to delegate their voting rights to another representative should they not be able to attend.
Meetings will be held regardless of the number of Member representatives present.
9.1.3 Role of the General Assembly
It is the governing body that oversees the consortium’s activities. It
- Reviews the state of the PHARO ecosystem and community.
- Recommends technical and nontechnical actions to further develop PHARO.
- Proposes items for the roadmap to the technical board.
- Reviews the financial situation of the consortium:
- Approves consortium expenses for salaries, events (meetings, conferences, …) and outsourced developments.
- Reviews the impacts of specific contracts on the revenues and work program of the consortium.
- Sets work priorities for the different items on the development roadmap from a list curated by the Technical Board.
- Reviews the contributions to PHARO made by personnel employed by Inria to work for the consortium.
- Elects a representative of Standard Members to assist the chairman in day to day operations.
- Approve modifications to the rules governing the PHARO consortium. If they imply changes in this membership agreement, new rules can only enter into effect once this agreement is updated or replaces following provisions of article 13.4.
9.1.4 Decision process
Decisions of the General Assembly shall be approved by a majority of votes of Standard Members present or represented, except for roadmap prioritization. Only Standard members get to vote. Roadmap prioritization is decided according to the process described in article 9.3.
An Academic Member plays a consultative role. His representative may attend the meetings of the General Assembly as a guest. He can propose ideas, suggestions and give his point of view on discussed topics. By attending the meetings, an Academic Member will be informed of the suggestions, orientations and priorities for the development of PHARO and obtain a report of PHARO activities.
Any decision of the General Assembly may be taken in accordance with the above in meetings via teleconference or other means.
9.1.5 Executive Committee
The chairman is assisted by a deputy elected by the General Assembly and by a representative of Inria to form an executive committee. The executive committee is responsible for representing the General Assembly for any day to day matter requiring timely action. It ensures the consortium can react promptly to any unforeseen event or solicitation for the best interest of its members and conduct negotiations on its behalf. The chairman will report on the activities of the executive committee in a timely manner to the General Assembly, that is the authoritative decision making body unless it has delegated its authority for specific actions.
9.2 Technical Board
A committee that oversees the development of the PHARO software shall be set up.
9.2.1 Composition
It will be composed of 7 members.
- 3 members chosen by the PHARO team
- 2 members chosen by Inria among the personnel employed for PHARO
- 2 members elected by the General Assembly. To ensure smooth operations of the technical board, only people who have shown positive contributions to PHARO can be elected. Their contributions are therefore evaluated by the technical board members chosen by the PHARO team and Inria who must approve any candidate before the election by the General Assembly takes place.
Technical Board members serve a one (1) year term (renewable).
9.2.2 Periodicity
This technical board meets as often as necessary, and not less than three (3) times a year. The meetings will be remotely accessible.
9.2.3 Role
The technical board shall:
- Evaluates requests for changes or features.
- Builds a roadmap for the development of PHARO:
- Identifying dependencies between features
- Keeping track of backlog and postponed developments
- Oversees the day to day development and issue handling of PHARO. As such, it shall be responsible to integrate contributions to PHARO from third parties and Members, and to report to the General Assembly their integration in the PHARO release.
- Oversees release management.
- Gets a say on the technical content of contracts around PHARO signed by Inria on behalf of the consortium.
9.2.4 Decision process
Decisions of the Technical Board shall be approved by a majority of votes of members present or represented, except for roadmap prioritization. Roadmap prioritization is decided according to the process described in article 9.3
9.3 Interactions between the General Assembly and the Technical Board to build PHARO’s Roadmap
PHARO’s roadmap is built as illustrated here:
1. The community and the General Assembly propose items for the roadmap.
2. The technical board reviews the proposals, estimating the effort they require before completion and any dependencies. It builds a roadmap, classifying items in the following categories: required, important and possible. The sum of work classified as required should not require more than 50% of available manpower for completion.
3. Standard Members of the General Assembly members get to nominate items on the roadmap. The number of nominations a member can make depends on his membership level. If a member is allowed more than one nomination, he can nominate the same item multiple times. To ensure the best interests of all parties, nominations can be changed during discussions on the roadmap during the General Assembly.
4. The final roadmap is built by the technical board from the required items and those with the most nominations.
**Article 10: Confidential information**
10.1 To be considered as confidential, the written information exchanged by the Parties should bear a written mention indicating its confidential nature.
10.2 In order to be considered as confidential, verbal information should be put into writing within a period of fifteen (15) days after its disclosure. This written document must bear the mention indicating its confidential nature.
10.3 Exchanges of written or verbal information by the Parties shall be presumed as non-exclusive and non-confidential, subject to application of the provisions of articles 10.1 and 10.2.
10.4 Any information considered as confidential pursuant to 10.1 and 10.2 shall not be disclosed to third party or published without written agreement of the Party owner of this information.
10.5 Are not considered confidential the information for which the receiving Party can prove:
- that the information was in the public domain at the time it was communicated; or
- that it later entered the public domain otherwise than by a failure to comply with the present obligation of confidentiality; or
- that the Party was in possession of the information prior to its being communicated; or
- that it received the information freely from a third party authorized to disclose it; or
- that it is legally required to communicate the information.
**Article 11: Publications**
The Members shall be encouraged to disclose to third parties their participation in the Consortium, the subject of this membership Agreement, and have the right to mention its existence, as well as the names of the other Members in the Consortium.
The Parties are free to make scientific publications regarding work undertaken under the Consortium subject to the provisions of Article 10.
Scientific publications shall include any oral or written communication whatever the medium and context may be, intended for a particular public, the subject of which is the technical and scientific aspects of the work carried out within the framework of the Consortium.
Article 12: Intellectual Property rights
12.1 Background
The background concerned by this agreement is PHARO in its latest Release.
PHARO is released under the MIT open source License and is available at the following address: http://www.pharo.org
12.2 License
The terms and conditions of use, exploitation, and distribution of PHARO by a third party are provided by the MIT open source License. Prior acceptance of these conditions is necessary to have access to the PHARO source code. The text of this license is accessible at the following address: http://opensource.org/licenses/mit-license.php
12.3 Consortium results
The Consortium results include all improvements, new versions, and changes made by one or more Members, decided, funded, and monitored by the Parties under Article 9 of this Membership Agreement.
The Consortium results are incorporated into the latest Release of PHARO under the responsibility of the Technical Board, as described in 9.2.3 of this Membership Agreement.
The Consortium results incorporated under the latest Release remain the ownership of the Members who have generated them. In particular, Consortium results generated by Inria personnel working for the PHARO consortium remain the ownership of Inria. However as expressed below all the results will be published under the MIT license.
The Consortium results incorporated into PHARO shall be edited, published, and disclosed by Inria via the Technical Board.
To this end, each Member allows Inria to edit, publish, and disseminate its results and contributions under the MIT License. This commitment will be officially recorded by written agreement between the Member concerned and Inria according to the template attached to the present Agreement (see appendix 2).
The incorporation of Consortium results into PHARO is final and irreversible. The PHARO Release with improvements and results is available under the MIT License.
12.4 Other results
Results obtained outside of the Consortium are:
- All improvements, new versions, and changes to PHARO performed by a third party or third parties (i.e., any individual person or corporate body) who have not signed this membership Agreement with Inria.
- All improvements, new versions, and changes to PHARO performed by one or more Members outside the Consortium's objectives and therefore not contained in the Release.
These results outside the consortium comprising derived or composite works in the meaning of Article L 113-2 paragraph two of the Intellectual Property Code, belong to third parties and Members who developed them. Such third parties or Members are free to use these results as they wish (to incorporate them in other software, etc.) and these results can be disseminated under the license of their choice.
Nevertheless, if third party results have a general interest, the Technical Board shall employ its best efforts to approach the third party to propose incorporating its results into the PHARO Release, in accordance with the procedure described in article 7 of this Membership Agreement.
Incorporation of Consortium results into PHARO is final and irreversible. The PHARO Release with improvements and results from third parties is available under MIT License.
**Article 13: Termination**
13.1 Fees not paid
In the case of non-renewal of the financial fee by the Member to the Consortium under the terms covered by Article 5, the Agreement shall be terminated by Inria under the conditions described in article 13.2 below.
13.2 Failure of one of the parties
This Agreement shall be terminated by one of the Parties in the event of failure by the other Party to perform one or more of the obligations contained in the above provisions. This termination shall become effective only three (3) months after the plaintiff Party has sent a registered letter with acknowledgement of receipt, as per the date of reception by the defaulting party, describing the reasons for the complaint unless, within this period of time, the defaulting Party has met its obligations. Such termination does not prevent the defaulting Party from fulfilling its contractual obligations until the entry into force of such termination, subject to any losses possibly sustained by the plaintiff Party due such termination of the agreement.
13.3 Termination by the member
The Member has the right to terminate this agreement at any time on prior notice sent by registered letter with acknowledgement of receipt to Inria two months before the desired termination date, as per the date of reception by the Coordinator. All sums already paid to Inria are not refundable. At the effective date of termination the Member will no longer be consider as a Consortium member and will lose all membership benefits.
13.4 Termination following update of the membership agreement
If the General Assembly decides to update the rules governing the PHARO consortium, Inria will implement these changes by sending a contract amendment or a new membership agreement to all parties by registered letter with acknowledgement of receipt. This agreement will then be terminated at the earliest of the following dates
- End of the Year the notification was received by the Member
Date at which the proposed contract amendment or proposed new membership agreement was signed by the Member.
13.5 Termination by Inria
Inria has the right to terminate this agreement at the end of each Year on prior notice sent by registered letter with acknowledgement of receipt to all Members two months before the end of the concerned Year, as per the date of reception by the Coordinator. All sums already paid to Inria are not refundable.
13.6 Termination due to lack of resources
As an exception to 13.5, Inria has the right to terminate this agreement at the end of each Year on prior notice sent by registered letter with acknowledgement of receipt to all Members one month before the end of the concerned Year, as per the date of reception by the Coordinator, if the expected revenues for the next Year are insufficient to cover the expected expenses as approved by the General Assembly.
Article 14: Notification
Any notification related to the implementation or interpretation of this Agreement shall be validly made if sent either
- by registered letter with acknowledgment of receipt, or
- by email provided the receiving party confirms receipt by email less than one week after notification was sent.
The contact information to use for notification is listed below:
14.1 Inria contact information
Inria
Direction générale déléguée à l’innovation
INRIASOFT
Domaine de Voluceau
Rocquencourt
BP 105
78153 LE CHESNAY, France
Email: consortium-adm@pharo.org
14.2 Member contact information
Name:
Address:
Tel:
Email:
Article 15: Nature of the Consortium.
The Parties have only an obligation of means regarding the objectives of this Agreement.
Article 16: Entire agreement
This membership Agreement and its appendix constitute the entire agreement between the Member and Inria with respect to the PHARO Consortium, and replace all other agreements or representations, whether written or oral.
Article 17: Independence of the provisions
If one or more provisions of this Agreement are held to be invalid or declared as such by application of a law, a regulation, or a final decision by a relevant jurisdiction, the other provisions shall retain all their force and validity.
Article 18: Assignment of the agreement
This Agreement is concluded *intuitu personae*. It is personal, non-transferrable, and non-assignable.
In the event of merger, acquisition, transformation of the Member, transfer of activity to another entity, this agreement cannot be transferred without prior written consent from Inria.
Article 19: Governing law
This Agreement is governed by French law.
Article 20: Settlement of disputes
Any dispute which may arise from the interpretation or performance of this Agreement remaining unresolved by the Parties for a period of thirty (30) days, shall be brought before the relevant court.
Membership form
☐ I have updated the preamble with my organization’s formal name and address
☐ I have updated section 14.2 with contact information for any formal notification regarding this membership agreement.
☐ I have chosen my membership level hereafter
☐ “Academic” Member
☐ “Bronze” Member
☐ “Silver” Member
☐ “Gold” Member
☐ “Platinum” Member
☐ I wish to pay more than the minimal fee for this membership level, for a total membership fee of ______€
☐ Additional 4 days of Support or of Specific Consulting or Development support days purchased: ______________
Drawn up at .................., on .....................
in two original copies
For The Member For Inria
Appendix 1
Presentation of PHARO Consortium and its objectives
The goal of the consortium is to structure and build an umbrella to foster business around PHARO and to promote PHARO.
There are several goals for the consortium.
**Promote.** The consortium will promote PHARO by supporting conferences, books, videos, exhibitions, and conference participation. It will improve PHARO visibility and support the expansion of its community.
**Give the direction of PHARO.** The role of the consortium is also to help deciding the future development of PHARO. The consortium will gather input from its members from a business perspective.
**Support the day to day development of PHARO.** The consortium will collect funds. The consortium will structure the development of PHARO. It will pay engineering tasks to be performed such as improving the virtual machine, network libraries, better JIT support or any other tasks decided by the General Assembly.
**Provide a solid, trustable visibility.** The consortium should show that PHARO is a mature and relevant technology. The website will provide a virtual showroom for PHARO success stories.
**Provide support.** The consortium will support a business eco-system around PHARO. The consortium will offer some support to help its members and their developments in PHARO.
Appendix 2
Agreement on Member contributions to PHARO
SOFTWARE DISTRIBUTION AGREEMENT
This Distribution Agreement ("Agreement") is entered into as of ___________ (the “Effective Date”) by and between ______________________________ ("Supplier").
whose address is
and Inria .................................................................("Distributor").
Together,
Distributor and Supplier are referred to herein as the “Parties” and each individually as a “Party.”
The Parties agree that Supplier wishes to contribute to the development of the open source software known as PHARO, which is currently supported by the Distributor. The Parties acknowledge that the Software in its entirety is a work containing source code contributions from several authors, and that Supplier’s Code is only a small component part of the Software work as a whole.
When submitting a contribution, (the “Supplier’s Code”) , the Parties agree that Supplier retains all rights in and to Supplier’s Code, aside from the rights expressly granted to Distributor in this Agreement.
When submitting Supplier's Code to be integrated in PHARO, Supplier hereby grants Distributor a perpetual, irrevocable, non-exclusive, royalty-free, worldwide license to distribute the Software, and specifically the Supplier’s Code therein, to end users, subject to the license agreement commonly known as the “MIT License” which is provided at the following URL:
<http://www.opensource.org/licenses/mit-license.php>.
Should the Supplier not be willing for its Supplier's Code to be distributed in PHARO in the above cited conditions, the Supplier should then refrain from submitting it.
Supplier acknowledges that it has the required rights to submit Supplier's Code, to be integrated and distributed in PHARO in the above cited conditions.
FOR SUPPLIER
Name
Date
Signature
Appendix 3 Model letter for internship demand
(To be completed on official letterhead of the Member)
Internship Demand for PHARO consortium
According to articles 7.1.5 and 7.4 of the membership agreement to the PHARO consortium, I undersigned, hereby, M…………., as representative of ………..(name of the company) platinum member of the consortium PHARO, calls for Inria to take a trainee on the following topic :…………………………
To allow Inria to take a trainee, ……………. (name of the company) shall pay Inria the amount of……….. euros without VAT (For french Member, the VAT applicable at the date of signature of this letter shall apply) in additional of the annual fees as Platinum member.
Said sum shall be paid by……………..(name of the company) upon presentation of an invoice by Inria
The invoice has to be sent to the following address:
…………………………………………
…………………………………………
…………………………………………
Payments shall be made within thirty (30) days from the date of receipt of Inria invoice.
For …………………..
Name………………………….
Title ………………………..
Date……………………..
Signature :
|
{"Source-Url": "http://files.pharo.org/consortium/2021-08-17-PHARO-membership-agreement.pdf", "len_cl100k_base": 8641, "olmocr-version": "0.1.53", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 52143, "total-output-tokens": 9724, "length": "2e13", "weborganizer": {"__label__adult": 0.000850677490234375, "__label__art_design": 0.0018100738525390625, "__label__crime_law": 0.00429534912109375, "__label__education_jobs": 0.1817626953125, "__label__entertainment": 0.0003974437713623047, "__label__fashion_beauty": 0.00047659873962402344, "__label__finance_business": 0.1483154296875, "__label__food_dining": 0.0008897781372070312, "__label__games": 0.00201416015625, "__label__hardware": 0.0015316009521484375, "__label__health": 0.0011472702026367188, "__label__history": 0.0009822845458984375, "__label__home_hobbies": 0.0008640289306640625, "__label__industrial": 0.0015201568603515625, "__label__literature": 0.0015316009521484375, "__label__politics": 0.0015993118286132812, "__label__religion": 0.0009517669677734376, "__label__science_tech": 0.0234222412109375, "__label__social_life": 0.0007171630859375, "__label__software": 0.047119140625, "__label__software_dev": 0.5751953125, "__label__sports_fitness": 0.0008311271667480469, "__label__transportation": 0.0008449554443359375, "__label__travel": 0.0008845329284667969}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 41525, 0.02359]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 41525, 0.02689]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 41525, 0.94817]], "google_gemma-3-12b-it_contains_pii": [[0, 724, false], [724, 3094, null], [3094, 5399, null], [5399, 7719, null], [7719, 10241, null], [10241, 11926, null], [11926, 14685, null], [14685, 17477, null], [17477, 20112, null], [20112, 22218, null], [22218, 24554, null], [24554, 25981, null], [25981, 28552, null], [28552, 30921, null], [30921, 33766, null], [33766, 35433, null], [35433, 36604, null], [36604, 37308, null], [37308, 38628, null], [38628, 40474, null], [40474, 41525, null]], "google_gemma-3-12b-it_is_public_document": [[0, 724, true], [724, 3094, null], [3094, 5399, null], [5399, 7719, null], [7719, 10241, null], [10241, 11926, null], [11926, 14685, null], [14685, 17477, null], [17477, 20112, null], [20112, 22218, null], [22218, 24554, null], [24554, 25981, null], [25981, 28552, null], [28552, 30921, null], [30921, 33766, null], [33766, 35433, null], [35433, 36604, null], [36604, 37308, null], [37308, 38628, null], [38628, 40474, null], [40474, 41525, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 41525, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 41525, null]], "pdf_page_numbers": [[0, 724, 1], [724, 3094, 2], [3094, 5399, 3], [5399, 7719, 4], [7719, 10241, 5], [10241, 11926, 6], [11926, 14685, 7], [14685, 17477, 8], [17477, 20112, 9], [20112, 22218, 10], [22218, 24554, 11], [24554, 25981, 12], [25981, 28552, 13], [28552, 30921, 14], [30921, 33766, 15], [33766, 35433, 16], [35433, 36604, 17], [36604, 37308, 18], [37308, 38628, 19], [38628, 40474, 20], [40474, 41525, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 41525, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
8b00895b402a4e7271738bdb00736c764bf732f7
|
**TRAINING AGENTS TO PERFORM SEQUENTIAL BEHAVIOR**
Marco Colombetti+ Marco Dorigo#
TR-93-023
September 1993
Abstract
This paper is concerned with training an agent to perform sequential behavior. In previous work we have been applying reinforcement learning techniques to control a reactive robot. Obviously, a pure reactive system is limited in the kind of interactions it can learn. In particular, it can only learn what we call pseudo-sequences, that is sequences of actions in which the transition signal is generated by the appearance of a sensorial stimulus. We discuss the difference between pseudo-sequences and proper sequences, and the implication that these differences have on training procedures. A result of our research is that, in case of proper sequences, for learning to be successful the agent must have some kind of memory; moreover it is often necessary to let the trainer and the learner communicate. We study therefore the influence of communication on the learning process. First we consider trainer-to-learner communication introducing the concept of reinforcement sensor, which let the learning robot explicitly know whether the last reinforcement was a reward or a punishment; we also show how the use of this sensor induces the creation of a set of error recovery rules. Then we introduce learner-to-trainer communication, which is used to disambiguate indeterminate training situations, that is situations in which observation alone of the learner behavior does not provide the trainer with enough information to decide if the learner is performing a right or a wrong move. All the design choices we make are discussed and compared by means of experiments in a simulated world.
---
* This work has been partly supported by the Italian National Research Council, under the "Progetto Finalizzato Sistemi Informatici e Calcolo Parallelo", subproject 2 "Processori dedicati", and under the "Progetto Finalizzato Robotica", subproject 2 "Tema: ALPI".
+ Progetto di Intelligenza Artificiale e Robotica, Dipartimento di Elettronica e Informazione, Politecnico di Milano, Piazza Leonardo da Vinci, 32, 20133 Milano, Italy (e-mail: colombe@ipmel2.elet.polimi.it).
# International Computer Science Institute, Berkeley, CA 94704, and Progetto di Intelligenza Artificiale e Robotica, Dipartimento di Elettronica e Informazione, Politecnico di Milano, Piazza Leonardo da Vinci, 32, 20133 Milano, Italy (e-mail: dorigo@icsi.berkeley.edu).
1. Introduction
This paper is concerned with the application of evolutionary reinforcement learning to the development of agents that act in a given environment.
Machine learning techniques have been widely adopted to shape the behavior of autonomous agents in partially unpredictable environments. Most often, agents are viewed as reactive systems, that is as systems whose actions are completely determined by current sensorial input. Several works in the literature, both theoretical and experimental, show that reactive systems can learn to carry out fairly complex tasks (see for example Mahadevan & Connell, 1992; Dorigo & Colombetti, 1992); however, there are interesting behavioral patterns that just cannot be exhibited by reactive systems, in that they are not determined by current perceptions alone.
An important class of non-reactive tasks is the class of sequential behavior patterns, that is behaviors in which the decision of what action to perform at time \( t \) is influenced by the actions performed in the past. The problem of learning sequential behavior has been tackled by Singh (1992) in the context of Q-learning. In this paper, we present a different approach to the problem of learning sequential behavior patterns, viewed as the result of coordinating separately learned basic behaviors (Colombetti & Dorigo, 1992).
The work presented here is part of a wider research effort aimed at developing agents capable of complex behavior through both explicit design and machine learning. In our research, which has a strong experimental orientation, we use ALECSYS, a software tool designed by Dorigo (1992). ALECSYS allows one to implement an agent as a network of interconnected modules, each of which is a learning classifier system (Booker, Goldberg & Holland, 1989). The system, which runs in parallel on a network of transputers, has been connected to both simulated agents and physical robots. The behavior of agents implemented through ALECSYS is shaped through a supervised reinforcement scheme, that is through reinforcements provided by an external trainer observing the agent’s behavior.
Our general methodology is the following. First, we define an environment, an agent, and a target behavior pattern that we want the agent to exhibit in the environment. Then we design a sensorimotor interface and a modular control architecture for the agent; typically, we use a hierarchical architecture where lower level modules are in charge of implementing basic reactive responses, and higher level modules are in charge of coordinating such responses to execute the overall task. We also design a training policy, i.e. a strategy to train the agent, and implement the trainer as a computer program in charge of giving reinforcements to the agent. Finally, we plan and execute a number of experiments to see whether the target behavior emerges, and to analyze the effect of different design choices on the agent’s performance.
In this paper we present the results of a research aimed at developing sequential behavior in a simulated agent. In particular, we concentrate on the problem of coordinating previously learned basic behaviors in such a way that a sequential behavior pattern will emerge. In Section 2, we define some technical terminology and situate the problem of sequential behavior in the context of a general approach to the development of autonomous agents. Section 3 briefly describes ALECSYS. In Section 4 we define the agents, the environment and the behavior patterns on which we have carried out our experimentation, and specify our experimental plan. In Section 5 we describe the two different training strategies which we used in our experiments. In Section 6, we report the results of a number of simple experiments. Concluding remarks are given in Section 7.
2. Reactive and dynamic behavior
As we have already pointed out, the simplest class of agents is that of reactive systems, i.e. agents which react to their current perceptions (Wilson, 1990; Littman, 1992). In a reactive system, the action $a(t)$ produced at time $t$ is a function of the sensorial input $s(t)$ at time $t$:
$$a(t) = f(s(t)).$$
As argued by Whitehead & Lin (1993), reactive systems are perfectly adequate to Markov environments, i.e. when:
- The greedy control strategy is globally optimal. This means that choosing the locally optimal action in each environmental situation leads to a course of actions that is globally optimal.
- The agent has complete knowledge of both the effects and the costs (or gains) of each possible action in each possible environmental situation.
In this case, there are well-known learning schemes, like Q-learning (Watkins, 1989; 1992), that are demonstrably able to discover the optimal control strategy through experience. In other words, a learning reactive agent can improve its performance so that it asymptotically converges to the optimal control strategy.
Although fairly complex behaviors can be carried out in Markov environments, very often an agent cannot be assumed to have complete knowledge about the effects and/or the costs of its own actions. Non-Markov situations are basically of two different types:
- Hidden-state environments. A hidden state is a part of the environmental situation that is not accessible to the agent, but is relevant to the effects and/or to the costs of actions. If the environment includes hidden states, a reactive agent cannot choose an optimal action; for example, a reactive agent cannot decide an optimal movement to reach an object that it does not see.
• **Sequential behavior.** Suppose that at time $t$ an agent has to choose an action as a function of the action performed at time $t-1$. A reactive agent can perform an optimal choice only if the action performed at time $t-1$ has some characteristic and observable effect at time $t$, that is only if the agent can infer which action it performed at time $t-1$ by inspecting the environment at time $t$. For example, suppose that the agent has to put an object in a given position, and then to remove the object. If the agent is able to perceive that the object is in the given position, it will be able to appropriately sequence the placing and the removing actions. However, a reactive agent will be unable to act properly at time $t$ if:
- the effects of the action performed at time $t-1$ cannot be perceived by the agent at time $t$ (this is a subcase of the hidden-state problem); or:
- no effect of the action performed at time $t-1$ persists in the environment at time $t$.
To develop an agent able to deal with non-Markov environments, one must go beyond the simple reactive model. We say that an agent is **dynamic** if the action $a(t)$ it performs at time $t$ depends not only on its current sensorial input $s(t)$, but also on its state $x(t)$ at time $t$; in turn, such state and the current sensorial input determine the state at time $t+1$:
$$a(t) = f(s(t), x(t));$$
$$x(t+1) = g(s(t), x(t)).$$
In this way, the current action can depend on the past history.
Agent’s states can be called **internal states**, to distinguish them from the states of the environment. They are often regarded as memories of the agent's past, or as representations of the environment; however, in spite of their rather intuitive meaning, terms like **memory** or **representation** can easily be used in a confusing way. Take for example the packing task proposed by Lin & Mitchell (1992) as an example of non-Markov problem:
“Consider a packing task which involves 4 steps: open a box, put a gift into it, close it, and seal it. An agent driven only by its current visual percepts cannot accomplish this task, because when facing a closed box the agent does not know if the gift is already in the box and therefore cannot decide whether to seal or open the box.”
It seems that the agent needs to remember that it has already put a gift into the box. In fact, the agent must be able to assume one of two distinct internal states, say 0 and 1, so that its controller can choose different actions when the agent is facing a closed box. We can associate state 0 to
---
1 In automata theory, this definition corresponds to a class of automata known as **Mealy machines** (McCluskey, 1986).
“the box is empty”, and state 1 to “the gift is in the box”. Clearly, the state must switch from 0 to 1 when the agent puts the gift into the box. But now, the agent's state can be regarded:
- as a memory of the past action “put the gift into the box;” or:
- as a representation of the hidden environmental state “the gift is in the box.”
Probably, the choice of one of these views is a matter of personal taste. But consider a different problem. There are two distinct objects in the environment, say A and B. The agent has to reach A, touch it, then reach B, touch it, then reach A again, touch it, and so on. In this case, provided that touching an object does not leave any sign on it, there is no hidden state in the environment to discriminate the situations in which the agent should reach A from the ones in which it should reach B. We say that the environment is forgetful, in that it does not keep track of the past actions of the agent. Again, the agent must be able to assume two distinct internal states, 0 and 1, so that its task is to reach A when in state 0, and to reach B when in state 1. Such internal states cannot be viewed as representations of hidden environmental states, because these do not exist. However, we still have two possible interpretations:
- internal states are memories of past actions: 0 means that B has been touched, and 1 means that A has been touched;
- internal states are goals, determining the agent's current task: state 0 means that the current task is to reach A, state 1 means that the current task is to reach B.
The conclusion we draw is that terms like memory, representation and goal, which are very commonly used for example in artificial intelligence, often involve a subjective interpretation of what is going on in an artificial agent. The term internal state, borrowed from systems theory, seems to be neutral in this respect, and it describes more faithfully what is actually going on in the agent.
In this paper, we are concerned with internal states that keep track of past actions, so that the agent's behavior can follow a sequential pattern. In particular, we are interested in dynamic agents possessing internal states by design, and learning to use them to produce sequential behavior. The idea is that the dynamics of the agent’s state will act as a kind of action plan, able to enforce the correct sequencing of actions. However, this intuitive idea must be taken with some care.
Let us observe that not all behavior patterns that at first sight appear to be the based on an action plan are necessarily dynamic. Consider for example an example of hoarding behavior: an agent leaves its nest, chases and grasps a prey, brings it to its nest, goes out for a new prey, etc. This apparently dynamic behavior can be produced by a reactive system, whose stimulus-
response associations are described by the following production rules (where only the most specific production whose conditions are satisfied is assumed to fire at each cycle):
Rule 1: \[ \rightarrow \text{move randomly.} \]
Rule 2: \[ \text{not grasped} \quad \& \quad \text{prey ahead} \rightarrow \text{move ahead.} \]
Rule 3: \[ \text{not grasped} \quad \& \quad \text{prey at contact} \rightarrow \text{grasp.} \]
Rule 4: \[ \text{grasped} \quad \& \quad \text{nest ahead} \rightarrow \text{move ahead.} \]
Rule 5: \[ \text{grasped} \quad \& \quad \text{in nest} \rightarrow \text{drop.} \]
In fact, we ran several experiments showing that a reactive agent implemented with ALECSYS can easily learn to perform similar tasks.
It is interesting to see why the behavior pattern described above, while merely reactive, appears as sequential to an external observer. In fact, if instead of the agent’s behavior we consider the behavior of the global dynamic system constituted by the agent and the environment, the task is actually dynamic. The relevant states are the states of the environment, which keeps track of the effects of the agent’s moves; for example, the effects of a grasping action are stored by the environment in the form of a grasped prey, which can then be perceived by the agent. In the following, we shall call pseudo-sequences those tasks performed by a reactive agent that are sequential in virtue of the dynamic nature of the environment, and we shall reserve the term proper sequence for tasks that can be executed only by dynamic agents, in virtue of their internal states.
Let us rephrase the above considerations. As it has already been suggested in the literature (see for example Rosenschein & Kaelbling, 1986; Beer, 1993), the agent and the environment can be viewed as a global system, made up by two coupled subsystems. For the interactions of the two subsystems to be sequential, at least one of them must be properly dynamic, in the sense that its actions depend on the subsystem’s state. The two subsystems are not equivalent, however, because while the agent can be shaped to produce a given target behavior, the dynamics of the environment is taken as given, and cannot be trained. It is therefore interesting to see whether the only subsystem that can be trained, that is the agent, can contribute to a sequential interaction with states of its own: this is what we called a proper sequence.
In this paper, instead of experimenting with sequences of single actions, we have focused on tasks made up of a sequence of phases, where a phase is a subtask which may involve an arbitrary number of single actions. Again, the problem to be solved is: how can we train an agent to switch from the current phase to the next one on the basis of both the current sensory input and knowledge of the current phase?
One important thing to be decided is when the phase transition should occur. The most obvious assumption is that a *transition signal* is produced by the trainer or by the environment, and is perceived by the agent. Clearly, if we want to experiment on the agent’s capacity to produce proper behavioral sequences, the transition signal must not itself convey information about which should be the next phase.
3. The learning system
ALECSYS is a tool to develop learning agents. Using ALECSYS, the learning “brain” of an agent can be designed as the composition of many learning behavioral modules. Some of these modules, which we call *basic behaviors*, are directly connected with sensorial and actuatorial routines, and their task is to learn responses to external stimuli. In some architectural organizations, namely in hierarchical architectures, we define a second kind of modules, called *coordination behaviors*, whose main task is to learn to coordinate other behaviors. Coordination modules are connected to lower-level modules, both basic and coordination ones, and can either choose which of the actions proposed by connected modules should be given priority, or compose such actions into a complex behavioral response.
There are different ways in which behavioral modules can be put together to build a learning system. In a recent study we have investigated a number of them (Dorigo & Colombetti, 1992), which we briefly summarize below.
- **Monolithic architecture.** In this architecture (see Figure 1) there is only one learning module which is in charge of learning all the behaviors necessary to accomplish the task. It is the most straightforward way of building a learning system, but it is not very efficient. In fact, it was the inefficiency of this approach which first motivated *distributed* architectures.
- **Distributed architectures.** In these architectures the system designer first analyzes the learning agent task and then splits it up into simpler tasks. Each of these tasks is then implemented as a monolithic architecture. Usually the simpler tasks identified by the system designer have an intuitive correspondence with the notion of *atomic behavioral module*, that is of a behavioral module which cannot be reasonably further decomposed. After atomic behavioral units are identified they must be interconnected to build the complete learning system; this can result in two different kind of architectural organizations, which are listed in the following.
- **Flat architectures.** In flat architectures all the behavioral modules are basic behaviors, that is they are directly interfaced with the environment. In case two or more behavioral modules produce homogeneous responses (e.g., they control the same movement actuators) their
actions are composed by an appropriate composition module (see Figure 2a); otherwise they just send their responses to the appropriate actuators (see Figure 2b).
**Hierarchical architectures.** In this case a hierarchy of behavioral modules is used to build the learning system. Beside basic behaviors, which directly connect the system to the external world, there are coordination behaviors, which are in charge of coordinating basic and other coordination modules. Figure 3 shows an example of a possible architecture of an agent implemented using ALECSYS. In this case we have three basic behaviors and two coordination behaviors. C1 is in charge of coordinating B1 and B2, while C2’s task is to coordinate C1 and B3. For example C2 could decide that whenever C1 and B3 are proposing some action, C1 should have priority. In turn, C1 could learn to compose the actions proposed by B1 and B2 into an intermediate action. Say B1 proposed a movement in direction $-10^\circ$ and B2 a movement in direction $+30^\circ$; then C1 could have learnt to mediate the two proposals in a $+20^\circ$ movement (other solutions are possible in which the two proposed actions are given different weights).



In ALECSYS, every single module is an enhanced version (see Dorigo, 1993) of a learning classifier system (CS) as proposed for example by Booker, Goldberg & Holland (1989). CSs are a rather complex paradigm for reinforcement learning. Functionally, they can be split in three components. The first one, called the performance system, is a kind of parallel production system; its role is to map input sensations into output actions. In the current version of ALECSYS, the performance system is a reactive system, in that internal messages are not allowed and therefore the system cannot remember past actions.
The second and third components, the credit apportionment and the rule discovery components respectively, are the learning components of a CS. The task of the credit apportionment subsystem is to evaluate rules in the rule base so that useful rules are ranked higher than less useful ones. For each rule a variable, called strength, measures the usefulness of the rule as evaluated by the credit apportionment subsystem. Strength is changed by means of redistribution of reinforcements received by the CS as feedback for actions performed. The algorithm we used is an extended version of the bucket brigade (Holland, 1986) which has been presented in details elsewhere (Dorigo, 1993). Since reinforcements are received at each step from an external trainer, ALECSYS is a supervised reinforcement learning system.
The third components is the rule discovery subsystem, which in ALECSYS is implemented by means of a genetic algorithm (GA). Genetic algorithms are a kind of evolutionary algorithm first proposed by Holland (1975). They work applying so-called genetic operators to a population of individuals which code solutions to a given problem. In the context of machine learning, most of the time individuals are rules and genetic operators mutate and recombine rules to produce new, hopefully more useful, ones. New rules, which overwrite low strength rules in the population, are tested and retained in case they demonstrate their utility to the learning system performance.
The main strengths of GAs are that:
- They can be easily implemented on a parallel computer (e.g., see Spiessens & Manderick, 1991).
- They are very efficient in recombinig rule components, favoring the reproduction, and therefore the survival, of those components which are more often contained in rules with a higher than average strength. It has been proven that the number of structures which are processed by the GA at every cycle is much greater than the number of individuals in the population (Booker, Goldberg & Holland, 1989; Bertoni & Dorigo, 1993).
- They seem to be only slightly sensitive to the precision with which the usefulness of individuals, i.e. their strength, is evaluated. This is important because strength, which is evaluated by the bucket brigade, is only a rough indicator of good performance.
In ALECSYS, the GA is called when the apportionment of credit system has reached a steady state, i.e. when the strengths of rules in the population tend to be stationary (this property is monitored at runtime). It works applying in sequence the crossover and the mutation operators (Goldberg, 1989) and returning the modified population (Figure 4). More details about the actual implementation can be found in (Dorigo, 1993).
\[
\text{function } \text{GA}(\text{Pop}); \\
\text{Pop} \leftarrow \text{Crossover}(\text{Pop}); \\
\text{Pop} \leftarrow \text{Mutate}(\text{Pop}); \\
\text{return}
\]
Figure 4. The genetic algorithm.
4. Experimental settings
When planning an experiment, the environment, the agent, and the target behavior must be designed together. Such entities are introduced here separately for descriptive convenience only.
4.1 Environment
What is a good experimental setting to show that proper sequences can emerge? Clearly, one in which: (i) agent-environment interactions are sequential, and (ii) the sequential nature of the interactions is not due to states of the environment. Indeed, under these conditions we have the guarantee that the relevant states are those of the agent. Therefore, we have carried out our initial experiments on sequential behavior in forgetful environments, that is in environments that keep no track of the effects of the agent’s move.
Our environment is basically an empty space containing two objects, that we respectively call A and B (Figure 5). The distance between A and B, which lie on a bidimensional plane in which the agent can move freely, is approximately 100 forward steps of the agent. In some of the experiments, both objects emit a signal when the agent enters a circular area of predefined radium around the object (shown by the dashed circles in the figure).
4.2 The agent’s “body”
The agent is a simulation of a simple mobile robot, which is intended to play the role of an artificial organism, and is thus called the Animat (see Wilson, 1987). The Animat's sensors are two on/off eyes with limited visual field of 180° and an on/off microphone. The eyes are able to detect the presence of an object in their visual fields, and can discriminate between the two objects A and B. The visual fields of the two eyes overlap by 90°, so that the total angle covered by the two eyes is 270°, and is partitioned in three areas of 90° each (see Figure 5).
The Animat’s actuators are two independent wheels that can either stay still, move one or two steps forward, or one step backward.
4.3 Target behavior
The target behavior is the following: the Animat should approach object A, then approach object B, then approach object A, and so on. (A more complex target behavior has been adopted in the experiment reported in Section 7.) This target sequence can be represented by the regular expression \( \{\alpha\beta\}\ast \), where we denote by \( \alpha \) the behavioral phase in which the Animat should approach object A, and by \( \beta \) the behavioral phase in which the Animat should approach object B. We assume that the transition from one phase to the next should occur when the Animat’s microphone senses a sound, which acts as a transition signal. This signal tells the Animat that it is time to switch to the next phase, but does not tell it which phase should be the next.
Concerning the production of the transition signal, there are basically two possibilities:
- **external-based transition**: the transition signal is produced by an external source (e.g., the trainer) independently of the current interaction between the agent and its environment;
- **result-based transition**: the transition signal is produced when a given situation occurs as a result of the agent’s behavior; for example, a transition signal is generated when the Animat

has come close enough to an object.
The choice between these two variants corresponds to two different intuitive conceptions of the overall task. If we choose external-based transitions, what we actually want from the Animat is that it learns to switch phase each time we tell it to. Instead, if we choose result-based transitions, we want the Animat to achieve a given result, and then to switch to the next phase. In fact, suppose that the transition signal is generated when the agent reaches a given threshold distance from A or from B. This means that we want the agent to reach object A, then to reach object B, and so on. As we shall see, the different conception of the task underlying this choice influences the way in which the Animat can be trained.
It would be easy to turn the environment described above into a Markov environment, so that a reactive agent could learn the target behavior. For example, we could assume that A and B are two lights, which are alternatively switched on and off, exactly one light being on at each moment. In this case, a reactive Animat could learn to approach the only visible light, and a pseudo-sequential behavior would emerge as an effect of the dynamic nature of the environment.
4.4 The agent's controller and sensorimotor interfaces
For the \{\alpha\beta\}^* behavior we implemented two agents with different control architectures. We used a monolithic architecture, and a two-level hierarchical architecture (see Section 3). In this paper we report the experiments performed with the latter, which gave better results.
The two-level hierarchical architecture was organized as follows. Basic modules consisted of two independent CSs, that we shall call CS\(\alpha\) and CS\(\beta\), respectively in charge of learning the two basic behaviors \(\alpha\) and \(\beta\). The coordinator consisted of one CS, in charge of learning the sequential coordination of the lower level modules.
The input of each basic module represents the relative direction in which the relevant object is perceived. Given that the Animat's eyes partition the environment into four angular areas, both modules have a 2-bit sensory word as input. At any cycle, each basic module proposes a motor action, which is represented by 4 bits coding the movement of each independent wheel.
Coordination is achieved by choosing for execution exactly one of the actions proposed by the lower level modules. This choice is based on the value of a 1-bit word, that represents the internal state of the agent, and that we therefore call the state word. The effect of the state word is hardwired: when its value is 0, the action proposed by CS\(\alpha\) is executed; when the value is 1, it is CS\(\beta\) that wins.
The coordinator receives as input the current value of the state word, and 1 bit representing the state of the microphone; this bit is set to 1 at the rising edge of the transition signal, and is equal to 0 otherwise. The possible actions for the coordinator are: (i) set the state word to 0, and (ii) set
the state word to 1. The task that the coordinator has to learn is to maintain the same phase if no transition signal is perceived, and to switch phase each time a transition signal is perceived.
The basic controller architecture is described in Figure 6. Viewed as a dynamic system, it is a Mealy machine (see Equations 1, Section 2), in that at each cycle \( t \), the sensory input at \( t \) and the value of the state word at \( t \) jointly determine both the action performed at \( t \) and the value of the state word at \( t+1 \).
4.5 Experimental design
For each experiment reported in this paper we ran twelve independent trials, starting from random initial conditions. Each trial included:
- a basic learning session of 4,000 cycles, in which the two basic behaviors \( \alpha \) and \( \beta \) were learned;
- a coordinator learning session of 12,000 cycles, in which learning of basic behaviors was switched off and only the coordinator was allowed to learn;
- a test session of 4,000 cycles, where all learning was switched off and the performance of the agent was evaluated.
In the learning sessions, the agent’s performance \( P_{\text{learn}}(t) \) at cycle \( t \) was computed for each trial as:
\[
P_{\text{learn}}(t) = \frac{\text{Number of correct actions performed from cycle } 1 \text{ to cycle } t}{t}
\]
where an action is considered as correct if it is positively reinforced. The graph of \( P_{\text{learn}}(t) \) for a single trial is called a learning curve. In the test session, the agent’s performance \( P_{\text{test}} \) is
Figure 6. Controller architecture of the Animat.
measured for each trial as a single number:
\[ P_{\text{test}} = \frac{\text{Number of correct actions performed in the test session}}{4000} \]
For each experiment we shall show the coordinator learning curve of a single, typical trial, and report the mean and standard deviation of the twelve \( P_{\text{test}} \) values for: (i) the two basic behaviors (\( \alpha \) and \( \beta \)); and (ii) the two coordinator’s tasks (maintain and switch). It is important to remark that the performance of the coordinator is judged from the overall behavior of the agent. That is, the only information available to evaluate such performance is whether the agent is actually approaching A or approaching B; no direct access to the coordinator’s state word is allowed. Instead, to evaluate the performance of the basic behaviors it is also necessary to know at each cycle whether the action performed was suggested by CS\( \alpha \) or by CS\( \beta \); this fact is established by directly inspecting the internal state of the agent.
Finally, to compare the mean performances of a pair of experiments we use the two-tailed t-test, computing the probability \( p \) that the samples produced by the two experiments are drawn from populations with the same mean performance.
5. Training policies
We view supervised reinforcement learning as a mechanism to translate a specification of the agent's target behavior into a control program that realizes it (Dorigo & Colombetti, 1992). As the translation process takes place in the context of agent-environment interactions, the resulting control program is highly sensitive to features of the environment that would be very difficult to model explicitly in a handwritten program (Dorigo & Colombetti, 1993).
As usual in the field, reinforcements are provided to our learning agent by a computer program, that we call the reinforcement program (RP): it is the RP that embodies a specification of the target behavior. We believe that an important quality an RP should possess is to be highly agent independent. In other words, we want the RP to base its judgments on high-level features of the agent’s behavior, without bothering too much about the details of such behavior. In particular, we want the RP to be as independent as possible from internal features of the agent, which are unobservable to an external observer. This requirement is reminiscent of the well-known methodological principle advocated by behaviorism, which states that only observable variables should be considered in behavior theory. In our case, there are no methodological preoccupation of this sort, also because in principle we can observe the internal states of artificial agents. However, the very same requirement seems to be a sensible engineering principle. In fact, an RP which is independent of events that are internal to the agent will be more abstract, general
and portable to different agents; in particular, it will be less sensitive to possible degradation of the agent’s hardware.
Let us consider the \{αβ\}* behavior, where:
\[\begin{align*}
α &= \text{approach object A;} \\
β &= \text{approach object B.}
\end{align*}\]
The transitions from \(α\) to \(β\) and from \(β\) to \(α\) should occur whenever a transition signal is perceived.
The first step is to train the Animat to perform the two basic behaviors \(α\) and \(β\). This is a fairly easy task, given that the basic behaviors are instances of approaching responses, that can be produced by a simple reactive agent. The only difficulty is due to the fact that the Animat’s world has hidden states: in fact, when an object is behind the Animat, it cannot be seen. The problem has been solved by training each CS to turn the Animat when it does not see the relevant object. This training technique and its results have been described elsewhere (see for example Dorigo & Colombetti, 1992).
After the basic behaviors have been learned, the next step is to train the Animat's coordinator to generate the target sequence. Before doing so, we have to decide how the transition signal is to be generated. We have experimented with both external-based and result-based transitions.
### 5.1 External-based transitions
Let us assume that coordinator training starts with phase \(α\). The trainer rewards the Animat if it approaches object A, and punishes it otherwise. At random intervals, the trainer generates a transition signal. After the first transition signal is generated, the Animat is rewarded if it approaches object B, and punished otherwise; and so on.
Let us now suppose that in phase \(α\), and without any transition signal, the Animat changes behavior. Clearly, as soon as the Animat starts approaching B, the trainer will give a punishment, because a change of phase occurred in absence of a transition signal. But then suppose that the Animat goes on approaching B. What should the trainer do? It would be incoherent to go on punishing the Animat, because it is now doing well: in fact, it is persisting with the same behavior in absence of a transition signal.
On the basis of these considerations, we have applied what we call a flexible reinforcement program \(\text{RP}_{\text{flex}}\), that is:
- start with phase \(α\);
- in phase \(α\), reward the Animat if it approaches A, and punish it otherwise; in phase \(β\), reward the Animat if it approaches B, and punish it otherwise;
• change phase at each transition signal;
• if the Animat appears to change behavior in absence of a transition signal, punish it but change phase;
• analogously, if the Animat appears not to change behavior in presence of a transition signal, punish it but restore the previous phase.
The rationale of this reinforcement program is that the trainer punishes an inadequate treatment of the transition signal, but rewards coherency of behavior. Experiments 1, 2, and 3 (next section) have been run using RP\textsubscript{flex}.
5.2 Result-based transitions
Let us now suppose that the target sequential behavior is understood as follows: the agent should approach and reach object A, then approach and reach object B, etc. A major difference with respect to the previous case is that a transition signal is now generated each time the agent comes close enough to an object (see the dashed circles in Figure 5). This calls for a different reinforcement program. In fact, it no longer makes sense for the trainer to flexibly change phase when the agent switches behavior: a phase is completed only when a given result is achieved, that is when the relevant object is reached.
We have therefore used a different reinforcement program, that we call the \textit{rigid reinforcement program} (RP\textsubscript{rig}):
• start with phase $\alpha$;
• in phase $\alpha$, reward the Animat if it approaches A, and punish it otherwise; in phase $\beta$, reward the Animat if it approaches B, and punish it otherwise;
• change phase at each transition signal, which is generated when the Animat gets to a predefined distance from the relevant object.
This program embodies the idea that the target behavior involves reaching objects, not just approaching them. However, the Animat did not learn the target behavior when trained with the RP\textsubscript{rig}.
It is not difficult to understand why. Consider an interval $[t_1, t_2]$, in which no transition signal is produced, and assume that the Animat erroneously changes behavior at $t_1$. With the RP\textsubscript{rig}, the Animat will be punished until it restores the previous behavior. But this means that in the interval $[t_1, t_2]$ the Animat will be punished if it keeps the same behavior, and rewarded if it changes behavior, even if no transition signal is perceived. From the Animat's point of view, this program
is incoherent: maintaining the same behavior in absence of a transition signal is sometimes rewarded, sometimes punished. In fact, the RP_{rig} rewards the Animat in three different cases:\footnote{Analogous cases hold for punishments.}
(i) when the Animat changes behavior in presence of a transition signal;
(ii) when the Animat \textit{does not} change behavior in absence of a transition signal (provided its current behavior is the right one);
(iii) when the Animat \textit{does} change behavior in absence of a transition signal (provided its current behavior is the wrong one).
Clearly, the problem is to make the agent distinguish between case (ii) and case (iii). To do so, it is sufficient to know at cycle \(N+1\) whether the action performed at cycle \(N\) was right or wrong; and therefore, it is sufficient for the Animat to store the sign of the reinforcement received from the RP_{rig} at the previous cycle.
To allow the Animat to remember whether it had been rewarded or punished at the previous cycle, we introduced a 1-bit \textit{reinforcement sensor}, that is a 1-bit field in the sensory interface telling the Animat whether the previous action had been rewarded or punished. In this way, the agent is able to develop specific behavior rules for case (iii), different from the rules for case (ii). Experiments 4, 5, and 6 (next section) show that the Animat is able to learn the target behavior when trained with the RP_{rig}, if its sensory interface includes the reinforcement sensor. We think that the notion of reinforcement sensor is not trivial, and therefore it needs to be discussed in some detail.
5.3 \textit{Meaning and use of the reinforcement sensor}
At each moment, the reinforcement sensor stores information about what happened in the previous cycle, and as such contributes to the agent's dynamic behavior. Its characteristic feature is that it stores information about the behavior of the trainer, not of the physical environment. It may seem that such information is available to the Animat even without the reinforcement sensor, as it is received and processed by the credit apportionment module of ALECSYS. The point is that information about reinforcement is not available to the Animat’s controller, unless it is coded into the sensory interface. To speak metaphorically, an agent endowed with the reinforcement sensor not only \textit{receives} reinforcements, but also \textit{perceives} them.
It is interesting to see how the information stored by the reinforcement sensor is exploited by the learning process. Let the reinforcement sensor be set to 1 if the previous action was rewarded, and to 0 if it was punished. When trained with the RP_{rig}, the Animat will develop behavior rules that can manage situation (iii) above, that is rules that change phase in absence of a transition
signal if the reinforcement sensor is set to 0. Such rules can be viewed as error recovery rules, in that they tell the agent what to do in order to fix a previous error in phase sequencing. Rules matching messages with the reinforcement sensor set to 1 will be called normal rules, to distinguish them from error recovery rules.
Without a reinforcement sensor, punishments are exploited by the system only to decrease the strength of a rule that leads to an error (i.e., to an incorrect action). With the reinforcement sensor, punishment are used for one extra purpose, that is to enable error recovery rule at the next cycle. In general, as learning proceeds less and less errors are made by the Animat, and the error recovery rules become increasingly weaker, so that sooner or later they are removed by the genetic algorithm.
Error recovery rules presuppose a reinforcement, and thus can be used only as far as the trainer communicates with the agent. If the trainer is switched off to test the acquired behavior, the reinforcement sensor must be clamped to 1, so that normal rules can be activated. This means that after we switch the trainer off, error recovery rules will remain silent; it is therefore advisable to do so only after all recovery rules have been eliminated by the genetic algorithm.
In the experiments reported in this paper, error recovery rules were either eliminated before we switched off the trainer, or they became so weak that they were practically no longer activated. With more complex tasks, however, one can easily imagine that some error recovery rules could maintain a strength high enough to survive and to contribute to the final behavior; in similar situations, switching off the trainer would actually impoverish the final performance. However, one could switch off the learning algorithm: the use of error recovery rules presupposes that an external system gives positive or negative “judgments” about the Animat’s actions, but does not require the learning algorithm to be active. After switching off learning, the trainer actually turns into an advisor, that is an external observer in charge of telling the agent, which is no longer learning anything, whether it is doing well or not.
We still do not know whether the use of an advisor has interesting practical applications; it seems to us that it could be useful in situations where the environment is so unpredictable, that even the application of the most reasonable control strategy will frequently lead to errors. In a similar case, it would not be possible to avoid errors through further learning; error recovery seems therefore to be an appealing alternative.
6. Experimental results
In this section we report the results of the experiments on the \( \{\alpha\beta\}^* \) behavior. The experiments described are the following:
• Experiments 1–3: sequential behavior with external-based transitions and flexible reinforcement program.
• Experiments 4–6: sequential behavior with result-based transitions, rigid reinforcement program and reinforcement sensor.
Experiments 1–3 and 4–6 are compared using two-tailed t-tests.
**Experiment 1: External-based transitions and flexible reinforcement program**
In this experiment, transition signals were produced randomly, with an average of one signal every 50 cycles. The Animat was trained with the flexible reinforcement program, RP_{flex}. Figure 7 shows a typical learning curve for the coordinator learning session, and reports the mean and standard deviation of the performances obtained in the test session out of twelve trials.
It appears that the Animat learns to maintain the current phase (in absence of a transition signal) better than to switch phase (when it perceives a transition signal). This result is easy to interpret: as transition signals are relatively rare, the Animat learns to maintain the current phase faster than it learns to switch phase.
As a whole, however, the performance of the coordinator is not fully satisfactory. One factor that keeps the performance of the coordinator well below 1 is that the performances of the two basic behaviors are not close enough to 1. In fact, during the training of the coordinator an action may be punished even if the coordinator has acted correctly, if a wrong move is proposed by the relevant basic CS.

There is however another reason why the learning of the coordination tasks is not satisfactory: \textsc{RP}\textsubscript{flex} cannot teach perfect coordination because there are ambiguous situations, that is situations where it is not clear whether the reinforcement program should reward or punish the agent. In fact, suppose that the Animat perceives a transition signal at cycle $N$ when it is approaching A on a curvilinear trajectory like the one shown in Figure 8, and that at cycle $N+1$ it goes on following the same trajectory. By observing this behavior, \textsc{RP}\textsubscript{flex} cannot know whether the Animat decided to go on approaching A, or whether it changed phase and is now turning to approach object B. As the agent's behavior is ambiguous, any reinforcement actually runs the risk of saying exactly the opposite of what it is intended to.
Ambiguous situations of the type described earlier arise because the agent’s internal state is a hidden state from the point of view of the trainer. One possible solution is to make the relevant part of this state known to \textsc{RP}\textsubscript{flex}. This was implemented in the next experiment.
\textit{Experiment 2: External-based transitions, flexible reinforcement program and agent-trainer communication}
To eliminate ambiguous situations, we have simulated a communication process from the agent to the trainer: better reinforcements can be generated if the agent communicates its state to the reinforcement program, because situations like the one described earlier are no longer ambiguous.
To achieve this result, we added to the Animat the ability to assume two different observable states, that we conventionally call \textit{colors}. The Animat can be either \textit{white} or \textit{black}, and can assume either color as the result of an action. In turn, the trainer can observe the Animat’s color at any time. The basic modules are now able to perform one more action, that is to set a color bit to 0 (white) or to 1 (black). In the basic learning session, the Animat is trained not only to

perform the approaching behaviors $\alpha$ and $\beta$, but also to associate a single color to each of them. During the coordinator learning session, $R_{P_{\text{flex}}}$ exploits information about the color to disambiguate the Animat’s internal state, using the agent’s color as a message.
As it emerges from the results of this experiment, reported in Figure 9, the coordinator’s performance is slightly higher than in Experiment 1. However, this difference is only weakly significant as regards the switch task (two-tailed t-test: $p = 0.094$), and it is not significant as regards the maintain task ($p = 0.340$).
**Experiment 3: External-based transitions, flexible reinforcement program and transfer of behavior**
Another interesting solution to the problem of ambiguous situations is based on the notion of behavior transfer. The idea is that the $\{\alpha\beta\}$* behavior is based on two components: the ability to perform the basic behaviors $\alpha$ and $\beta$, and the ability to coordinate them in order to achieve the required sequence. While the basic behaviors are strongly linked to the environment, the coordination task is abstract enough to be learned in an environment, and then transferred to another one. Therefore, we proceeded as follows:

The Animat learned the complete \(\{\alpha\beta\}\)* behavior in a simpler environment, where the ambiguity problem did not arise.
Then, the Animat was then trained to perform the two basic behaviors in the target environment.
Finally, the coordinator rules learned in the simpler environment were copied into the coordinator for the target task. To this purpose, we selected the rules that had the highest performance in the simpler environment; therefore, all twelve experiments in the target environment were run with the same coordinator.
The simpler, non ambiguous environment used for coordination training is sketched in Figure 10. It is a 1D counterpart of the target environment: the Animat can only move to the left or to the right on a fixed rail. At each instant, the Animat is either approaching A or approaching B: no ambiguous situations arise.
As reported in Figure 11, the performance achieved in the 1D environment was almost perfect, due to the simplicity of the task. Figure 12 shows the results obtained by transferring the coordinator to an Animat that had previously learned the basic behaviors in the 2D environment.
As it can be seen, there was an improvement in the coordinator’s performance with respect to Experiment 1, weakly significant for the maintain task (p = 0.095) and highly significant for the switch task (p = 0.0002), and also a significant improvement with respect to Experiment 2 as regards the switch task (p = 0.023), but not as regards the maintain task (p = 0.310). As a whole, the transfer of the coordinator gave the best results.
Experiment 4: Result-based transitions and rigid reinforcement program with reinforcement sensor
This experiment was run with result-based transitions: that is, the transition signal was generated each time the Animat reached an object. The target behavior was therefore conceived as: reach object A, then reach object B, and so on. Coherently with this view of the target behavior, we adopted the rigid reinforcement program, RP_{rig} (see Section 5.2); the Animat was therefore endowed with the 1-bit reinforcement sensor.
The results, reported in Figure 13, show that the target behavior was learnt; however, the performance of the switch task was rather poor.
Experiment 5: Result-based transitions, rigid reinforcement program and agent-trainer communication with reinforcement sensor
This experiment is the result-based analogous of Experiment 2: the Animat was trained to assume a color, thus revealing its internal state. The results are reported in Figure 14. Communication significantly improved the performance of both the maintain (p = 0.016) and the switch task (p = 0.002).

### Table 1: Performance in test session: basic behaviors
<table>
<thead>
<tr>
<th>Task</th>
<th>Mean</th>
<th>Std. deviation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Maintain</td>
<td>0.9313</td>
<td>0.0528</td>
</tr>
<tr>
<td>Switch</td>
<td>0.7166</td>
<td>0.1559</td>
</tr>
</tbody>
</table>

### Table 2: Performance in test session: coordination
<table>
<thead>
<tr>
<th>Task</th>
<th>Mean</th>
<th>Std. deviation</th>
</tr>
</thead>
<tbody>
<tr>
<td>Maintain</td>
<td>0.9789</td>
<td>0.0350</td>
</tr>
<tr>
<td>Switch</td>
<td>0.8885</td>
<td>0.0788</td>
</tr>
</tbody>
</table>
Figure 13. Experiment 4: Learning result-based transitions.
Figure 14. Experiment 5: result-based transitions and agent-trainer communication.
Experiment 6: Result-based transitions, rigid reinforcement program and transfer of behavior
This experiment is the result-based analogue of Experiment 3. Figure 15 shows the results obtained in the 1D environment, and Figure 16 gives the performances of the Animat in the 2D environment, after transferring the best coordinator obtained in the 1D environment. The final performances were significantly better than in Experiment 4, both for the maintain (p = 0.0009) and for the switch task (p = 0.0001). In relation with Experiment 5, the improvement of the switch task was weakly significant (p = 0.095), while it was not significant for the maintain task (p = 0.2818).


We conclude this set of experiments with Figure 17, summarizing the results of the t-tests for all relevant pairs of experiments.
Figure 17. Result of t-tests for the maintaining (above) and switching (below) tasks. Significant probability levels are in bold. Arrows indicate the direction of increasing value of the experimental mean; e.g. the mean of Exp.1 is lower of both the mean of Exp.2 and Exp.3.
7. Conclusions
In this paper we have presented an approach to training an agent which learns proper behavioral sequences. Many other researchers have tackled the problem of learning sequences of actions in the realm of classifier systems (e.g., Riolo, 1989). Our work differentiate itself in that the building blocks of our sequences are elementary behaviors instead of simple actions.
We have discussed at length the difference between pseudo- and proper sequences, and we have shown that ALECSYS, our CS-based learning system, can learn proper sequences (pseudo-sequences were discussed in previous work, see Dorigo & Colombetti, 1992).
An important aspect of our research is the attention we pose on the interplay among the learner, the trainer, and the environment. We show that, when considering proper sequences, there are at least two kinds of transition signals which can cause a change to the next phase of the sequence: external-based transitions and result-based transitions. To each of these transition modalities corresponds a training policy, the flexible and the rigid training policies respectively. These policies require the introduction of communication features into our system:
- trainer-to-learner communication (through a reinforcement sensor, which makes explicitly available to the learner information about the quality of its behavior);
- learner-to-trainer communication (to let the learner know what is the current state of the learner).
Most interesting, the use of the reinforcement sensor introduces into the rule set a new kind of rules, called error recovery rules, which are activated only in case of punishment. These rules tend to disappear as learning goes on and performance improves.
Finally, we have shown that the coordination task, at least in the context of our experiments, is abstract enough that it can be learned in a simple situation, and then transferred into a more demanding one.
References
|
{"Source-Url": "http://www.icsi.berkeley.edu/ftp/global/pub/techreports/1993/tr-93-023.pdf", "len_cl100k_base": 12270, "olmocr-version": "0.1.53", "pdf-total-pages": 28, "total-fallback-pages": 0, "total-input-tokens": 73586, "total-output-tokens": 14754, "length": "2e13", "weborganizer": {"__label__adult": 0.00045990943908691406, "__label__art_design": 0.001071929931640625, "__label__crime_law": 0.00046372413635253906, "__label__education_jobs": 0.004528045654296875, "__label__entertainment": 0.00021219253540039065, "__label__fashion_beauty": 0.00028634071350097656, "__label__finance_business": 0.0003731250762939453, "__label__food_dining": 0.0005054473876953125, "__label__games": 0.0015897750854492188, "__label__hardware": 0.002422332763671875, "__label__health": 0.0008282661437988281, "__label__history": 0.0006003379821777344, "__label__home_hobbies": 0.00038909912109375, "__label__industrial": 0.0011129379272460938, "__label__literature": 0.0008068084716796875, "__label__politics": 0.00037789344787597656, "__label__religion": 0.000598907470703125, "__label__science_tech": 0.45654296875, "__label__social_life": 0.00020194053649902344, "__label__software": 0.01165771484375, "__label__software_dev": 0.51318359375, "__label__sports_fitness": 0.0004279613494873047, "__label__transportation": 0.0009717941284179688, "__label__travel": 0.0002493858337402344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 61069, 0.02566]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 61069, 0.79337]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 61069, 0.93228]], "google_gemma-3-12b-it_contains_pii": [[0, 2466, false], [2466, 5425, null], [5425, 8042, null], [8042, 10734, null], [10734, 13567, null], [13567, 16413, null], [16413, 19194, null], [19194, 20563, null], [20563, 23477, null], [23477, 25312, null], [25312, 27379, null], [27379, 30421, null], [30421, 32040, null], [32040, 34930, null], [34930, 37438, null], [37438, 39809, null], [39809, 42653, null], [42653, 45489, null], [45489, 47081, null], [47081, 49209, null], [49209, 50575, null], [50575, 51720, null], [51720, 52825, null], [52825, 53917, null], [53917, 54918, null], [54918, 56922, null], [56922, 58915, null], [58915, 61069, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2466, true], [2466, 5425, null], [5425, 8042, null], [8042, 10734, null], [10734, 13567, null], [13567, 16413, null], [16413, 19194, null], [19194, 20563, null], [20563, 23477, null], [23477, 25312, null], [25312, 27379, null], [27379, 30421, null], [30421, 32040, null], [32040, 34930, null], [34930, 37438, null], [37438, 39809, null], [39809, 42653, null], [42653, 45489, null], [45489, 47081, null], [47081, 49209, null], [49209, 50575, null], [50575, 51720, null], [51720, 52825, null], [52825, 53917, null], [53917, 54918, null], [54918, 56922, null], [56922, 58915, null], [58915, 61069, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 61069, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 61069, null]], "pdf_page_numbers": [[0, 2466, 1], [2466, 5425, 2], [5425, 8042, 3], [8042, 10734, 4], [10734, 13567, 5], [13567, 16413, 6], [16413, 19194, 7], [19194, 20563, 8], [20563, 23477, 9], [23477, 25312, 10], [25312, 27379, 11], [27379, 30421, 12], [30421, 32040, 13], [32040, 34930, 14], [34930, 37438, 15], [37438, 39809, 16], [39809, 42653, 17], [42653, 45489, 18], [45489, 47081, 19], [47081, 49209, 20], [49209, 50575, 21], [50575, 51720, 22], [51720, 52825, 23], [52825, 53917, 24], [53917, 54918, 25], [54918, 56922, 26], [56922, 58915, 27], [58915, 61069, 28]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 61069, 0.03162]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
089ffd2dfa8f269e73309b743e4895b83947dc05
|
Derivable Partial Locking for Algebraic Data Types
Boldizsár Németh† and Zoltán Kelemen†
Abstract
Parallelism and concurrency are one of the most actively researched fields in Computer Science. Writing concurrent programs is challenging because of the need for synchronization and solving possible race conditions and deadlocks while avoiding unnecessary waiting and overhead.
The integrity of the program data can be archived by providing locks for its data structures or using concurrent data structures. Partial locking allows threads to lock exactly those parts of the global data they need to read or update.
This article presents a method that helps the implementation of thread-safe programs with Algebraic Data Types [1]. By transforming the data model of the application to thread-safe data structures with a built-in, configurable locking mechanism including partial locking. With this support, the programmer can focus on the business logic of his application when writing the program. As part of this article, we prove that the shared version of the calculation will produce the same result as the original one.
Keywords: concurrency, partial locking, functional programming, Algebraic Data Type (ADT), representation synthesis, type transformation
1 Introduction
Programming parallel algorithms is complicated when the representation of business data is mixed with different synchronization primitives that must be used with their own separate handling functions.
We offer a solution to transform program data into a representation that is thread-safe, in the functional language Haskell. Our goals are to enable the programmer to parallelize a program without having to reimplement parts of the solution, and change how the representation can be used by multiple threads.
The solution is composed of generating the type of the shared representation, transforming values into the representation, generating accessors for the shared representation and functions that act like the constructors of the original data.
Generating constructor functions and references helps the programmer to adapt his program for concurrent execution.
To be able to quickly change how multiple threads can work on the data structure. This paper describes a method to control the way program data is shared. This information is separated from the program logic. This is called the sharing configuration of the program. The configuration declares how the access to the program state is controlled.
Every type can be configured independently to define the protection for instances of the given type in the database (the state of the program). In our solution, the synchronization in shared programs is data-centric. The synchronization primitives are parts of the data structure. This way, the usage of these primitives can be guaranteed.
The execution of a program using our sharing method is done in three phases, as seen on Figure 1.
1. The problem is analyzed and the correct initial state of the program is shared.
2. The problem is solved by a number of threads working on the shared representation.
3. The result state is merged.
If the program runs continuously its state can be inspected any time while it is running, as seen on Figure 2.
1.1 Background
Hawkins et al. described a system [2] where data structures are synthesised from an abstract relational specification and a decomposition. A relational specification is similar to the pure ADT we use and decomposition is similar to our configuration. They applied the theory to concurrency in a subsequent paper [3].
We emphasize controlling the granularity at which the generated parallel computation locks objects. It can have a significant impact on the overall performance. This topic is thoroughly inspected in the context of automatically parallelized programs in [4].
Our method is practice-oriented, and that was inspired by Simon Marlow’s book on the practical side of parallel programming in Haskell [5]. It has excellent chapters on MVars and Threads, and parallel programming using threads.
Other technologies exist for parallelizing algorithms. The Java streams [6] and C# PLINQ [7] can be used to parallelize a collection. Each thread is working on a separate part of the collection. Our goal is to parallelize heterogeneous data structures, not just homogeneous collections, and to enable different threads to access the same data in a thread-safe way.
Combining parallelism with partial locking as a method to enable multiple threads to access different parts of a data structure is a well known and thoroughly researched topic in the field of database design [8].
Data structures in Haskell can be defined by Algebraic Data Types. A simple ADT has the form $\text{T} \text{Ct} \ t_1 \ldots t_n = \text{DCt} \ t_1 \ldots t_n$. $\text{T} \text{Ct}$ is the type constructor, $t_v$ are the type variables, $\text{DCt}$ is the data constructor and $t_i$ are the types of the arguments of the constructor. The type variables can appear inside the types of the arguments. On the right side there can be more constructors, separated by $\text{|}$.
From this point, this paper will assume that the reader has some understanding of concurrency, threads, polymorphism and Algebraic Data Types.
2 Partial locking
Partial locking is a way to share a data structure and enable working threads to lock parts of it without interfering with each other. This can improve the scalability and performance of the whole program, because it reduces the time each thread spends waiting. The resulting data structure still ensures consistent use by multiple threads.
The shared database supports two kinds of locking: read locks and write locks. Reader threads can access the same part of the data concurrently. A thread cannot lock a part of the data for writing if another thread reads or writes the data or some part of it at that time. If the system is configured right, each thread will only lock the data part it needs for the computation.
For example, take a list of some type. If different elements of the list should be operated on independently but elements can only locked by one thread, it can be manipulated by partial locking.
2.1 Producing shared representation of a data type
Lets define the following data types for constructing the shared representation.
Definition 1. Elements of the Skeleton representation
- **Mem\(_n\)** is a simple tuple type for collecting \(n\) members of arbitrary types. We defined a function for constructing them. (In the following definition the left side is the type declaration and the right side is the constructor definition. In this case the type name and the constructor name are the same.)
\[
\text{Mem}_n \ t_1 \ldots \ t_n = \text{Mem}_n \ t_1 \ldots \ t_n \\
\text{mem}_n = \text{Mem}_n
\]
- **Alt\(_n\)** is a union type that can have \(n\) states each having a value of possibly different types. The function \(\text{alt}_{n;i}\) creates the \(i\)th alternative of the possible \(n\).
\[
\text{Alt}_n \ t_1 \ldots \ t_n = \text{Alt}_{n;1} \ t_1 \mid \ldots \mid \text{Alt}_{n;n} \ t_n \\
\text{alt}_{n;i} = \text{Alt}_{n;i}
\]
- **Skeleton** is a composition of the Mem\(_n\) and Alt\(_n\) types.
The Skeleton representation is a subset of ADT types.
2.2 Node types
There are five different node types, each representing a unique way to control accessing the shared representation between threads. As it can be seen on Figure 3, they can be ordered by how much parallelism they allow. Of course, more powerful locking mechanisms have a higher cost in terms of computation and memory overhead.
- **Clean** states that the configured data type must not be converted into a shared representation. **Clean** data cannot be accessed by multiple threads. **Clean** data in itself is immutable, but it can be part of a mutable database. **Clean** representation has no additional costs.
- **Noth** provides no extra protection for the data. It is similar to **Clean**, but the parts of the data configured to **Noth** can have a different configuration.
- **Prim** guarantees mutual exclusion for a part of the data. At any time of the execution, only one thread can have access to a part of the database that is configured to **Prim**. Threads trying to access the protected data will queue up, and access the resource in a first-come-first-served (FCFS) order. **Prim** is relatively low-cost, it is implemented by one synchronization primitive.
• *Multi* allows multiple threads to access the data structure if their actions do not interfere. This applies to multiple reader threads or threads updating different parts of the data. However, it does not guarantee fairness. If a thread would like to gain exclusive access to the data, it may have to wait forever, if threads that can share the data access it frequently. *Multi* is more expensive than *Prim*.
• *Fair* provides a protection that allows non-interfering threads to work simultaneously and guarantees fair FCFS access for all threads. *Fair* nodes use concurrency primitives to implement a shared lock [9], but their cost is higher than that of *Multi* nodes.
It is clear that a good configuration strategy is needed to reach an optimal performance. Common sense dictates that nodes on the upper level of the representation are configured to high-level types and nodes on the lower level (that appear in higher numbers) are configured to types with low cost. Typically predefined types like *Char*, *String* and *Int* are configured to *Clean*.
As it was mentioned, each type can have different configurations. If different instances of the given type should be given different protection levels, the original type should be configured to the neutral node type *Noth* and wrapper data structures can be introduced with a different configuration. There is no default configuration, so each type that can be a part of the shared program state must be configured.
3 Context dependent references
References are first-class functional accessors that enable getting, setting and updating the accessed value in a context. They are implemented as a package on the package repository Hackage [10]. A reference represents a method to access information from a given object. They are interchangeable when their types are
the same. So a reference that accesses some information of type \(A\) (the accessed element) through an object of type \(B\) (the context) can be replaced by another reference for \(A\) through \(B\).
**Definition 2. Reference**
Let \(\text{ref} : s \triangleright a\rightharpoonup a'\) be a reference iff
- \(s, a\) are types. \(s\) is the type of the context and \(a\) is the type of accessed element.
- \(w\) and \(r\) are type constructors and monads [11]. \(w\) is called writer monad, \(r\) is called reader monad.
- \(\text{get ref} : : s \rightarrow r\ a\)
- \(\text{set ref} : : a \rightarrow s \rightarrow w\ s\)
- \(\text{update ref} : :(a \rightarrow w\ a) \rightarrow s \rightarrow w\ s\)
**Definition 3. Composition of references**
Let’s define the composition of two references marked with the \& operator:
\[\& : a \triangleright b \rightharpoonup b' \rightarrow b'' \rightharpoonup c' \rightarrow a \triangleright c'\]
- \(\text{get } (r_1 \& r_2) s \equiv \text{get } r_1 \left(\text{get } r_2 s\right)\)
- \(\text{set } (r_1 \& r_2) x s \equiv \text{update } r_1 \left(\text{set } r_2 x\right) s\)
- \(\text{update } (r_1 \& r_2) f s \equiv \text{update } r_1 \left(\text{update } r_2 f\right) s\)
**Definition 4. Member reference**
Let the reference \(\text{m} : s \triangleright a\rightharpoonup a'\) be the \(j\)th member reference iff
- \(s\) has only one constructor: \(s \equiv \text{CTR } t_1 \ldots t_n\)
- \(\text{get m} \left(\text{CTR } t_1 \ldots t_j \ldots t_n\right) \equiv \text{return } t_j\)
- \(\text{set m } b \left(\text{CTR } t_1 \ldots t_j \ldots t_n\right) \equiv \text{return } \left(\text{CTR } t_1 \ldots b \ldots t_n\right)\)
- \(\text{update m } f \left(\text{CTR } t_1 \ldots t_j \ldots t_n\right) \equiv \text{return } \left(\text{CTR } t_1 \ldots (f t_j) \ldots t_n\right)\)
Member references can have arbitrary \(w\) and \(r\) parameters, but they cannot perform actions except for returning the referenced value.
**Definition 5. Structural reference**
A reference is a structural if it is a member reference or it can be created by a composition (by the \& operator) of member references.
A structural reference accesses some information that is inside the object.
4 Automatic generation of shared references and constructors
Because of the complexity of the shared representation, it would not be a feasible solution to burden the programmer with rewriting his code to use the shared representation. Instead we provided a way to generate constructor functions and references for the shared representation of the data structure, according to the constructors of the original data structure and normal references that can be generated for accessing its fields. The bodies of these references are generated according to the configuration of the types that are part of the representation.
For this reason defining a number of simple references for the node types, accessing the protected data.
The implementation of this automatic generation of references and constructors is using Template Haskell (TH) [12]. TH is a library for generating and inspecting the Abstract Syntax Tree (AST) of a Haskell program. It can only add new elements to the program, but cannot change the already defined parts. Program fragments can be inspected by looking them up using their names with the reify function, but the implementation of functions cannot be seen. To access the implementation, TH can process parts of the AST by receiving them directly as an argument.
We decided to store the configuration as instances of type families, because it can be queried from TH easily.
4.1 Generating references
The generated references are composed of two parts. The first part is a tuple reference for the index of the member accessed by the reference. Tuple references are simple means to access the \( n \)th field of a simple data structure parametrized by the types of it’s members (for example, a pair, triplet, and so on).
The second part is a reference accessing the protected data from a node type. These references will be generated by inspecting the configuration for a given type, and can access the data in a protected, thread-safe way, depending on which kind of protection does the representation offer. These are the _clean, _noth, _prim, _multi and _fair references.
For example, given a normal representation of a log record with a configuration:
```haskell
data Log
= Log { _msg :: String,
_loggingDate :: Time }
type instance Node String = Clean
type instance Node Time = Prim
```
Calling the generator function makeSharedRefs with the quoted name of the Log datatype will create the following references:
```haskell
msg :: Simple IOLens (Shared Log) String
```
4.2 Generating constructors
The generated constructors provide a way to build up larger shared data structures from smaller ones. The alternative method is to build up the data structure in its original representation and have to share it after that.
The shared constructor takes the shared arguments, creates the protection primitives for thread-safety and builds up the shared structure of the data to contain these protection primitives.
For example, let’s inspect what kind of constructor functions would be generated from a list of log messages, if \([\text{Log}]\) (list of Logs) is configured to Multi and Log is configured to Prim. First let’s take a look on the original definition of the list:
\[
data \ [a] = \emptyset \mid a: [a]
\]
The type variable \(a\) will be replaced by \(\text{Log}\). From \(\emptyset\) the \(\%\) operator will be generated, and from (:) the (\%:) operator will be created. Finally the following functions will be generated after calling \texttt{makeSharedCons} on the quoted type expression of \([\text{Log}]\).
\[
(\%[\]) : \text{IO} (\text{Shared} [\text{Log}])
\]
\[
(\%[\]) = \text{return} (\text{Alt2}_1 \text{Mem0})
\]
\[
(\%:) : \text{Shared Log} \rightarrow \text{Shared} [\text{Log}] \rightarrow \text{IO} (\text{Shared} [\text{Log}])
\]
\[
(\%:) x \, xs = \text{do} \ d \gets \text{newPrim} \, x \hspace{1cm} \text{ds} \gets \text{newFair} \, xs \hspace{1cm} \text{return} (\text{Alt2}_2 (\text{Mem2} \, d \, \text{ds}))
\]
It was an implementation challenge to enable the user to create constructor functions for concrete types, because the original constructors belong to the general type. But it was solved by taking the types of the constructors and transforming them by replacing the type variables with their actual types.
5 Formal definition of transforming types and values to their shared representation
Let’s define a transformation of a type in a general way, according to a given type mapping \(C\). We will refer to this transformation with \(\text{Trf}_C\).
**Definition 6. Generic transformations of types**
\(\text{Trf}_C : \text{Raw} \rightarrow \text{ExtendedSkeleton}_C\)
Where \(\text{Raw} is the set of all types, and \text{ExtendedSkeleton}_C \subseteq \text{Raw} is the set of all types that can be constructed using \text{Alt}_n, \text{Mem}_n, applying the type-level function \(C\). The function \(C\) has the type of \(\text{Raw} \rightarrow \text{ExtendedSkeleton}_C\).
If \(T\) is a scalar type, \(\text{Trf}_C \ T = T\)
If \( T \) is not a scalar type, then \( T \) has \( n \) constructors with \( r_1, r_2, \ldots, r_n \) fields:
\[
T = C_{r_1} m_{1;1} \ldots m_{1;r_1} | \ldots | C_{r_n} m_{n;1} \ldots m_{n;r_n}
\]
In this case
\[
\text{Trf}_C T = \text{Alt}^n (\text{Mem}_{r_1} (C m_{1;1}) \ldots (C m_{1;r_1}))
\]
\[\ldots (\text{Mem}_{r_n} (C m_{n;1}) \ldots (C m_{n;r_n}))\]
**Definition 7.** Generic transformation of values
We should also define the corresponding transformation of values, according to a given value-level function \( c \):
\[
\text{trf}_c :: (t \rightarrow \text{Trf}_C t) \text{ where } c \rightarrow \text{Trf}_C s
\]
If \( t \) is a scalar type, \( \text{trf}_c v = v \)
Otherwise if \( t \) has \( n \) different constructors,
\[
\text{trf}_c (C_{r_1} m_{i;1} \ldots m_{i;r_i}) = \text{Alt}^n (\text{mem}_{r_i} (c m_{i;1}) \ldots (c m_{i;r_i}))
\]
**Definition 8.** Mappings for sharing
And then we can define the mappings that give sharing as our transformation:
Let \( \text{conf} \) be a configuration given by the user, declaring how much multi-threading support is needed for the configured types.
\[
\text{Sh}_\text{conf} t = t \quad \text{if } \text{conf } t = \text{Clean}
\]
\[
\text{Sh}_\text{conf} t = \text{Trf}_\text{Sh}_\text{conf} t \quad \text{if } \text{conf } t = \text{Noth}
\]
\[
\text{Sh}_\text{conf} t = \text{Prim } (\text{Trf}_\text{Sh}_\text{conf} t) \quad \text{if } \text{conf } t = \text{Prim}
\]
\[
\text{Sh}_\text{conf} t = \text{Multi } (\text{Trf}_\text{Sh}_\text{conf} t) \quad \text{if } \text{conf } t = \text{Multi}
\]
\[
\text{Sh}_\text{conf} t = \text{Fair } (\text{Trf}_\text{Sh}_\text{conf} t) \quad \text{if } \text{conf } t = \text{Fair}
\]
\[
\text{sh}_\text{conf} :: t \rightarrow \text{Sh}_\text{conf} t
\]
\[
\text{sh}_\text{conf} v = v \quad \text{if } \text{conf } t = \text{Clean}
\]
\[
\text{sh}_\text{conf} v = \text{trf}_\text{sh}_\text{conf} v \quad \text{if } \text{conf } t = \text{Noth}
\]
\[
\text{sh}_\text{conf} v = \text{newPrim } (\text{trf}_\text{sh}_\text{conf} v) \quad \text{if } \text{conf } t = \text{Prim}
\]
\[
\text{sh}_\text{conf} v = \text{newMulti } (\text{trf}_\text{sh}_\text{conf} v) \quad \text{if } \text{conf } t = \text{Multi}
\]
\[
\text{sh}_\text{conf} v = \text{newFair } (\text{trf}_\text{sh}_\text{conf} v) \quad \text{if } \text{conf } t = \text{Fair}
\]
Note: use of IO monad and its binding is omitted for the sake of simplicity.
\[
\text{Share} = \text{Trf}_\text{Sh}_\text{conf}
\]
\[
\text{share} = \text{trf}_\text{sh}_\text{conf}
\]
**6 Proof of the semantic equivalence between the original and the shared version**
**Definition 9.** Homomorphism
The function family \( h \) is a homomorphism from \( A \) to \( B \) for references \( r_1, r_2, \ldots, r_n \) iff
\[
\bullet \ h = (h_s, h_r), \text{ where } h_s : A \rightarrow B \text{ is the mapping of original values and } h_r : A \triangleright \alpha \rightarrow B \triangleright \alpha \text{ is the mapping of references.}
\]
For every reference \( r_i : A \Rightarrow a \) where \( i \in [1, n] \)
\[
\begin{align*}
- & \; \text{get } r_i \equiv \text{get } (h_s, r_i) \circ h_s \\
- & \; h_s \circ \text{set } r_i \; x \equiv \text{set } (h_s, r_i) \; x \circ h_s \\
- & \; h_s \circ \text{update } r_i \; g \equiv \text{update } (h_s, r_i) \; g \circ h_s
\end{align*}
\]
**Theorem 1. Homomorphism and composition**
If \( (h_s, h_r, 1) \) is a homomorphism for a set of references \( R_1 \) and \( (h_s, h_r, 2) \) is a homomorphism for a set of references \( R_2 \) then \( (h_s, h_r) \) \( (h_s = h_{s, 2} \circ h_{s, 1}, h_r = h_{r, 2} \circ h_{r, 1}) \) is a homomorphism for references \( \{ r : r \in R_1 \text{ and } h_{r, 1} \; r \in R_2 \} \)
**Proof.** The proofs for the equations of get, set and update:
\[
\begin{align*}
\text{get} \; (h_s, r, s) & \equiv \text{get} \; ((h_{s, 2} \circ h_{r, 1}) \; r) \; ((h_{s, 2} \circ h_{s, 1}) \; s) \\
\text{set} \; (h_s, r) \; x \; (h_s, s) & \equiv \text{set} \; ((h_{s, 2} \circ h_{r, 1}) \; r) \; x \; ((h_{s, 2} \circ h_{s, 1}) \; s) \\
\text{update} \; (h_s, r) \; f \; (h_s, s) & \equiv \text{update} \; ((h_{s, 2} \circ h_{r, 1}) \; r) \; f \; ((h_{s, 2} \circ h_{s, 1}) \; s)
\end{align*}
\]
These three equations prove that the composition of homomorphisms is also a homomorphism.
**Definition 10. Transformation of references (refShare)**
As already seen in Section 4.1, a structural reference \( \text{ref} : s \Rightarrow a \) can be transformed into a distributed representation.
If the reference ref is a structural reference composed of member references \( m_1, \ldots, m_n \), then \( \text{refShare} (m_1 \& \ldots \& m_n) \equiv \text{refShare} m_1 \& \ldots \& \text{refShare} m_n \).
If ref is a member reference accessing the \( j \)th field of the constructor:
\[
\text{refShare ref} \equiv \_ \& \text{protRef}_c conf \b
\]
\( \text{protRef}_c \) creates the protection primitive generated by \( \text{share} \) and is defined as follows:
\[
\begin{align*}
\text{protRef}_c \text{v} & = _\text{clean} \text{if} \ t = \text{Clean} \\
\text{protRef}_c \text{v} & = _\text{noth} \text{if} \ t = \text{Noth} \\
\text{protRef}_c \text{v} & = _\text{prim} \text{if} \ t = \text{Prim} \\
\text{protRef}_c \text{v} & = _\text{multi} \text{if} \ t = \text{Multi} \\
\text{protRef}_c \text{v} & = _\text{fair} \text{if} \ t = \text{Fair}
\end{align*}
\]
_\text{clean}, _\text{noth}, _\text{prim}, _\text{multi} and _\text{fair} are references accessing the content of the protection primitives \( \text{Clean}, \text{Noth}, \text{Lock}, \text{Multi} \) and \( \text{Fair} \). Let's assume that their implementation is correct, so:
- \( m_j \equiv \text{get protRef}_c \text{conf} (\text{sh}_c \text{conf} m_j) \)
- \( \text{sh}_c \text{conf} x \equiv \text{set protRef}_c \text{conf} x (\text{sh}_c \text{conf} m_j) \)
- \( \text{sh}_c \text{conf} (f \ m_j) \equiv \text{update protRef}_c \text{conf} f (\text{sh}_c \text{conf} m_j) \)
**Theorem 2.** \( (\text{share}, \text{refShare}) \) is a homomorphism for member references.
**Proof.** If \( m \) points to the \( j \)th field of the \( n \) fields of the constructor, the context of the reference must be a type built by a constructor with \( n \) fields: \( \text{Ctr} m_1 \ldots m_j \ldots m_n \)
Needed to prove that each operation keeps the homomorphism:
get \( m \ s \equiv \text{get (refShare m) (share s)} \)
\( \iff \) \( m \ s \equiv \text{(\_j \& \text{protRef}_c \text{conf}) (\text{share s})} \)
\( \iff m_j \equiv \text{get (\_j \& \text{protRef}_c \text{conf}) (\text{Mem}_n (\text{sh}_c \text{conf} m_1) \ldots \ldots (\text{sh}_c \text{conf} m_j) \ldots (\text{sh}_c \text{conf} m_n))} \)
\( \iff m_j \equiv \text{get \_j (\text{get protRef}_c \text{conf} (\text{Mem}_n (\text{sh}_c \text{conf} m_1) \ldots \ldots (\text{sh}_c \text{conf} m_j) \ldots (\text{sh}_c \text{conf} m_n)))} \)
\( \iff m_j \equiv \text{get protRef}_c \text{conf} (\text{sh}_c \text{conf} m_j) \)
share \( (\text{set m x s}) \equiv \text{set (refShare m) x (share s)} \)
Evaluating the right side:
set \( (\text{refShare m}) x \) (share s)
\( \equiv \text{set (\_j \& \text{protRef}_c \text{conf}) x (share s)} \)
\( \equiv \text{set (\_j \& \text{protRef}_c \text{conf}) x (\text{Mem}_n (\text{sh}_c \text{conf} m_1) \ldots \ldots (\text{sh}_c \text{conf} m_j) \ldots (\text{sh}_c \text{conf} m_n))} \)
\( \equiv \text{update \_j (set protRef}_c \text{conf} x (\text{Mem}_n (\text{sh}_c \text{conf} m_1) \ldots \ldots (\text{sh}_c \text{conf} m_j) \ldots (\text{sh}_c \text{conf} m_n))} \)
\( \equiv \text{Mem}_n (\text{sh}_c \text{conf} m_1) \ldots (\text{set protRef}_c \text{conf} x (\text{sh}_c \text{conf} m_j)) \ldots (\text{sh}_c \text{conf} m_n)) \)
\( \equiv \text{Mem}_n (\text{sh}_c \text{conf} m_1) \ldots (\text{sh}_c x) \ldots (\text{Mem}_n (\text{sh}_c \text{conf} m_n)) \)
Evaluating the left side:
share (set m x s)
≡ share (set m x (Ctr m₁ ... m_j ... m_n))
≡ share (Ctr m₁ ... x ... m_n)
≡ Memₙ (sh_conf m₁) ... (sh_conf x) ... (sh_conf mₙ)
share (update m f s)
≡ share (update (refShare m) f (share s))
Evaluating the right side:
update (refShare m) f (share s)
≡ update (_j & protRef f) (share s)
≡ update (_j & protRef f) (Memₙ (sh_conf m₁) ... (sh_conf mₙ))
≡ update _j (update protRef f) (Memₙ (sh_conf m₁) ... (sh_conf mₙ))
≡ Memₙ (sh_conf m₁) ... (update protRef f) (sh_conf mₙ))
≡ Memₙ (sh_conf m₁) ... (sh_conf (f m_j)) ... (sh_conf mₙ))
Evaluating the left side:
share (update m f s)
≡ share (update m x (Ctr m₁ ... m_j ... m_n))
≡ share (Ctr m₁ ... (f m_j) ... m_n)
≡ Memₙ (sh_conf m₁) ... (sh_conf (f m_j)) ... (sh_conf mₙ)
Theorem 3. (share, refShare) is a homomorphism for structural references
Proof. If the reference r is a structural reference, then r is a composition of member references: r ≡ m₁ & ... & mₙ.
From Theorem 1 it is clear that the composition of two homomorphisms will be a homomorphism for references. From Theorem 2 is known that this property holds for member references. This is generalizable by using the fact that the homomorph images (transformed by refShare) of structural references will also be structural references. Thanks to that, this is generalizable Theorem 2 to the composition of n member references.
Definition 11. Translatable function
A translatable function is a function f of type A → A in which only references are used to access elements of type A.
A translatable function is nearly polymorphic in its argument type because only the use of references constrain the input and output types. This is necessary to be able to change the representation to another form.
Definition 12. Operating reference
Let call the subexpression s of the body of a function of type A → A operating references iff
• \( s \) is a reference.
• \( s \) has the context type of \( A \).
The operating references have to be changed when the representation of the transformed element is changed.
**Definition 13.** Homomorphic translation
\( h \) is the homomorphic translation of the function \( f \) of type \( A \rightarrow A \) iff
• \( h = (h_s, h_r) \) is a homomorphism from \( A \) to \( B \) for all operating references of \( f \). See definitions 9 and 12.
• \( f \) is a translatable function
• An operating reference \( r \) in \( f \) is replaced by \((h_r, r)\) inside the translated function.
It is trivial to prove that the translated function will have the type \( B \rightarrow B \). The homomorphic translation is done by the programmer using the automatically generated constructs we developed.
**Theorem 4.** The homomorphic translation of a function produces the same result.

The result of applying the homomorphic translation of a function to a shared value is the same as applying the original function and sharing the result afterwards:
\[
F_h (\lambda x \rightarrow e) \circ h_s \equiv h_s \circ (\lambda x \rightarrow e).
\]
If \( h_s \) is invertible (this is true in most cases, for example the distribution mapping) also \( h_s^{-1} \circ F_h (\lambda x \rightarrow e) \circ h_s \equiv (\lambda x \rightarrow e) \).
**Proof.** The proof can be easily constructed from the previous theorems.
1. Because $f$ is a translatable function, expressions of type $A$ are accessed by references that can be translated.
2. These references could be used with get, set or update, and can be composed with $\&$.
3. Because the values and references are translated by a homomorphism, the calls of get function evaluates to the same result, while set and update functions return the homomorphic image of the original result.
4. Subexpressions of $e$ that are not operating references remain unchanged.
5. By structural recursion, the result will be the homomorphic image of the original result.
Theorem 4 does not take shared constructors into account. The usage of shared constructors is more straightforward because there is a more direct equivalence between the original and shared constructors. So the extension of the theorem to include shared constructors is left to the reader.
7 Case study
Code listings of the case study can be found in the appendix.
We created a case study for our method. We implemented a small application that consists of a number of worker threads, producing log messages and sending them through a channel to a logger thread, or querying log messages, that are sent back on separate channels.
This case study application is implemented using our library, so the configuration that controls the granularity of the parallelization is separated from the representation and the business logic.
We use a simple database representation shown on Listing 1 for the case study. The main loop of the original body is on Listing 2. For the original representation, Feature of the reference package is used to automatically generate structural references as it can be seen on Listing 5.
For the shared version of the case study two configurations had been written (one of them is shown on Listing 4) to enable multiple threads to work on the same database simultaneously. We had to wrap the database into a simple wrapper data type and an IORef [13]. The simple wrapper is needed to let the configuration of the outermost database type. The references for this two data types became the prefixes of our structural references, as it can be seen in the modified main loop on Listing 3. The code did not have to change in any other way. In the implementation we used Haskell type families [14] for configuration.
To measure the overhead caused by the generic definition of the program we manually implemented the same thread-safe logging application by using the concurrency primitives manually. To measure the net gain on thread-safe representation we also implemented the case study with simple central locking.
8 Results
In this paper we demonstrated a method to create a thread-safe representation of an Algebraic Data Type. We inspected how types and values can be converted to this representation. We designed how can the transformation can be controlled by a configuration, and how distributed references and constructor functions can be generated.
We formalized the general concept of homomorphism for references and used it to prove that the shared computation on the shared representation yields the same result.
A simple logging application was implemented as a case study. It had 2 different implementations, one with using concurrency primitives for thread-safety (Manual locking) and the other using our library to generate thread-safe representation (Partial locking). The second approach lets the user to configure the representation so we measured two versions of the case study. One uses Fair nodes for higher levels of the data structure (#1), and the other uses the faster Multi nodes (#2).
The abstraction level of the alternative implementations are measured by the number of effective lines of code, shown on Table 1, and the performance of the implementations is measured by the number of transitions completed in a 2 second interval, seen on Figure 5. Each implementation was tested with different number of read and write operations.
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Manual locking</td>
<td>52</td>
<td>57</td>
<td>0</td>
<td>109</td>
</tr>
<tr>
<td>Partial locking</td>
<td>33</td>
<td>54</td>
<td>9</td>
<td>96</td>
</tr>
</tbody>
</table>
On Table 1 it is easy to see that partial locking can be implemented in fewer lines than manual locking. However, the relatively low difference is more important, because it is present in the innermost loops of the application that only contain a few lines. As the manual locking example was implemented we needed to write the functions for handling concurrent lists manually.
The measurements were done on a Lenovo T440p laptop, that has an Intel Core i7™ processor with 16GB of DDR3 RAM. Each measurement was performed 20 times and the results was averaged.
On Figure 5 we can see that all solution that using primitive concurrency operators (Manual locking) does not increase performance more than 25%. Manual
locking is implemented by using the concurrency primitives of GHC. Using it results a rather complicated and hard-to-maintain code for representation and usage. The better performance of the edge cases is explained by Haskell’s lazy evaluation. When the application mostly reads data and never writes, the reads will be much simpler and can be performed quicker than in a balanced situation.
The results show that the library described in this paper gives a higher level of abstraction than the concurrency primitives of GHC, its performance is close to the performance of using the primitives.
8.1 Further work
Our method can be extended by allowing the user to transform bodies of arbitrary functions into a shared format, not only constructors. We would also like to thoroughly investigate properties of references. As part of this we will search for a solution to manage deadlocks and transactions. We intend to consider the correctness of this method when it is generalized to arbitrary functions.
Currently our implementation is based on the GHC generics library [15]. This stops us from using system specific types in shared data types and may cause some performance problems. We would like to experiment with alternatives to the generics library.
References
Appendix: sample codes from the case study
data LogDB = LogDB
{ _criticalErrors :: LogList,
_errors :: LogList,
_debugInfos :: LogList,
_startDate :: Time,
_lastLogDate :: Time }
data Log = Log
{ _loggerThread :: String,
_msg :: String,
_loggingDate :: Time }
data LogList = LogList
{ _logListData :: [Log],
_logListNum :: Size }
data Size = Size
{ _sizeInt :: Int }
data Time = Time
{ _year :: Int,
_month :: Int,
_day :: Int,
_hour :: Int,
_minute :: Int,
_sec :: Int }
Listing 1: Representation of the case study
case q of
LogThat log →
do time ← getTime
(lastLogDate != time
>> (debugInfos & logListData != (log %:))
>> (debugInfos & logListNum & sizeInt !- (1))
logDB
LogQuery ch →
do n ← logDB `!` debugInfos & logListNum & sizeInt
if n > 0 then do
i ← evalRandIO (fromList (map (,1) [0..n-1]))
logDB `?`! debugInfos
& logListData & distrLogElem (fromIntegral i) & msg
>>= putMVar ch
else putMVar ch Nothing
Listing 2: Original main loop of the case study
case q of
LogThat log →
do time ← getTime
(ioref & wrappedDB & lastLogDate != time
>>= (ioref & wrappedDB & debugInfos & logListData !" (log %:))
>>= (ioref & wrappedDB & debugInfos & logListNum & sizeInt !- (+1)))
logDB
LogQuery ch →
do n ← logDB ^! ioref & wrappedDB & debugInfos & logListNum & sizeInt
if n > 0 then do
i ← evalRandIO (fromList (map (,1) [0..n-1]))
logDB ^?! ioref & wrappedDB & debugInfos
& logListData & distrLogElem (fromIntegral i) & msg
>>= putMVar ch
else putMVar ch Nothing
Listing 3: Main loop of the case study’s logger
type instance Node LogDB = Fair
type instance Node LogList = Fair
type instance Node [Log] = Fair
Listing 4: Configuration of the case study representation
makeReferences "'Time
makeReferences "'Log
makeReferences "'Size
makeReferences "'LogList
makeReferences "'LogDB
Listing 5: Generating the original references
makeSharedRefs "'Time
makeSharedRefs "'Log
makeSharedRefs "'LogList
makeSharedRefs "'Size
makeSharedRefs "'LogDB
makeSharedRefs "'LogDBWrapper
Listing 6: Generating shared references and constructors
|
{"Source-Url": "http://www.inf.u-szeged.hu/actacybernetica/edb/vol22n1/pdf/Nemeth_2015_ActaCybernetica.pdf", "len_cl100k_base": 10103, "olmocr-version": "0.1.48", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 53601, "total-output-tokens": 12071, "length": "2e13", "weborganizer": {"__label__adult": 0.0003414154052734375, "__label__art_design": 0.0002574920654296875, "__label__crime_law": 0.0003204345703125, "__label__education_jobs": 0.0004346370697021485, "__label__entertainment": 5.179643630981445e-05, "__label__fashion_beauty": 0.00013339519500732422, "__label__finance_business": 0.0001577138900756836, "__label__food_dining": 0.0003604888916015625, "__label__games": 0.0005125999450683594, "__label__hardware": 0.0007610321044921875, "__label__health": 0.0005140304565429688, "__label__history": 0.00021159648895263672, "__label__home_hobbies": 9.012222290039062e-05, "__label__industrial": 0.0003895759582519531, "__label__literature": 0.0001908540725708008, "__label__politics": 0.00026106834411621094, "__label__religion": 0.0004925727844238281, "__label__science_tech": 0.01202392578125, "__label__social_life": 7.671117782592773e-05, "__label__software": 0.00347900390625, "__label__software_dev": 0.97802734375, "__label__sports_fitness": 0.0003421306610107422, "__label__transportation": 0.0005540847778320312, "__label__travel": 0.00021708011627197263}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 39637, 0.01061]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 39637, 0.49678]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 39637, 0.80954]], "google_gemma-3-12b-it_contains_pii": [[0, 2037, false], [2037, 3253, null], [3253, 6212, null], [6212, 8484, null], [8484, 10317, null], [10317, 12548, null], [12548, 15065, null], [15065, 17579, null], [17579, 20600, null], [20600, 22131, null], [22131, 25538, null], [25538, 27405, null], [27405, 28879, null], [28879, 31214, null], [31214, 33887, null], [33887, 35146, null], [35146, 37234, null], [37234, 37416, null], [37416, 38478, null], [38478, 39637, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2037, true], [2037, 3253, null], [3253, 6212, null], [6212, 8484, null], [8484, 10317, null], [10317, 12548, null], [12548, 15065, null], [15065, 17579, null], [17579, 20600, null], [20600, 22131, null], [22131, 25538, null], [25538, 27405, null], [27405, 28879, null], [28879, 31214, null], [31214, 33887, null], [33887, 35146, null], [35146, 37234, null], [37234, 37416, null], [37416, 38478, null], [38478, 39637, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 39637, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 39637, null]], "pdf_page_numbers": [[0, 2037, 1], [2037, 3253, 2], [3253, 6212, 3], [6212, 8484, 4], [8484, 10317, 5], [10317, 12548, 6], [12548, 15065, 7], [15065, 17579, 8], [17579, 20600, 9], [20600, 22131, 10], [22131, 25538, 11], [25538, 27405, 12], [27405, 28879, 13], [28879, 31214, 14], [31214, 33887, 15], [33887, 35146, 16], [35146, 37234, 17], [37234, 37416, 18], [37416, 38478, 19], [38478, 39637, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 39637, 0.00964]]}
|
olmocr_science_pdfs
|
2024-11-24
|
2024-11-24
|
529a92cdc8823bf7083bd614fa5c60190d8019c0
|
Process-related user interaction logs: State of the art, reference model, and object-centric implementation
Luka Abb, Jana-Rebecca Rehse
University of Mannheim, Mannheim, Germany
A B S T R A C T
User interaction (UI) logs are high-resolution event logs that record low-level activities performed by a user during the execution of a task in an information system. Each event in such a log represents an interaction between the user and the interface, such as clicking a button, ticking a checkbox, or typing into a text field. UI logs are used in many different application contexts for purposes such as usability analysis, task mining, or robotic process automation (RPA). However, UI logs suffer from a lack of standardization. Each research study and processing tool relies on a different conceptualization and implementation of the elements and attributes of user interactions. This exacerbates or even prohibits the integration of UI logs from different sources or the combination of UI data collection tools with downstream analytics or automation solutions. In this paper, our objective is to address this issue and facilitate the exchange and analysis of UI logs in research and practice. Therefore, we first review process-related UI logs in scientific publications and industry tools to determine commonalities and differences between them. Based on our findings, we propose a universally applicable reference model of UI logs, which includes all core attributes but remains flexible regarding the scope, level of abstraction, and case notion. Finally, we provide exemplary implementations of the reference model in XES and OCED.
1. Introduction
User interaction (UI) logs are high-resolution event logs that record low-level, manual activities performed by a user during the execution of a task in an information system [1]. Each event in such UI log represents a single interaction between the user and the graphical user interface (GUI) of a software application. Examples for such events include clicking a button, typing into a text field, swiping left on a touchscreen, ticking a checkbox, or selecting an item from a dropdown [2]. UI logs provide a data-driven, non-intrusive, and long-term approach to studying the behavior of software users [3]. Therefore, they are used in multiple recent research streams, for example to analyze usage patterns in software applications [4–6], to identify candidate routines for robotic process automation (RPA) [2,7,8], or to derive RPA automation and test scripts [9,10]. Furthermore, software vendors such as Celonis and UiPath provide solutions designed to capture and analyze UI data, facilitating the examination and automation of specific task executions within a process [11].
When dealing with multiple UI logs from different sources, researchers and practitioners will eventually find that these logs differ substantially from one another. This inherent lack of standardization is, among other things, caused by the diverse applications of UI logs, as sketched above. Data collected for a specific research study tends to be narrowly scoped and customized to fit the proposed analysis technique or automation approach. This leads to considerable variation regarding the number, type, and granularity of recorded events and corresponding attributes. Even when researchers record the same attributes at a similar level of detail, there is no common definition of UI log attributes to which they can adhere. Instead, they often rely on ad-hoc conceptualizations of elementary notions like activities and UI components. This lack of standardization also occurs in industry. Each vendor has developed their own UI log structure tailored to the capabilities of their recording software [12,13]. In addition, some vendors do not rely on commonly used log formats like CSV or XES, but generate UI logs in proprietary data formats.
The lack of standardization in UI log structure and data format causes multiple problems. First, it complicates the integration of UI logs from different sources [2,14], which might be required for purposes like cross-application automation or usability analysis. Second, it poses a challenge for the interoperability of data collection and downstream processing tools: Logs recorded by a specific data collection tool are typically only compatible with the corresponding analytics or automation methods. Combining data collection and processing tools
Finally, we conclude the paper with a discussion in Section 8.
2. Background and related work
In this section, we provide the necessary background information and report on related work on event logs and exchange formats (Section 2.1), UI logs and their analysis (Section 2.2), as well as the use of UI logs in other domains (Section 2.3).
2.1. Event logs and exchange formats
The goal of process mining is to extract information about business processes through the analysis of event logs, i.e., collections of events recorded in an information system [20]. An event denotes the execution of a particular activity in a process, which is represented by the label of the activity (e.g., “create invoice”). In addition, events can have other attributes, such as the executing resource. In a conventional event log, these events are grouped into different cases, each corresponding to one process instance. A case then refers to a trace, i.e., a sequence of events that occurred during the execution of the process instance. Cases can also include additional attributes, such as the size of an order in an order-to-cash process.
To facilitate the exchange of event data between different information systems, the business process management (BPM) community has developed standardized interchange formats that define the structure, contents, and semantics of event logs. The current main format is XES, which was introduced in 2010 to replace the older MXML format [21]. In 2016, XES was accepted as the official IEEE standard for event data [22]. An updated version was released in 2023 [23].
In the XES standard, an event log consists of a three-level hierarchy of log, trace, and event objects. The format is designed to be highly generic, with a minimal set of explicitly defined attributes on each of the three levels. Additional attributes, with a commonly understood semantic meaning, can be introduced by XES extensions. For example, the `concept` extension introduces the `name` attribute, which stores names for event logs, traces, and events.
Although XES is an IEEE standard, which is widely used in research and is supported by many process mining tools, it has major limitations. One of them is the assumption that there always exists a single case identifier that can be used to group events into clearly separated process instances. Events captured in real-life information systems often relate to multiple entities, such as orders, items, or resources [16]. Thus, there are multiple potential case identifiers and accordingly multiple perspectives that one can take on a single collection of events. To store this process data in a XES log, it needs to be flattened by selecting one of the case identifier candidates. This flattening can lead to quality issues like divergence and convergence in the log [16,24], which, for example, distort the results of automated process discovery techniques [25].
To overcome these limitations in the XES standard, the community is currently focusing on object centrality as a new paradigm for conceptualizing and capturing event data [26]. Object-centric event logs do not require a single case notion. Instead, they explicitly capture the entities (or objects) that an event relates to [16]. To eventually provide an object-centric alternative to XES, a working group within the IEEE Taskforce on Process Mining is currently developing conceptual foundations for Object-Centric Event Data (OCED) [26]. A preliminary OCED meta-model, shown in Fig. 1, was circulated in the community and presented at the International Conference on Process Mining’s XES symposium in November 2022 [15]. Initial reference implementations [27,28] were presented the following year at the same conference. There is not yet a consensus about how exactly to implement the meta-model and which of its parts should be included in an eventual OCED standard. As a result, the reference implementations share core concepts, but differ slightly in terms of their operationalization.
In the OCED format, an event log is a collection of `events` and `objects`, which can either be physical objects, like a product, or more abstract entities, like a task or department. Both events and objects are labeled...
with a type and can have additional attributes. Object relations define how objects are related to each other. The interactions between events and objects, and their attributes and relations can be further described through qualifiers.
2.2. UI logs and user behavior mining
UI logs are a particular type of event log, in which events represent low-level interactions between a user of a software system and the system’s GUI. For a given software system, there are two general approaches for recording UI logs. External logging relies on dedicated logging tools, which combine screen capture and OCR technology with a hardware input recorder [9]. It is common in industry tools. Internal logging draws on capabilities within the software applications, which allows recording any available internal information, but requires access to the applications’ source code [29]. Hence, it is more prevalent in research tools. As a hybrid between external and internal logging, application-specific plug-ins present another alternative. These plug-ins allow recording any available internal information, but can be used without source code access.
UI logs capture high-resolution data on interactions between users and software systems, which can be analyzed to generate insights into how users behave while they are engaged with an application [1,30]. The goal of such an analysis is to gain knowledge about and eventually improve the interactions between humans and IT systems. We refer to this analysis of UI logs as user behavior mining (UBM). UBM can serve different purposes, such as identifying different software usage patterns [31] or increasing employee efficiency through improving the usability of a UI [32]. As such, it is closely related to several current research topics in the BPM domain.
By relating lower-level UI logs with higher-level event logs, UBM can enhance traditional process mining by providing insights into how individual process steps are executed. Process-related event data, captured for example from ERP systems like SAP or Oracle, typically records what was done in a process, such as the creation of an order. However, they do not specify how employees actually conducted these tasks. This information can be provided by recording and analyzing a corresponding UI log. This analysis of low-level process task executions is referred to as task mining [20] or desktop activity mining [33]. It can give organizations more specific insights into their processes than traditional process mining alone. It can also help software vendors to improve their products, for example, by identifying common usability issues.
Task-specific user interactions captured in a UI logs can serve as the basis for automating these tasks and the processes they belong to. For this purpose, software robots are constructed to mimic the recorded human behavior when interacting with the UI. This approach to automation is called robotic process automation (RPA) [29] and has lately received considerable attention in research and practice. Within RPA, UI logs are used for robotic process mining [2], which for example encompasses the identification of suitable tasks for automation or the segmentation of unstructured UI logs [34]. UI logs can also be used directly as an input to automation scripts, which obviates the necessity to manually configure a bot’s routine.
2.3. UI logs in other domains
In addition to the research areas mentioned above, logs of interactions between users and software systems have been used as a source of data-driven insights into user behavior in several other domains. A rather prominent one is web usage mining [35], i.e., the analysis of clickstream user data recorded during interactions with websites. Web usage mining is often process-agnostic, meaning that it is not aware of the logic of a potential underlying (business) process. Instead, its main purpose is to improve the usability of websites, for example, by adapting their content and structure to users’ browsing behavior [36, 37]. The primary data source for web usage mining are server logs that are generated in a standardized logging format like the Extended Log Format [38] and have a fixed set of attributes. These attributes include the URL of the current and previous page request, the resource accessed, timestamps, identifying data like the user’s IP address, and technical data about the user’s web browser and operating system. The data recorded in these logs is limited to information transmitted from the client to the server, although it can afterwards be complemented with data from a secondary source, e.g., demographic information from a user database.
Other fields that rely on UI logs for investigating user behavior are human–computer-interaction [39–41], information retrieval [42,43], software usability [44,45], and visualization [46,47]. Logs in these domains can take various forms, but they generally record user interactions at a much lower level of detail than the process-related UI logs that are the focus of this paper.
3. Literature review
The first goal of this paper is to review the state of the art of process-related UI logs. The findings of this review will serve as the basis for designing the reference data model, which should subsume and integrate the commonalities between existing logs, but stay flexible with regard to their differences. In this section, we review UI logs from scientific literature to identify these commonalities and differences.
3.1. Research method
For identifying UI logs from scientific literature, we conducted a structured literature review [48] in three stages: database search, targeted search in conference proceedings, and forward–backward search. An overview of the number of publications found in each stage is shown in Fig. 2.
**Database search.** As we expected the relevant UI logs to mainly occur in technical papers, we selected Springer Link, ACM Digital Library, and IEEE Xplore as databases. As search terms, we used the word “log”, combined with multiple other terms:
1. “user interact*” and “user interface”, as typical terms used to denote UI logs,
2. “task mining” and “desktop activity mining”, as common terms for high-resolution process mining, and
3. “robotic process automation” and “robotic process mining”, as important application fields of UI logs in a process context.
Because we want to focus on the current state of the art, we limited our search to papers that were written in English and published after 2015. To ensure a certain quality, we considered only peer-reviewed journal articles and conference papers. Other than these filter criteria, we applied the default search parameters of the respective database.
This keyword search returned a set of initial results. The relevance of the papers in this set was assessed based on their title and abstract. Note that some search terms returned an excessive number of initial results; in this case, we only looked at the first 100 papers, sorting by relevance in the search interface of the respective database. This initial relevance assessment yielded a second set of potentially relevant papers. To ascertain the relevance of those papers, we scanned their full text for passages on UI logs or recording approaches for them. Papers were considered as relevant if (1) they had some relation to the Business Process Management domain and (2) they either contained a concrete UI log or described the UI log collection process in enough detail to infer the captured attributes. We excluded papers that utilize UI logs from industry tools, because these are covered in the industry review in Section 4. In the end, 14 publications were found to be relevant. The results of this initial review are summarized in Table 1.
A list of all papers that we deemed potentially relevant is included in our Gitlab repository.
---
Fig. 2. The number of publications found in different stages of the literature review.

Table 1
<table>
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>Database search</td>
<td>100+</td>
<td>100+</td>
<td>100+</td>
<td></td>
</tr>
<tr>
<td>Selected</td>
<td>11</td>
<td>2</td>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td>Final</td>
<td>14</td>
<td>2</td>
<td>27</td>
<td></td>
</tr>
</tbody>
</table>
---
**Proceedings search.** Next, to supplement the database search, we searched for relevant papers directly in the proceedings of the two main process science conferences: the International Conference on Business Process Management (BPM) and the International Conference on Process Mining (ICPM). Both searches included the proceedings of workshops and associated forums, in addition to the conference proceedings themselves. In this search, we also applied the previously described exclusion and relevance criteria. This yielded another two results, one for BPM [55] and ICPM [56] respectively.
**Forward–backward search.** Finally, we performed a forward–backward-search on the 16 previously found papers to also cover publications that our search terms might have missed or that were published in other venues. Therefore, we checked the reference section of each paper (backward) and their respective citations using Google Scholar (forward). If any of those papers appeared relevant based on title and abstract, it was deemed potentially relevant and the full text was analyzed according to the relevance criteria listed above. This forward–backward search returned another 10 relevant publications.
Although we did not explicitly search for web usage mining logs, our search returned papers about server-side and also client-side web usage mining (recording web activities by adding tracking software to a browser), but none of these met the above-listed criteria. In our review, we therefore only included one exemplary clickstream log from a process mining context: the BPI Challenge 2016 [57], in which
the Dutch Employee Insurance Agency recorded eight months of user activities on their website.
Our final result was hence a set of 27 relevant publications. Compared to the original conference paper, this review yielded seven additional publications [50–56].
3.2. Results
The 27 relevant publications were then analyzed to identify commonalities and differences between them. A considerable number of publications covered the same use case and data collection approach and were therefore treated as duplicates, resulting in 13 unique approaches. The majority of papers (19) cover RPA or robotic process mining [27–12,29,34,49–53,55,58,59,61,62]. Four publications [4–6, 60] focus on software process mining [63]. The remaining four are general approaches for the analysis of user interactions in broader applications [33,54,56,57].
3.2.1. Commonalities
Although the reviewed UI logs were fairly heterogeneous, we found a set of six core attributes that were recorded in more than half of them.
1. An action type that describes the action a user takes. This is recorded in almost all UI logs. Actions are most often divided into mouse and keyboard inputs, but some logs further distinguish between different mouse buttons and between string inputs and hotkeys. There are three notable exceptions that do not distinguish action types: the BPIC 2016 clickstream log [57], Urabe et al. [8], and Beerepoot et al. [56].
2. The atomic target UI element that the user action is executed on, for example, a button or a text field. This attribute is also recorded in all but three UI logs. One exception is the approach by Dev et al. [4], who only record the usage of specific tools (e.g., Crop) in a graphics editor application. Jimenez-Ramirez et al. [10,29] record click coordinates and screenshots, but only use them to match similar user actions and do not map them to target elements. Finally, Beerepoot et al. [56] record user interactions at a higher abstraction level than the other approaches, focusing on application windows rather than singular UI elements.
3. One or multiple attributes that contain further information about the location of the target element in the user interface hierarchy of an application. An example is an Excel cell as the target element which is embedded in a worksheet (hierarchy level 1) that belongs to a workbook (hierarchy level 2) [12]. About half of the UI logs in our literature review include attributes that specify the location of the target element in the UI hierarchy.
4. The software application that the user is interacting with, e.g., a web browser, ERP system, office application, etc. This attribute is always recorded when a study tracks user actions across more than one application. Some approaches, however, only record capture actions in a single application and therefore do not record it (marked as “single” in Table 2).
5. The input value that the user writes into a text field. Input values are included in about half of the publications.
6. A timestamp that makes it possible to establish an event order. This is recorded in all publications.
Table 2 indicates which of the 13 approaches include which attributes (*). We can conclude that the core set of attributes is fairly standardized among UI logs and should therefore be contained in a reference data model. Next, we focus on the differences between the individual logs.
3.2.2. Differences
Most authors characterize user interactions through an action type, i.e., what the user does, and a target element, i.e., where they do it. However, the set of possible values for the action type, and hence the level of detail at which actions are recorded, differs considerably. For example, Agostinelli et al. [9] record aggregated action types abstracted from raw hardware input (e.g., clickButton and clickTextField), whereas Jimenez-Ramirez et al. [29] make the low-level differentiation between left, right, and middle mouse clicks. Which other attributes are included in a UI log also differs between approaches: whereas timestamps and the application in focus (where applicable) are recorded in all logs, only about half of them include input values and information on the location of the target element within the application’s UI hierarchy. Examples for other, less common attributes that are only recorded in a few approaches include the current value of a text field [11,12,59], user IDs [8,11,12,60], other resources involved [6,57], and associations to higher-level process steps [33,61]. An illustration of two UI logs with different attribute sets is shown in Fig. 3.
Another interesting finding was that most of the reviewed UI logs are initially unlabeled, i.e., they do not have a concrete case notion [64]. In some publications, events in unlabeled logs are later grouped into cases based on different attributes. These attributes include external session IDs created automatically by a system [57] or manually by users [5,9,12], user IDs [60], or case IDs from associated higher-level event logs [61].
To conclude, our review of UI logs from scientific literature has found that virtually all existing UI logs rely on a set of core components that represent user interactions. At the same time, the logs differ considerably with regard to the level of detail, attribute scope, and case notion. In the next section, we study whether these findings also apply to UI logs from industry solutions.
4. Review of industry solutions
To ensure broad applicability of our reference data model, we also review the state of the art of process-related UI logs in industry to identify the commonalities and differences between them and see how they relate to the scientific logs. This additional review is presented in this section. Because those approaches are core to the industry solutions’ functionality and business secrets, the available material
for this review may be less specific than scientific papers. Therefore, we conduct the industry review in this section as an addition to the literature review, meant to confirm and complement the established findings.
4.1. Research method
An initial analysis indicated that RPA tools are presently the only industry solutions that collect UI logs on a large scale. Some vendors also advertise task mining capabilities, but their primary focus is on recording UI logs for the automation of routines. Because the RPA market is highly fractured and fast-moving, we could not conduct a complete review. Instead, we opted to analyze a sample of companies that can be seen as representative for the market. Therefore, we selected the companies that the 2022 Gartner Magic Quadrant RPA report attributes with a “high ability to execute” and/or a “high completeness of vision”: UiPath, Automation Anywhere, Microsoft Power Automate, Blue Prism, NICE, WorkFusion, Pegasystems, Appian, SAP Process Automation, and Salesforce MuleSoft. We have selected those tools because, based on their ranking by Gartner, they evidently have achieved a certain level of conceptual and/or technical maturity. We therefore assumed that the underlying data models were sufficiently mature, comprehensive, and stable to warrant their consideration in a state-of-the-art analysis and, eventually, their inclusion in the design of a universally applicable reference model. In addition to those tools, we also included Celonis Task Mining, which is the only major product that uses UI logs primarily for low-level process mining.
4.2. Results
Based on the collected materials, the remaining ten tools were analyzed to identify commonalities and differences between them and the scientific logs from Section 3. In doing so, we used the results from the previous section as a guideline.
4.2.1. Commonalities
For each industry solution, we analyzed whether it also records the six core attributes found in the literature review. The results are summarized in Table 3.

Fig. 3. Excerpts of two UI logs from scientific publications [50,62] with different attribute sets.
The recording process. After collecting the material, we had to exclude Pegasystems from our list because we could not obtain sufficient information on the functionalities of their recording software.
4.2. Results
Based on the collected materials, the remaining ten tools were analyzed to identify commonalities and differences between them and the scientific logs from Section 3. In doing so, we used the results from the previous section as a guideline.
4.2.1. Commonalities
For each industry solution, we analyzed whether it also records the six core attributes found in the literature review. The results are summarized in Table 3.
All reviewed tools record action types, target elements, input values, applications, and timestamps. Similar to what we found in the literature review, the recordable action types differ between tools, and in addition, separate tools often use different names for the same user action. These two aspects are illustrated in the comparison of mouse-related action types in Automation Anywhere and Celonis Task Mining in Table 4: both solutions support recording (single) left, right, and double clicks, but use slightly different names. Automation Anywhere does not support the recording of mouse wheel scrolling actions, whereas Celonis Task Mining does. Automation Anywhere’s recorder also features an additional generic Click action type, which is intended to make recording more reliable through redundancy.
Additionally, the action types have considerable variation in abstraction level, even within a single tool. One tool where this phenomenon occurs is Microsoft Power Automate, as shown in Fig. 4. Among the four recorded activities, the first and fourth action types are low-level hardware inputs (“click” and “populate”), enriched with information about the action’s target (“element in window” and “text field in webpage”). The second and third, however, are abstracted from a series of such inputs and refer to higher-level activities, such as “launch web browser”.

Fig. 4. Excerpts of two UI logs from scientific publications [50,62] with different attribute sets.
Table 3
UI log attributes as found in the industry review.
<table>
<thead>
<tr>
<th>Tool</th>
<th>Action type</th>
<th>Target element</th>
<th>UI hierarchy</th>
<th>Application</th>
<th>Input value</th>
<th>Time-stamp</th>
</tr>
</thead>
<tbody>
<tr>
<td>UiPath</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>MS Power Automate</td>
<td>•</td>
<td>•</td>
<td>•</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>Automation Anywhere</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>Celonis</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>SS&C Blue Prism</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>WorkFusion</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>SAP Process Automation</td>
<td>•</td>
<td>•</td>
<td>•</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>NICE</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>Appian</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
<tr>
<td>MuleSoft</td>
<td>•</td>
<td>•</td>
<td>screenshots</td>
<td>•</td>
<td>•</td>
<td>•</td>
</tr>
</tbody>
</table>
Table 4
Mouse-related action types in Automation Anywhere (Universal Recorder) and Celonis Task Mining.
<table>
<thead>
<tr>
<th>Automation Anywhere</th>
<th>Celonis Task Mining</th>
</tr>
</thead>
<tbody>
<tr>
<td>Click</td>
<td>Left-click</td>
</tr>
<tr>
<td>Right Click</td>
<td>Right-click</td>
</tr>
<tr>
<td>Mouse wheel</td>
<td>Mouse wheel (up)</td>
</tr>
<tr>
<td>Mouse wheel (down)</td>
<td></td>
</tr>
</tbody>
</table>
Fig. 4. Examples of recorded actions with varying abstraction levels in Microsoft Power Automate.
4.2.2. Differences
We also examined whether, in comparison to the scientific logs, the industry solutions systematically record any additional attributes, but we did not find any. However, we did find a significant difference between industry logs and scientific logs in how they capture information on the location of elements within the UI hierarchy. In research, this information is explicitly recorded in UI log attributes. Most industry tools instead store hierarchy information as screenshots outside of the log. Some tools also use the UI hierarchy to construct selectors that uniquely identify an element within an application’s GUI, similar to file paths.
Another difference between industry logs and scientific logs concerns the case notion. In the industry solutions, the case ID is always a task or process label that is manually added to the log. Additional business context attributes also need to be added by users and are not recorded by the tool.
To conclude, our review of industry solutions has found that all existing solutions also record the set of core components that we found in the scientific logs. At the same time, there are considerable differences between the tools regarding the level of detail, set of action types, and recording of UI hierarchy information. In the next section, we build on these findings to design a reference model for process-related UI logs.
5. Reference data model
In this section, we introduce our reference data model for process-related user interaction logs. We consider a reference model to be a conceptual model that serves to be reused for the design of other conceptual models [18]. Under such a reuse-oriented conceptualization, (universal) applicability of the model is not a defining property. However, maximizing the model’s application scope increases its reuse potential and therefore its value to the community. Therefore, we designed the model in an inductive or bottom-up fashion [18]: based on the commonalities and differences between existing UI logs that we found in the literature and industry reviews, we constructed a model that subsumes those commonalities, but remains flexible with regard to their differences.
In the following, we first elaborate on the principles that guided our design process in Section 5.1. The reference model and its individual components are presented in detail in Section 5.2. Finally, we critically discuss our design choices and their implications in Section 5.3.
5.1. Design principles
In the literature and industry reviews, we found that the main commonality between existing UI logs are the six core attributes. The main differences between them concerned the scope, the level of abstraction, and the case notion. Based on these findings, our data model follows four fundamental design principles:
1. **Minimal set of core components**: The essential characteristics of user interactions, as found in the reviews, are modeled as the components and standard attributes of the data model. Because the model is intended to be non-specific and universally applicable, we include no other elements, thus keeping the number of components and standard attributes to a minimum.
2. **Flexible scope**: To ensure flexibility in scope, the data model can be extended with any number of additional components and all components can have an arbitrary number of attributes. Also, nearly all components and standard attributes are optional. The only non-optional component and attribute that ensure the existence of a UI log are the activity and its name.
Information Systems 124 (2024) 102386
L. Abb and J.-R. Rehse
Fig. 5. User interaction log data model.
(3) **Flexible level of abstraction**: To enable user interactions to be modeled in various application contexts and at various levels of abstraction, the domain of the standard attributes in the data model, such as the action type, is left unspecified and can be determined at the point of instantiation. Furthermore, all components are modeled as classes and can be subclassed. Explicit subclasses are only defined for the target object, because they are inherent to the structure of user interfaces and the way they are embedded in information systems.
(4) **No explicit case notion**: Whereas the case notion of a business process is tied to its instances, UI logs are not inherently structured along any data dimension. The reviews have shown that they can have many possible case identifiers. The data model therefore does not include an explicit case notion. Instead, the case notion needs to be defined at the point of instantiation.
5.2. Reference model components
We designed the reference data model as a UML diagram, depicted in Fig. 5. It consists of nine components, modeled as classes, and their interrelations, modeled as associations. Each class has an ID and can have any number of attributes. Some components have standard attributes that have a particular significance for user interactions. In the following, we define and explain the individual components.
5.2.1. Components that define the user interaction
In our model, user interactions consist of two parts. The first part is the action component with its action type standard attribute that describes what the user does. Common action types, as observed in the reviews, correspond to the functionalities of standard peripheral input devices, such as left or right mouse clicks, single keystrokes, or keystroke combinations for shortcuts. Higher-level distinctions are also possible. For example, when collecting data in an ERP system, actions can be divided into input actions, which make changes to a business object, and navigation actions, which only serve to navigate the GUI [1]. We therefore do not specify any default values for the action type attribute.
The second part of a user interaction is the target object on which the action is executed. It is instantiated as one of four object types in the UI hierarchy, as explained below. The action type and target object together determine the central model component: the user activity. An activity has three standard attributes: the activity name, which acts as the event label, like in a traditional event log, an optional input value that denotes, e.g., the string that is entered into a text field, and a timestamp to indicate its execution time. The activity name is determined as a function of the action type of the corresponding action and the identifier of the corresponding target object, for example, a concatenation.
The timestamp is a very common attribute in traditional event logs as well as UI logs. It can be used to calculate the duration of user interactions as well as waiting times between them. In addition, many UI logs rely on timestamps to establish an order between the individual events. However, as we wanted to keep the data model as flexible as possible and there are alternative ways to introduce a notion of order into an event log [65], we did not make timestamps a mandatory attribute of activities. In the absence of a timestamp, we would require at least one other attribute that can serve as an ordering criterion.
5.2.2. Components that define the UI hierarchy
In our reviews, we found that the target object of user interactions was logged at different levels of granularity. To incorporate them, we specified the target object in terms of a UI hierarchy, which integrates the various types of UI element context data into a general structure. It consists of four components, which form a tree-shaped composition hierarchy: UI element, UI group, application, and system. The UI element and UI group levels mirror the hierarchical structure of virtually all GUIs (e.g., the document object model of a website). The application and system levels go beyond the actual GUI and position it within an information system, which makes it possible to record application- and system-level user interactions and allows the UI log to be compatible with cross-application and even cross-system UI tracking.
Most actions are executed on atomic UI elements, which form the lowest level. Examples include buttons, text boxes, dropdowns, checkboxes, or sliders. Elements can be stateful, such as a non-empty text box or a greyed-out button. Capturing this state is necessary, for example, to track the effects of copy/paste actions or to differentiate between activity outcomes. The state of a UI element is therefore recorded in its current state standard attribute.
UI elements are combined into UI groups, which can be nested within other UI groups. In many cases, these UI groups are explicit design elements of the user interface, but our model does not impose grouping criteria and allows UI groups to be formed from arbitrary sets of UI elements. A simple example that we saw in the literature review is an Excel cell (UI element), which is part of a worksheet (UI group), which is again part of a workbook (UI group). Modeling UI groups has two main advantages. First, it allows to uniquely identify functionally identical UI elements. For the example above, recording information about UI groups allows us to distinguish between the cell A1 in separate Excel worksheets. This idea is used in many industry solutions to generate element selectors from screen captures. Second, UI groups can be useful for event abstraction, i.e., mapping user interactions to higher-level conceptual tasks, if these tasks are closely tied to particular UI groups. For example, all interactions with elements in a login mask (enter username, enter password, click login) can directly be abstracted to the “login” task.
UI elements and UI groups belong to an application, i.e., a single program instance. Some actions are directly executed on the application and are not tied to lower-level elements, such as “undo” or application-specific hotkeys.
The root node of the UI hierarchy is the system, on which the applications run and actions are recorded. Similar to application-level actions, it is also possible to capture system-level actions, such as the Ctrl-Alt-Del key combination to open the Task Manager on a Windows system.
5.2.3. Components that define the context
Finally, the data model includes two components that put UIs in a conceptual (process) context: user and task. These exist in some form for all UI logs, which is why they are included in the model. In contrast, other potential context components, such as organizational or resource attributes, are use-case-specific and can be considered by extending the model.
The user is the entity that initiates any interaction. Each action is associated with a single user. Because user IDs and attributes depend on the data collection environment (e.g., device IDs in mobile applications or IP addresses on websites), the model does not specify any attributes for users. This also means that the user component is not necessarily restricted to humans and can model computer-initiated interactions, for example when recording partially automated processes.
The task component models a specific unit of work that is part of a larger process. It is used to associate the recorded user interactions with conceptual tasks or routines, which makes it possible to map low-level GUI interactions to higher-level user activities. This abstraction is an essential prerequisite for being able to perform meaningful analysis on UI logs or to use them for automation. It is, however, also possible to record user interactions that do not belong to any task defined on a conceptual or business level; for example, an employee interacting with a social media application in between performing tasks in an ERP system.
5.3. Critical discussion of model quality
In this section, we want to briefly discuss our model’s design with respect to the six quality criteria for data models proposed by Moody and Shanks [66,67]: completeness, flexibility, simplicity, understandability, integration, and implementability.
A data model is complete if it is able to meet all functional requirements. In our case, this means that the model should be able to capture any process-related UI log. Because our model was developed based on the set of UI logs that we found in our literature and industry reviews, it can capture all of them by design. Of course, we cannot rule out that there may be other, future UI logs that will not be completely or appropriately captured by the data model. However, at least with respect to existing logs, it can be considered as complete.
The flexibility of a data model denotes its ability to be adapted to differing requirements. This was one of our main priorities when developing the model and is reflected in the design principles in Section 5.1. It is important to note that this flexibility presents a trade-off: whereas adaptability is advantageous for a data model, its role as a reference model could be compromised due to the potential for varying implementations. Our model aims to facilitate the standardization of UI logs and to ensure their unification into a common format. This objective may not be fully realized if the implementations vary too widely. If, for example, two UI logs each contain a large number of additional attributes that extend the data model in different ways, or if the discrepancy in the level of abstraction among the action types becomes too significant, they would again require considerable harmonization effort before they can be compared or integrated effectively.
Simplicity of the model was another aspect that we prioritized in the design. It is achieved by including only a minimal set of components and attributes and manifests itself in a relatively low number of elements (entities and relationships) in the model. The understandability of a data model is closely linked to its simplicity. While we cannot conclusively evaluate this without a user study, we argue that the low complexity of the model, and its intended audience of technically proficient researchers and BPM professionals, serves as arguments in favor of its understandability.
The integration of a data model is achieved if it is consistent with other data, e.g., in an organizational context. For our model, it is particularly important to be consistent with other process data, e.g., higher-level events logs or process models. This is facilitated by the inclusion of the task component, which bridges the abstraction level between user interactions and process-level activities, and by the generic nature of the other components such as User, UI element or Application, which are independent of the environment in which the UI log is recorded and used. Beyond that, we argue that effective integration is impossible to ensure in a reference model and primarily hinges on appropriate instantiations in application-specific data models.
Finally, a good data model should be easy to implement. In analogy to the above discussion on completeness, our model’s foundations in existing UI logs also supports its implementability, since each of these logs can be considered as an instantiation of the reference model. However, this does not inherently demonstrate its ease of implementation from the ground up. To address this, we provide a working example of an implementation of our data model in the following Section 6.
It is important to note that this discussion primarily concerns the quality of our model as a data model. Its utility as a reference model according to the reuse-oriented conceptualization of the term can be shown only through the extent of future adoption by others.
6. Working example
In this section, we aim to demonstrate the practical utility of the data model by describing how we instantiated it to design the data collection process in an RPA project that we are currently conducting in cooperation with an ERP system vendor [68]. The project is set in the medical technology industry, where companies are required to regularly validate their information systems to ensure that they are in compliance with external quality regulations. The validation of an information system involves manually executing a number of predefined workflows step-by-step according to a rigid execution plan, checking the result of each step against a set of acceptance criteria, and documenting the result.
A validation project currently involves high manual effort. The goal of our case study is to automate validation for a wide range of workflows using RPA technology. We record how process experts interact with the user interface of the ERP system during validation and then train bots to emulate these interactions. To record interaction data, we modified the source code for the application’s web-based front-end by adding various event handler methods to atomic and container elements (i.e., UI elements and UI groups). This allows us to capture user interactions at a high level of detail and to implement the components and standard attributes from the data model.
In the following, we use the example of a keyword creation workflow to show how an artificial UI log that captures one execution of this workflow may instantiate the data model. A high-level BPMN diagram of the five consecutive steps in the keyword creation workflow is shown in Fig. 6. These steps are executed on the GUI parts shown in Fig. 7.
The user (1) logs in (Fig. 7(a)), (2) selects the right client and profile (Fig. 7(b)), (3) navigates through the dashboard (Fig. 7(c)) to reach the explorer tree (Fig. 7(d), left), (4) creates a new keyword (Fig. 7(d), right), and (5) logs out. The main acceptance criterion is that the newly created keyword shows up in the explorer tree after refreshing.
Table 5 shows an excerpt of the UI log for one case, i.e., one execution of the keyword creation workflow. It includes the action type, target UI element, and one level of UI groups, plus input value and current state where applicable. The captured action types in this log are left and right clicks, text input, selected keyboard shortcuts, and none. The activity label of an event (in most cases) consists of the concatenated action type and target object identifier.
The first two events in the log do not correspond to single user interactions, but instead take advantage of the UI group concept to directly abstract to higher-level tasks. Instead of recording each event in the login and client selection masks separately, the task is tracked only at completion. For these abstracted activities (marked with an “A” prefix), the action type is “none”; they are defined only through the target UI group, independent of the performed actions. This approach can be used for simple tasks with the same execution pattern in all workflows. One upside of this approach is that it makes it possible to not record input values when desired. Whereas in the client selection mask, the content of the text fields is read out when the user presses the “Set Profile” button, input values are never read in the login mask to avoid recording the user’s login credentials. Another advantage of this abstraction is that it reduces noise, which is a common problem in UI logs [2]. In our scenario, activities like initially entering a wrong username do not affect the outcome of the workflow and are therefore not relevant for automating it. By abstracting during data collection, those activities are automatically disregarded.
For effective automation, various user inputs need to be tracked. Therefore, the instantiation of the input value attribute in the log is flexible and depends on the action type and target object: When a user writes into a textbox, the input value is the entered string. When an item is selected from a dropdown, the input value records the label of that item. For abstracted activities, the input value captures the string values of all relevant UI group elements as a map. Most state information, however, is not required for automation. Therefore, the current state attribute only records the values that can be selected from list and dropdown elements, which is needed for some more complex workflows in the validation process. For example, if a document needs to be approved, the validation must verify that a document’s author cannot be selected as approving manager.
This simple example demonstrates how some of the core components of the reference model can be instantiated in a real-life scenario, and how the flexibility in abstraction level can be leveraged to record attributes in a way that matches the requirements of a particular use case.
case. It also shows that, in practice, components that are not relevant for a use case can simply be left out. The main advantage of using the reference model here is that, unlike with an ad-hoc model tailored to the use case, the attributes captured in the UI log follow a general convention that also applies to other user interfaces. This makes recording UI logs in the same format straightforward even in other applications, and makes it possible to develop automation or task mining solutions that are independent of the recording approach used.
The full log from Table 5, which contains additional attributes, is available as a CSV file in our repository. Note that we have replaced the original identifiers for UI elements, groups, and application with symbolic, human-readable ones. The main purpose of this CSV log is to demonstrate the data collected in our working example. In the next section, we provide exemplary implementations of that log in the XES and OCED formats.
7. Implementation
To increase the applicability and reuse potential of our reference data model, we also require an implementation in a common event log format. Such an implementation can be reused for the interchange of UI log data and may be the first step towards defining a standardized interchange format in event logs. Because of the current paradigm shift in the process mining community from single-case event logs towards object-centric ones, this section describes two types of implementations of our data model: a conventional, XES-based one in Section 7.1 and two object-centric, OCED-based ones in Section 7.2.
7.1. XES extension
For the first implementation of the reference model, we relied on XES as the still the de-facto interchange standard for event logs. As described above, the XES standard for event logs allows for domain-specific extensions to describe additional event log attributes. Hence, we implemented the ULLog extension for XES, which provides a standardized exchange format for UI logs as a supplement to the data model. The XML specification for this extension is shown in Fig. 8.7
The implementation considers the event equivalent to the event label. It does not include the activity name or timestamp standard attributes because these are already provided by the concept and time extensions. The other components and standard attributes are defined at event level, i.e., as attributes of an activity instance. The generic target object is not directly implemented, but can instead be specified through attributes that correspond to its four UI hierarchy subclauses: the target object is the lowest-level UI hierarchy component that exists for this event. For example, for an event with a UI element attribute, the target object is always this UI element, whereas for an event with no UI element or UI group attributes, the target object is the application.
An exemplary XES version of the log described in Section 6 that implements this extension is available in our repository.
7.2. OCED implementation
As already described in Section 2, XES has multiple limitations, which play a prominent role in the implementation of UI logs. We discuss these limitations in more detail in the following subsection and explain why an object-centric implementation is well-suited for our reference data model. We then provide implementations of the UI log from Section 6 in two object-centric formats: OCEL 2.0 [27] and an OCED symmetrical header [28]. Of the four reference implementations of the current iteration of the OCED meta-model [15] presented at the OCED symposium at ICPM 2023, these two were the only stand-alone reference implementations. Hence, they were the only two formats that could serve our intended purpose.
7.2.1. Suitability of object-centricity for UI logs
Although it is the current event log standard, XES is not particularly well-suited for UI logs. This has two major reasons. First, XES does not support explicitly defining the relations between attributes, so all components of the UI hierarchy have to be implemented at event level. Therefore, even if many events involve the same target object, the UI group, application, system, and their respective attributes need to be included each time, causing considerable redundancy. Second, XES assumes a single case notion, contrary to the flexible case notion that we intend for the data model. To retain this flexibility, case notion candidates like the user and task context components are also implemented at event level, even though they would be case-level attributes in many UI logs.
As an alternative to XES, an object-centric exchange format could address these shortcomings. In an object-centric event log, all entities or objects are defined in their own right, along with their relations and attributes. An event can be related to any number of objects, eschewing redundant attribute storage. A flexible case notion is inherent to object-centric event logs, because they can be “flattened” and thus viewed from the perspective of any object type. The (full) OCED meta-model
---
7 The extension is also available at https://gitlab.uni-mannheim.de/jpmac/ui-log-data-model/-/raw/main/UILog_extension.
is shown in Fig. 1. The left side of the model describes events, their associated attributes, and the time construct, which are found in a similar form in XES. The right side describes objects and their attributes, as well as typed relations between objects. In the center, these two clusters are connected through qualified associations. Note that there also exists a “base” version of the meta-model, which is missing the associations between event and object relation and between event and object attribute value [69].
Our reference data model lends itself very well to an object-centric implementation, since almost all of its components can be conceptualized as objects and it already defines object-to-object relations, e.g., in the UI hierarchy, and object-to-event relations, e.g., between action and target object. Hence, the mapping of our components to the OCED meta-model is relatively straightforward. The Activity component in our reference model corresponds to the event in the OCED meta-model. The attributes of the Action and Activity components are event attributes. The Activity name and Timestamp standard attributes of the Activity component are equivalent to the event type and time concepts in OCED. The four components of the UI hierarchy (UI element, UI group, Application, and System), as well as the User and Task components, are object types. Their concrete instances in a UI log are objects. All attributes of these components are therefore object attributes. Finally, the aggregation/composition associations within the UI hierarchy are translated to object relations. For the basic version of the reference model, these are the only object relations, as the only other potential objects are Task and User, which are only indirectly connected with other objects.
If the reference model is extended with components that are specific to the domain or the use case, this may of course introduce additional object types and object relations. For example, the full version of the UI log from Section 6 features six attributes not shown in Table 5: (1) a timestamp, (2) the name of the validation test case that is being recorded (Keyword Creation in the working example), (3) the step within the test case and (4) its position, which together instantiate the Task component of the reference model (e.g., Login is the first step to be performed), (5) the HTML tag of the targeted UI element (where applicable), and (6) the application (browser in the working example). In this log, the test case and step attributes can be conceptualized as objects with a hierarchical relation (multiple steps within one test case). The position of the step within the test case is then an attribute of the step object. Likewise, the HTML tag is an attribute of the UI element object.
7.2.2. Implementation in OCEL 2.0
OCEL 2.0 [27] is a revision of the first object-centric event log standard proposed in 2021 [24]. It supports SQLite, XML and JSON.
exchange formats. OCEL 2.0 implements a slightly adapted version of the OCED meta-model, as shown in Fig. 9. In this version, event–object relationships are simplified by removing the direct associations between event and object attribute value respectively object relation. This means that the implementation does not provide a possibility to specify how an event is related to an object attribute or a relation between objects. Instead, events can only be directly related to object instances. In this sense, the implementation is closer to the above-mentioned base OCED meta-model than to the full one in Fig. 1.
In addition, object attribute values in OCEL 2.0 have a direct link to the time concept, which allows for the specification of attribute value time series independent of observed events. This makes it possible to transitively re-establish the association between events and object attribute values through the timestamp of an event, its relation to an object instance, and the timestamps of that object’s attribute values.
An OCEL 2.0 JSON file that implements our working example UI log is included in our repository. This implementation maps the attributes of the working example log to event attributes, objects, or object attributes, as described in the previous subsection. Concretely, we include activity, timestamp, action type, and input value as event attributes and define five object types: test case, step, ui element, ui group, and application. The step object type has the attribute position; the ui element object type has the attributes current state and html tag. The correlation between attribute values and object instances is taken directly from the tabular source log that was produced by our recording tool, i.e., a particular object has an attribute value (at a certain time) if they are observed together in the same event. We assign each attribute value the timestamp of the event that it is observed in, because our recording tool does not include a mechanism to evaluate object attributes independent of the user actions recorded.
There are two types of object relationships in our OCEL 2.0 implementation: the hierarchy among test case and step, as well as the hierarchy among ui element, ui group, and application. In line with the OCED schema, these are defined not at object type level, but individually for each object instance. For example, the object masterdata of type ui element has a relationship to the object explorer tree of type ui group, but there is no general relationship defined between ui elements and ui groups. We chose to leave the optional qualifiers for event to object or object to object relationships empty because they are purely descriptive and not part of the actual user interaction data.
Regarding the limitations of OCEL 2.0 compared to the full OCED meta-model (as described above), we argue that these are of little consequence for UI logs that follow our reference model. For the first limitation, even though there is no direct relation between events and object attribute values in OCEL either, dynamic object attributes and their connection to events are realized through the relation between object attribute values and time, so we do not consider this a limitation of the format.
For the second limitation, the missing association between event and object relation means that object relations must remain static and cannot change throughout an event log. This is in line with the relations between objects in the UI hierarchy, which are generally static: a particular UI element, such as a button, will always remain part of its UI group and will never suddenly move to a different application. This limitation could become a problem if users and tasks are both conceptualized as objects with a direct relation: in this case, it would not be possible for a user to switch from executing one task to another. However, in our reference model, there is no direct association between these two components. Rather, they are indirectly connected through the activity.
7.2.3. Semantic header implementation
The central idea of the semantic header reference implementation [28] is to keep the event log data in a format that can be directly extracted from a source system, e.g., a collection of CSV exports from a relational database. This data is then supplemented with an additional semantic header that specifies how this raw data maps to OCED concepts and how it can be transformed into an event knowledge graph [70], a data structure that naturally model events, objects, and their relations for process mining. Unlike OCEL 2.0, this reference implementation operationalizes the original OCED meta-model without modifications. In the presented implementation [28], the meta-model is translated into a property graph (PG) schema, as shown in Fig. 10. This schema can be instantiated in two JSON files: First, a dataset description file, which contains the name and data type of each attribute and specifies to which column(s) in the underlying data the attribute corresponds. Second, the actual semantic header file, which describes how the raw records are transformed into the event knowledge graph, i.e., which record attributes are used to construct event nodes, entity nodes, and their properties. It also defines relations between entities, i.e., object relations.
Although the semantic header is designed to handle collections of records (as they would be created when exporting several tables from a database), in our case, the UI recording tool only produced a single CSV file, which contains all information. To implement the semantic header, we therefore only define a single EventRecord and create the dataset description file by simply defining one record attribute for each column in the tabular UI log. We set those attributes that do not have
a value for every event to be optional (e.g., the input value, which does not exist for click actions). In the semantic header file, we define the same four event attributes and five objects/entity nodes as in the OCEL implementation: activity, timestamp, action type, and input value as well as test case, step, ui element, ui group, and application.
We also assign the same object attributes as in the OCEL implementation: position for the step object as well as current state and html tag for the ui element object. Finally, we define the same three object relations: step to test case, ui element to ui group, and ui group to application. Unlike in OCEL, these are defined at the level of object types instead of object instances. Which object instances are related to each other is inferred from their co-occurrence in events in the underlying record. We also specify in the header that all other edges in the resulting event knowledge graph (such as the directly-follows relations between events) should likewise be inferred from the raw data.
The dataset description and header JSON files for our working example UI log are also included in our repository.
8. Discussion and conclusion
In this paper, we address the lack of standardization of UI logs, in order to facilitate the exchange and analysis of UI logs in research and practice. Based on a review of the state of the art of process-related UI logs in scientific literature and industry solutions, we propose a reference data model for UI logs. This model consists of a set of core components to capture essential characteristics of user interactions and is flexible with regard to scope, abstraction level, and case notion. We exemplarily show how the model can be instantiated in a real-life RPA scenario and implement it in both a conventional and two object-centric formats. This way, we demonstrate that the emerging paradigm of object-centricity for event data is well suitable for being applied to UI logs.
To achieve our main objective, i.e., address the issues that arise from the lack of standardization of UI logs, we prioritize the future reuse of our reference model and accompanying implementations. Therefore, we derive the model from existing UI logs and show how it can be implemented in multiple standardized data interchange formats. Most of the model components (activities, action types, UI elements, UI groups, applications, timestamps, and input values) are directly adopted from the core attributes identified in our literature and industry reviews. Our contribution is their integration into a unified framework with well-defined relations. For example, we propose a rigid interpretation of an activity by defining it as a combination of an action and a target element. We also expand on the location context of UI elements, which is collected in various forms by most approaches, and explicitly define four distinct types of target objects in an unambiguous hierarchy.
To this unified framework, we add additional, less frequently collected components and standard attributes that are particularly relevant for a complete model of user interactions. For instance, the current state is an important property of stateful UI elements when the log is intended to be used for automation. In the UI hierarchy, we add the system on top of the commonly recorded application to model system-level user interactions. We also introduce the user and task context components to add (optional) generic business context to UI logs.
By providing a domain-specific event log in two reference implementations of the current OCED meta-model, we also make a contribution to the ongoing development of the OCED standard. It can serve as an example and starting point for other implementations, and our discussion of the implementations design choices and limitations in the context of UI logs will hopefully help shape the discussion about the requirements that an object-centric exchange format needs to fulfill.
One limitation of our work concerns its grounding in existing UI logs. Despite following a methodical approach, we do not claim that our reviews or the model are complete or exhaustive. There could be unidentified UI logs or future UI logs in different use cases, which are not well represented by the model. For instance, our data model is only intended to model user interactions with graphical user interfaces, and we did not consider alternative input types, for example from voice commands or eye-tracking devices. The model may also be somewhat biased towards automation use cases because RPA solutions are overrepresented in the two reviews that it is based on. However, our literature review also included UI logs that are not created in an automation context, for example, the ones used by Beerepoot et al. which are used to understand people’s high-level work practices.
goal was to scope the data model in a way that it is not limited to RPA but pertains to all potential use cases of UI logs that we identified. A second limitation is that our object-centric implementations are based on a standard that is not yet finalized and are thus only preliminary. It is possible that they will become outdated once the development of OCED progresses further.
Our reference model can contribute to the field by providing a common, application-independent conceptual framework for user interactions. However, like any reference model, it needs to prove its utility in practice. We therefore want to encourage researchers and practitioners to adopt the model for capturing UI logs in their projects, and to extend it both with regard to new use cases and with regard to conceptual aspects, such as user privacy.
Declaration of competing interest
The authors declare that they have no known competing financial interests or personal relationships that could have appeared to influence the work reported in this paper.
Data availability
No data was used for the research described in the article.
Acknowledgments
This research was supported in part by the German Federal Ministry for Education and Research, grant number 01IS21044B. We would like to thank the senior PC member Andrea Marrella and the three anonymous reviewers for their helpful comments and support on our original conference paper. Furthermore, our gratitude goes to Dirk Fahlbund and Marco Montali for the in-depth discussion of our object-centric implementations.
References
[22] XES Working Group, IEEE standard for eiXensible Event Stream (XES) for achieving interoperability in event logs and event streams, 2015, IEEE Std 1849.
[23] XES Working Group, IEEE approved draft standard for eiXensible Event Stream (XES) for achieving interoperability in event logs and event streams, 2023, IEEE Std.
|
{"Source-Url": "https://madoc.bib.uni-mannheim.de/67173/1/1-s2.0-S0306437924000449-main.pdf", "len_cl100k_base": 14594, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 48930, "total-output-tokens": 17692, "length": "2e13", "weborganizer": {"__label__adult": 0.0003247261047363281, "__label__art_design": 0.0014047622680664062, "__label__crime_law": 0.00034737586975097656, "__label__education_jobs": 0.005596160888671875, "__label__entertainment": 0.0001881122589111328, "__label__fashion_beauty": 0.0002155303955078125, "__label__finance_business": 0.001007080078125, "__label__food_dining": 0.00030922889709472656, "__label__games": 0.0010118484497070312, "__label__hardware": 0.0012254714965820312, "__label__health": 0.00037217140197753906, "__label__history": 0.0006537437438964844, "__label__home_hobbies": 0.00022149085998535156, "__label__industrial": 0.0006651878356933594, "__label__literature": 0.0006489753723144531, "__label__politics": 0.00027060508728027344, "__label__religion": 0.0003740787506103515, "__label__science_tech": 0.1650390625, "__label__social_life": 0.00020968914031982425, "__label__software": 0.07098388671875, "__label__software_dev": 0.748046875, "__label__sports_fitness": 0.000213623046875, "__label__transportation": 0.0004396438598632813, "__label__travel": 0.00020444393157958984}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 79846, 0.03042]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 79846, 0.39666]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 79846, 0.91682]], "google_gemma-3-12b-it_contains_pii": [[0, 4444, false], [4444, 8682, null], [8682, 14186, null], [14186, 18879, null], [18879, 24760, null], [24760, 29286, null], [29286, 34749, null], [34749, 40830, null], [40830, 48541, null], [48541, 51772, null], [51772, 56981, null], [56981, 59944, null], [59944, 65791, null], [65791, 70664, null], [70664, 79846, null], [79846, 79846, null]], "google_gemma-3-12b-it_is_public_document": [[0, 4444, true], [4444, 8682, null], [8682, 14186, null], [14186, 18879, null], [18879, 24760, null], [24760, 29286, null], [29286, 34749, null], [34749, 40830, null], [40830, 48541, null], [48541, 51772, null], [51772, 56981, null], [56981, 59944, null], [59944, 65791, null], [65791, 70664, null], [70664, 79846, null], [79846, 79846, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 79846, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 79846, null]], "pdf_page_numbers": [[0, 4444, 1], [4444, 8682, 2], [8682, 14186, 3], [14186, 18879, 4], [18879, 24760, 5], [24760, 29286, 6], [29286, 34749, 7], [34749, 40830, 8], [40830, 48541, 9], [48541, 51772, 10], [51772, 56981, 11], [56981, 59944, 12], [59944, 65791, 13], [65791, 70664, 14], [70664, 79846, 15], [79846, 79846, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 79846, 0.09127]]}
|
olmocr_science_pdfs
|
2024-12-10
|
2024-12-10
|
c571e79e7059f4a5e992cfe824a4a759c37840d2
|
Partial Evaluation for Dictionary-free Overloading
Mark P. Jones
Research Report YALEU/DCS/RR-959
April 1993
This work is supported jointly by DARPA contract number N00014-91-J-4043 and NSF contract number CCR-9104987.
Partial Evaluation for Dictionary-free Overloading
Mark P. Jones
Yale University, Department of Computer Science,
P.O. Box 2158 Yale Station, New Haven, CT 06520-2158.
Abstract
It has long been suggested that parametric polymorphism might be implemented by generating a distinct version of the code for each monomorphic instance of a function that is used in a given program. However, most implementations avoid this approach for fear that it could lead to a substantial increase in the size of the compiled program—a so-called code explosion—and that it would complicate the process of separate compilation.
An alternative, used in many systems, is to have a single implementation of each polymorphic function and use a uniform (or boxed) representation for all values. This avoids the risk of code explosion but makes it more difficult to support parametric overloading. In addition, the use of boxed representations for even the most primitive values may carry a significant run-time cost.
This paper presents a new approach that lies between these two extremes. The resulting system can be used to obtain an efficient implementation of overloading and to avoid the use of boxed representations of values in common cases (by reducing it to a particular form of overloading). We describe a compiler for a Haskell-like language that supports overloading using a system of type classes. The compiler generates distinct implementations for each overloaded function that appears in a given program but only a single version of the code for pure polymorphic values. This avoids many of the problems associated with the use of dictionaries in previous implementations of type class overloading. Furthermore, comparing the output from our compiler with that of an earlier dictionary-based implementation we find that, for realistic applications, there is no code explosion.
The new compiler has been obtained by adding a simple partial evaluator to the dictionary-based system. The results of this paper therefore provide further motivation for including a more general partial evaluation system as part of production quality compilers for such languages.
We do not attempt to deal with the interaction between partial evaluation and separate compilation although our results certainly suggest that further work in that area would be beneficial.
1 Introduction
The inclusion of a polymorphic type system in the design of a programming language recognizes the fact that many useful algorithms can be described in a uniform manner without full knowledge about the kind of values on which they operate. For example, if all lists are implemented in the same way within a particular programming language, then the process of calculating the length of a list is independent of the type of values that it contains.
In his seminal paper on polymorphism in programming languages [14], Milner used a polymorphic type system as a means of identifying a large class of programs in an untyped λ-calculus whose execution would not “go wrong”. Objects in the underlying semantic model can have many different types; for example, there is a unique identity function \( \lambda x.x \) that serves as the identity for all types. With this in mind, it is quite natural to consider an implementation in which all versions of a particular polymorphic function are implemented by the same section of program code. This approach is simple and has worked well in many practical implementations, including those which support separate compilation. Unfortunately, it is difficult to support parametric overloading in this framework; for example, we may need to rely on run-time tags [1] or additional parameters such as dictionaries in Haskell [7, 21]. In addition, it is necessary to use a uniform representation for run-time values, typically a single machine word. Objects that do not fit into this space must be allocated storage elsewhere and represented by a pointer to that value. This is known as a boxed representation and can cause substantial performance overheads.
Another possibility is to use a simply-typed \( \lambda \)-calculus as the underlying model, with a semantic domain \( D_\tau \) for each type \( \tau \). This leads to an implementation in which distinct sections of code are used to implement different instances of a polymorphic function. For example, the polymorphic identity function mentioned above is treated as a family of functions, indexed by type, with a different implementation, \( \lambda x. : \tau x \), for each type \( \tau \). This is by no means a new idea; similar suggestions have been made many times in the past both as an implementation technique (for example, in [15]) and as a theoretical tool for describing the semantics of ML-style polymorphism [16]. It is easy to deal with overloading and to avoid the need for uniform representations using sets of values indexed by type; there is no need to insist that the indexing set includes all types or that the implementations are always substitution instances of a single simply-typed term.
There are two reasons why this approach has not been widely adopted in concrete implementations; first that it might lead to an explosion in the size of the compiled program, second that it does not interact well with the use of separate compilation. It is not particularly difficult to demonstrate how a code explosion might occur. For example, suppose that we define a sequence of functions in a Haskell program using:
\[ f_i(x, y) = \begin{cases} x & \text{if } i = 0 \\ \text{undefined} & \text{otherwise} \end{cases} \]
where \( f_0 \) has type \( a \to a \to \text{Bool} \). It is easy to show that, in the general case, a call to \( f_i \) will involve \( 2^i \cdot j \) different versions of \( f_j \) for each \( 0 \leq j \leq i \). However, this worst-case exponential behaviour may not occur in practice. For example, if the only instance of \( f_0 \) that is actually used has type \( \text{Int} \to \text{Int} \to \text{Bool} \), then it is only necessary to generate one version of the code for each of the functions \( f_j \).
This paper describes our results with a compiler that uses a combination of the typed and untyped models described above, generating distinct versions of the code for overloaded functions, but only a single version for all other functions. Input programs for the compiler are written in a Haskell-like language with support for user-defined overloading based on an extended system of type classes [7, 11, 21]. All current Haskell systems make use of dictionary values at run-time to implement type class overloading and this can have a significant effect on run-time performance. As a result, some Haskell programmers have resorted to including explicit type information in programs to avoid the use of overloading in performance-sensitive applications, but loosing much of the flexibility that overloading can provide. By generating distinct versions of the code for overloaded operators we have the potential to avoid many of these problems because dictionary values are no longer involved. In effect, we can offer the performance of an explicitly typed program without the need for explicit type signatures, compromising the flexibility of type class overloading.
The dictionary-free implementation is obtained by specializing the output of a previous version of the compiler that does rely on the use of dictionaries at run-time. As might be expected, there is a very close connection with standard techniques used in partial evaluation; a production compiler providing dictionary-free overloading in this way would probably use a more general partial evaluation system to achieve the same kind of results.
The principal objective of the work presented in this paper was to assess what kind of impact, if any, the code explosion problems described above might have in realistic programming examples. The results are very promising, suggesting that, for realistic programs the code explosion problem does not occur. Indeed, in all the cases that we tried, the size of the compiled program was actually reduced!
The remainder of this paper is organized as follows. We begin with a brief introduction to the use of type classes in Haskell in Section 2, describing the way in which overloaded functions are defined and extended to work on a range of datatypes. All current implementations of Haskell are based on the dictionary passing style discussed in Section 3. The need to eliminate the use of dictionaries motivates the use of a form of partial evaluation in Section 4 which produces a dictionary-free implementation of programs using type class overloading. We provide some measurements of program size for a collection of ‘realistic’ programs using both the dictionary passing style and the dictionary-free implementations. Another benefit of a dictionary-free implementation is that it considerably reduces the motivation for the ‘dreaded monomorphism restriction’ in Haskell, making it possible to eliminate this in future versions of Haskell. This is discussed in Section 5. Another application, described in Section 6, is to allow the use of more efficient (i.e. non-uniform) representations for certain frequently used data types. This is made possible by treating the familiar constructor functions and pattern matching constructs as overloaded values. Finally, Section 7 gives some pointers to further work, in particular to the problems of combining global partial evaluation and separate compilation.
2 Type classes
Type classes were introduced by Wadler and Blott [21] as a means of supporting overloading (ad-hoc polymorphism) in a language with a polymorphic type system. This section gives a brief overview of the use of type classes in a language like Haskell and provides some examples that will be used in later sections. Further details may be found in [6, 7]. The basic idea is that a type class corresponds to a set of types (called the instances of the class) together with a collection of member functions (sometimes described as methods) that are defined for each instance of the class. For example, the standard Prelude in Haskell defines the class \( \text{Num} \) of numeric types using the declaration:
\[\text{class } (Eq a, \text{Text} a) \Rightarrow \text{Num} a \text{ where}
\begin{align*}
(+) & : a \to a \to a \\
(\cdot) & : a \to a \\
\text{abs, signum} & : a \to a \\
\text{fromIntegral} & : \text{Integer} \to a
\end{align*}\]
The first line of the declaration introduces the name for the class, \( \text{Num} \), and specifies that every instance \( a \) of \( \text{Num} \) must also be an instance of \( \text{Eq} \) and \( \text{Text} \). These are two additional standard classes in Haskell representing the set of types whose elements can be compared for equality and those types whose values can be converted to and from a printable representation respectively. Note that, were it not for a limited character set, we might well have preferred to write type class constraints such as \( \text{Num} a \) in the form \( a \in \text{Num} \).
The remaining lines specify the operations that are specific to numeric types including simple arithmetic operators for addition (+), multiplication (\( \cdot \)) and subtraction (−) and unary negation \( \text{negate} \). The \( \text{fromIntegral} \) function is used to allow arbitrary integer value to be coerced to the corresponding value in any other numeric type. This is used primarily for supporting overloaded integer literals as will be illustrated below. Notice the last line of the declaration which gives a default definition for subtraction in terms of addition and unary negation. This definition will only be used if no explicit definition of subtraction is given for particular instances of the class.
Instances of the class \( \text{Num} \) are defined by a collection of instance declarations which may be distributed throughout
the program in distinct modules. The program is free to extend the class `Num` with new datatypes by providing appropriate definitions. In the special case of the built-in type `Integer` (arbitrary precision integers or bignums), the instance declaration takes the form:
\[
\text{Instance `Num` `Integer` where}
\]
\[
(+) \quad \equiv \quad \text{primPlusInteger}
\]
\[
\therefore
\]
\[
\text{fromInteger} \ x \ = \ x
\]
This assumes that the implementation provides a built-in function `primPlusInteger` for adding two `Integer` values. Note that, for this special case, the implementation of `fromInteger` is just the identity function. The Haskell standard prelude also defines a number of other numeric types as instances of `Num` including fixed precision integers and floating point numbers. The definition of `fromInteger` is typically much more complicated for examples like these.
Other useful datatypes can be declared as instances of `Num`. For example, the following definition is a simplified version of the definition of the type of complex numbers in Haskell:
```
data Complex a = a :+ a
instance Num a ⇒ Num (Complex a) where
(x :+ y) + (u :+ v) = (x + u) :+ (y + v)
fromInteger x = fromInteger x :+ fromInteger 0
```
We can deal with many other examples such as rational numbers, polynomials, vectors and matrices in a similar way. As a simple example of the use of the numeric class, we can define a generic `fact` function using:
```
\text{fact} \ n \ = \ \text{if} \ n == 0 \ \text{then} \ 1 \ \text{else} \ n * \text{fact} \ (n - 1)
```
Any integer constant \( m \) appearing in a Haskell program is automatically replaced with an expression of the form `fromInteger m` so that it can be treated as an overloaded numeric constant, not just an integer. If we make this explicit, the definition of `fact` above becomes:
```
\text{fact} \ n \ = \ \text{if} \ n == 0 \ \text{then} \ \text{fromInteger} \ 0 \ \text{else} \ n * \text{fact} \ (n - \text{fromInteger} 1)
```
As a result, the `fact` function has type `Num a ⇒ a → a` indicating that, if \( n \) is an expression of type `a` and `a` is an instance of `Num`, then `fact n` is also an expression of type `a`. For example:
```
\text{fact} 6 \ \Rightarrow \ 720
\text{fact} (6.0 :+ 0.0) \ \Rightarrow \ 720.0 :+ 0.0
```
The type system ensures that the appropriate definitions of multiplication, subtraction etc. are used in each case to produce the correct results. At the same time, an expression like `\text{factorial} 0` will generate a type error since there is no declaration that makes `Char`, the type of characters, an instance of `Num`.
3 Dictionary passing implementation
This section outlines the technique of dictionary passing and explains some of the reasons why it is so difficult to produce efficient code in the presence of dictionary values.
The biggest problem in the implementation of overloading is that of finding an efficient and effective way to deal with method dispatch – selecting the appropriate implementation for an overloaded operator in a particular situation. One common technique is to attach a tag to the run-time representation of each object; each overloaded function is implemented by inspecting the tags of the values that it is applied to and, typically using some form of lookup table, branching to the appropriate implementation.
Apart from any other considerations about the use of tags, this approach can only deal with certain kinds of overloading. In particular, it cannot be used to implement the `fromInteger` function described in the previous section; the implementation of `fromInteger` depends, not on the type of its argument, but on the type of the value it is expected to return!
An elegant solution to this problem is to separate tags from objects, treating tags as data objects in their own right. For example, we can implement the `fromInteger` function by passing the tag of the result as an extra argument. This amounts to passing type information around at run-time but is only necessary when overloaded functions are involved. Therefore, in fact, several different choices for the kind of values that are used as tags (corresponding to the notion of evidence in the theory of qualified types [8, 9]). For example, Thate [20] suggests using types themselves as tags, extending the implementation language with a type-case construct that supports ‘pattern matching’ on types to deal with method dispatch.
A more concrete approach – based on the use of dictionary values – was introduced by Wadler and Blott [21] and has been adopted in all current Haskell systems. A dictionary consists of a tuple that contains the implementations for each of the member functions in a given class. Superclasses can be dealt with by storing a pointer to the appropriate class in the dictionary. For example, Figure 1 illustrates the structure of a dictionary for the `Num` class, including the auxiliary dictionaries for the superclasses `Eq` and `Text`.
Specific instances of this structure are constructed as necessary using the instance declarations in a program. We use the names of the member functions as selectors that can be applied to a suitable dictionaries to extract the corresponding implementation. For example, if `dictNumInteger` is the dictionary corresponding to the instance declaration for `Num Integer` given in Section 2, then:
```
(+) dictNumInteger 2 3 \quad \Rightarrow \quad \text{primPlusInteger} 2 3
\quad \Rightarrow \quad 5
```
Notice that these overloaded primitive functions are dealt with by adding an extra dictionary parameter. The same technique can be used to implement other overloaded functions. For example, adding an extra dictionary parameter to the `factorial` function given above and using member functions
For the purposes of this paper, we concentrate on the use of dictionaries although many of our comments apply more generally to any implementation of type class overloading which makes use of evidence values at run-time, whatever concrete form that may take.
3.1 Dictionaries increase program size
In an attempt to reduce the size of executable programs produced by a compilation system, many systems use some form of ‘tree shaking’ to eliminate unused sections of code from the output program. This is particularly important when large program libraries are involved; the standard prelude in Haskell is an obvious example.
The idea of grouping related operations into a single class is certainly quite natural. In addition, it often results in less complicated types. For example, if Haskell used separate classes $Eq$, $Plus$ and $Mult$ for each of the operators (==), (+) and (*) respectively, then the function:
\[
\text{pyth } x \ y \ z \ = \ x \times x + y \times y \quad \text{==} \quad z \times z
\]
might be assigned the type:
\[
(Eq \ a, \ Plus \ a, \ Mult \ a) \Rightarrow a \rightarrow a \rightarrow a \rightarrow \text{Bool}
\]
rather than the simpler:
\[
\text{Num } a \Rightarrow a \rightarrow a \rightarrow a \rightarrow \text{Bool}.
\]
A disadvantage of grouping together methods like this is that it becomes rather more difficult to eliminate unwanted code as part of the tree shaking process. For example, any program that uses a dictionary for an instance of $\text{Num}$ will also require corresponding dictionaries for $\text{Eq}$ and $\text{Text}$. Many such programs will not make use of all of the features of the $\text{Text}$ class, but it is still likely that large portions of the standard prelude dealing with reading and printing values will be included in the output program. In a similar way, even a program where only Int arithmetic is used, the need to include a fromInteger function as part of the dictionary may result in compiled programs that include substantial parts of the run-time support library for Integer bignums.
Another factor that tends to contribute to the size of programs that are implemented using the dictionary passing style is the need to include additional code to deal with the construction of dictionary values (and perhaps to implement the selector functions corresponding to each member function and superclass).
3.2 Dictionaries defeat optimization
It is well known that the presence of higher-order functions often results in significant obstacles to effective static analysis and efficient code generation. Exactly the same kind of problems occur with the use of dictionaries – the selector functions used to implement member functions are (usually) higher-order functions – except that the problems are, if anything, more severe since many of the most primitive operations in Haskell are overloaded.
To illustrate the problems that can occur, consider the following definition of a general purpose function for calculat-
ing the sum of a list of numbers\footnote{Augustsson \[2\] uses essentially the same example to demonstrate similar problems}:
\[
\begin{align*}
\text{sum} & \quad :: \quad \text{Num} \ a \Rightarrow [a] \rightarrow a \\
\text{sum} \ xs & \quad = \quad \text{loop} \ 0 \ xs \\
\text{where} & \quad \text{loop} \ \text{tot} \ [] & \quad = \quad \text{tot} \\
& \quad \text{loop} \ \text{tot} \ (x : xs) & \quad = \quad \text{loop} \ (\text{tot} + x) \ xs
\end{align*}
\]
After the translation to include dictionary parameters this becomes:
\[
\begin{align*}
\text{sum} \ d \ xs & \quad = \quad \text{loop} \ d \ (\text{fromInteger} \ d \ 0) \ xs \\
\text{where} & \quad \text{loop} \ d \ \text{tot} \ [] & \quad = \quad \text{tot} \\
& \quad \text{loop} \ d \ \text{tot} \ (x : xs) & \quad = \quad \text{loop} \ (d ((+) \ d \ \text{tot} \ x)) \ xs
\end{align*}
\]
As the original definition is written, it seems reasonable that we could use standard strictness analysis techniques to discover that the second (accumulating) argument in recursive calls to \text{loop} can be implemented using call-by-value so that the calculation of the sum runs in constant space. Unfortunately, this is not possible because we do not know enough about the strictness properties of the function \((+) \ d\); even if the implementation of addition is strict in both arguments for every instance of \text{Num} in a particular program, it is still possible that a new instance of \text{Num} could be defined in another module which does not have this property. The code for \text{sum} has to be able to work correctly with this instance and hence the implementation of \text{sum} will actually require space proportional to the length of the list for any instance of \text{Num}.
The implementation of \text{sum} given above also misses some other opportunities for optimization. For example, if we were summing a list of machine integers (values of type \text{Int}) then the second argument to \text{loop} could be implemented as an unboxed value, and the addition could be expanded inline, ultimately being implemented by just a couple of low-level machine instructions.
3.3 The run-time overhead of dictionary passing
There are a number of additional run-time costs in an implementation of type class overloading based on dictionaries. The construction of a dictionary involves allocation and initialization of its components. Our experience suggests that the number of distinct dictionaries that will be required in a given program is usually rather small (see Section 4.3 for more concrete details) so the cost of dictionary construction should not, in theory, be too significant. However, there are many examples which show that the same dictionary value may be constructed many times during the execution of a single program. Some of these problems can be avoided by using more sophisticated translation schemes when dictionary parameters are added to Haskell programs, but others cannot be avoided because of the use of context reduction in the Haskell type system (see [9] for further details).
There is also a question about whether dictionary construction is implemented lazily or eagerly. In the first case, every attempt to extract a value from a dictionary must be preceded by a check to trigger the construction of the dictionary if it has not previously been evaluated. (Of course, this is entirely natural for a language based on lazy evaluation and standard techniques can be used to optimize this process in many cases.) The second alternative, eager construction of dictionary, values, risks wasted effort building more of the dictionary structure than is needed. This is a real concern; with the definitions in the standard Prelude for Haskell, the dictionary for the instance \text{RealFloat} (\text{Complex Double}) involves between 8 and 16 additional superclass dictionaries, depending on the way in which equivalent dictionary values are shared. With a lazy strategy, all of the member functions for the \text{RealFloat} class can be accessed after building only a single dictionary.
Finally, there is a potential cost of manipulating the additional parameters used to pass dictionary values. For example, it may be necessary to generate extra instructions and to reserve additional space in a closure (or allocate more application nodes in a graph-based implementation) for dictionaries. However, our experience suggests that these costs are relatively insignificant in practice.
3.4 The use of explicit type signatures
One common optimization in current Haskell systems is to recognize when the dictionaries involved in an expression are constant and to extract the implementations of member functions at compile-time. This often requires the programmer to supply additional type information in the form of an explicit type declarations such as:
\[
\text{fact} \quad :: \quad \text{Int} \rightarrow \text{Int}.
\]
\((\text{Int} \ is \ a \ built-in \ type \ of \ fixed-size \ integers, \ typically \ 32 \ bit \ values.\) The translation of \text{fact} can then be simplified to:
\[
\text{fact} \ n \quad = \quad \text{if} \ \text{primEqInt} \ n \ \text{zero} \\
& \quad \text{then} \ \text{one} \\
& \quad \text{else} \ \text{primMultInt} \ n \ (\text{fact} \ (\text{primSubInt} \ n \ \text{one}))
\]
where \text{primEqInt}, \text{primMultInt} and \text{primSubInt} are primitive functions which can be recognized by the code generator and compiled very efficiently, and \text{zero} and \text{one} are the obvious constant values of type \text{Int}.
In current Haskell systems, adding an explicit type signature like this in small benchmark programs which make extensive use of overloading typically gives at least a ten-fold improvement in program execution time! (Of course, the speedups are much more modest for 'real-world' programs.) As a result, it has become quite common to find Haskell programs that are sprinkled with type annotations, not so much to help resolve overloading, but rather to avoid it altogether.
We should also mention that identifying the correct place to insert an explicit type signature to avoid overloading is not always easy. For example, changing the type declaration for the \text{sum} function in Section 3.2 to:
\[
\text{sum} \quad :: \quad [\text{Int}] \rightarrow \text{Int}
\]
does not necessarily avoid the use of dictionaries. According to the standard typing rules, the local function \text{loop} will still be treated as having the polymorphic overloaded type \text{Num} \ a \Rightarrow a \rightarrow [a] \rightarrow a and the corresponding translation is:
\[
\begin{align*}
\text{sum} \ xs & \quad = \quad \text{loop} \ \text{dictNumInt} \ \text{zero} \ xs \\
\text{where} & \quad \text{loop} \ d \ \text{tot} \ [] & \quad = \quad \text{tot} \\
& \quad \text{loop} \ d \ \text{tot} \ (x : xs) & \quad = \quad \text{loop} \ d ((+) \ d \ \text{tot} \ x) \ xs
\end{align*}
\]
Instead, we have to add a type signature to the local definition:
\[
\text{sum } xs = \text{ loop } 0 \text{ xs}
\]
where
\[
\begin{align*}
\text{loop} & : \text{Int} \rightarrow [\text{Int}] \rightarrow \text{Int} \\
\text{loop tot} \; [] & = \text{tot} \\
\text{loop tot} \; (x : xs) & = \text{loop tot} \; (\text{tot} + x) \; xs
\end{align*}
\]
This allows the code generator to use the optimizations described in Section 3.2, but the flexibility and generality of the original \text{sum} function has been completely lost.
4 A dictionary-free implementation
Haskell type classes have proved to be a valuable extension to the Hindley-Milner type system used in languages like ML. The standard prelude for Haskell included in [7] illustrates this with a range of applications including equality, ordering, sequencing, arithmetic, array indexing, and parsing/displaying printable representations of values. However, it is clear from the comments in the previous section that any implementation based on the use of dictionary passing faces some serious obstacles to good run-time performance.
The possibility of a dictionary-free implementation was mentioned by Wadler and Blott in the original paper introducing the use of type classes [21], together with the observation that this might result in an exponential growth in code size. This was illustrated by considering the function:
\[
squares (x, y, z) = (x \ast x, y \ast y, z \ast z)
\]
which has type:
\[
(\text{Num } a, \text{Num } b, \text{Num } c) \Rightarrow (a, b, c) \rightarrow (a, b, c).
\]
Notice that, even if there are only two instances of the class \text{Num}, there are still eight possible versions of this function that might be required in a given program.
But do examples like this occur in real programs? Other situations where the apparent problems suggested by theoretical work do not have any significant impact on practical results are well known. For example, it has been shown that the complexity of the Dams-Milner type inference algorithm is exponential, but the kind of examples that cause this do not seem to occur in practice and the algorithm behaves well in concrete implementations.
In an attempt to investigate whether expanding programs to avoid the use of dictionaries results in a code explosion, we have developed a compiler for Gofer, a functional programming system based on Haskell, that does not use make use of dictionary parameters at run-time. The compiler is based on an earlier version whose output programs did rely on the use of dictionaries. The main difference is the use of a specialization algorithm, described in Section 4.1, to produce specialized versions of overloaded functions. Not surprisingly, the same results can be obtained using a more general partial evaluation system and we discuss this in Section 4.2.
Comparing the sizes of the programs produced by the two different versions of the compiler, we have been able to get some measure of the potential code explosion. We had expected that expanding out all of the definitions of overloaded functions in realistic applications would produce larger compiled programs, but we hoped that our experiments would show that the increases in code size are usually fairly modest. To our surprise, we were somewhat surprised to find that, for all the examples we have tried, the ‘expanded’ program is actually smaller than the original dictionary based version!
4.1 A formal treatment of specialization
This section describes an algorithm for converting the code for a dictionary-based implementation of a program with overloading to a specialized form that does not involve dictionaries. Although our presentation is rather formal, the algorithm itself is simple enough; starting with the top-level expression in a given program, we replace each occurrence of an overloaded function \( f \) together with the dictionary values \( d \) that it is applied to, with a new variable, \( f' \). The resulting expression is enclosed in the scope of a new definition for \( f' \) that is obtained by specializing the original definition for \( f \) and using the corresponding dictionary arguments \( d \).
4.1.1 Source language
The algorithm takes the translations produced by the type checker [9] as its input; the syntax of these terms is given by the following grammar:
\[
M ::= x e \quad \text{variables} \\
M M \quad \text{application} \\
\lambda x. M \quad \text{abstraction} \\
\text{let } B \text{ in } M \quad \text{local definitions}
\]
The symbol \( x \) ranges over a given set of term variables, and \( e \) ranges over (possibly empty) sequences of dictionary expressions. In addition, \( B \) ranges over finite sets of bindings (pairs of the form \( x = M \) ) in which no variable \( x \) has more than one binding. The symbol \( e \) used here denotes a (possibly empty) sequence of dictionary parameters. The set of variables \( x \) bound in \( B \) will be written \text{dom } B. An additional constraint that is guaranteed by the type system but not reflected by the grammar above is that every occurrence of a variable in a given scope has the same number of dictionary arguments (equal to the number of class constraints in the type assigned to the variable and to the number of dictionary parameters in the defining binding).
Note also that the language used in [9] allows only single bindings in local definitions; of course, an expression of the form \( \text{let } x = M \text{ in } M' \) in that system can be represented as \( \text{let } \{ x = M \} \text{ in } M' \) in the language used here. The motivation for allowing multiple bindings is that we want to describe the specialization algorithm as a source to source transformation and it may be necessary to have several specialized versions of a single overloaded function.
4.1.2 Specialization sets
Motivated by the informal comments above, we describe the algorithm using a notion of \text{specializations} each of which is an expression of the form \( f \ d \rightsquigarrow f' \) for some variables \( f \) and \( f' \) and some sequence of dictionary parameters \( d \). As a convenience, we will always require that \( f' \) is a ‘new’ variable that is not used elsewhere. Since a given program may actually require several specialized versions of some overloaded functions, we will usually work with (finite) sets of specializations. To ensure that these sets are consistent, we will restrict ourselves to those sets \( S \) such that:
\[
(x \ d \rightsquigarrow x'), (y \ e \rightsquigarrow y') \in S \Rightarrow x = y \land d = e.
\]
In other words, we do not allow the same variable to represent distinct specializations. This is precisely the condition needed to ensure that any specialization set \( S \) can be interpreted as a substitution where each \((x \mapsto x') \in S\) represents the substitution of \( x \mapsto x' \) for the variable \( x' \). For example, applying the specialization set \( \{ x \mapsto x' \} \) as a substitution to the term \((\lambda y.y)(x d)\) gives \((\lambda y.y)(x d)\).
In practice, it is sensible to add the following restrictions in an attempt to reduce the size of specialization sets, and hence the size of compiled programs:
- Avoid duplicated specialization of the same function: if \((x \mapsto x') \in S\), then \(x' = y'\).
- Avoid unused specializations: there is no need to include \((x \mapsto x') \in S\) unless \(x\) actually occurs with dictionary arguments \( d\) in the scope of the original definition of \(x\).
Note however that these conditions are motivated purely by practical considerations and are not required to establish the correctness of the specialization algorithm.
It is convenient to introduce some special notation for working with specialization sets:
- If \(V\) is a set of variables, then we defined \(S_V\) as:
\[
S_V = \{ (x \mapsto x') \in S \mid x \not\in V \}.
\]
In other words, \(S_V\) is the specialization set obtained from \(S\) by removing any specializations involving a variable in \(V\). As a special case, we write \(S_\emptyset\) as an abbreviation for \(S(x)\).
- For any specialization set \(S\), we define:
\[
\text{Vars } S = \{ x \mid (x \mapsto x') \in S \}.
\]
- We define the following relation to characterize the specialization sets that can be obtained from a given set \(S\), but with different specializations for variables bound in a given \(B\):
\[
S' \text{ extends } (B, S) \iff \exists S''. \text{Vars } S'' \subseteq \text{dom } B \land S' = S(\text{dom } B) \cup S''.
\]
4.1.3 The specialization algorithm
The specialization algorithm is described using judgments of the form \(S \vdash M \sim M'\) and following the rules in Figure 2. The expression \(M\) is the input to the algorithm and the output is a new term \(M'\) that implements \(M\) without the use of dictionaries and a specialization set \(S\) for overloaded functions that appear free in \(M\).
Note that there are two rules for dealing with variables. The first, \((\var{let})\), is for variables that are bound in a let expression or defined in the initial top-level environment; these are the only places that variables can be bound to overloaded values, and hence the only places where specializations might be required. The second rule, \((\var{\lambda})\), deals with the remaining cases; i.e. variables bound by a \(\lambda\)-abstraction or variables defined in a let expression that are not overloaded. Although it is beyond the scope of this paper, we mention that this distinction can be characterized more formally using the full set of typing rules for the system.
The hypothesis \(e = d\) in the rule \((\var{let})\) implies the compile-time evaluation of the dictionary expressions \(e\) to dictionary constants \(d\). In order for the specialization algorithm to be part of a practical compiler, we need to ensure that this calculation can always be carried out without risk of non-termination. See Section 4.1.6 for further comments.
We should also mention the judgment \(S, S' \vdash B \sim B'\) used as a hypothesis in the rule \((\let{})\). This describes the process of specializing a set of bindings \(B\) with respect to a pair of specialization sets \(S\) and \(S'\) to obtain a dictionary-free set of bindings \(B'\) and is defined by:
\[
S, S' \vdash B \sim B' \iff B' = \{ x' = N' \mid (x = \lambda x.N) \in B \\
\land (x \mapsto x') \in S' \land S \vdash [e/v]N \sim N' \}
\]
Note that, for each variable bound in \(B\), only those that also appear in \(\text{Vars } S'\) will result in corresponding bindings in \(B'\). Assuming we follow the suggestions in the previous section and do not include unused specializations in \(S'\), then the specialization algorithm also provides tree shaking, eliminating redundant definitions from the output program. It is also worth mentioning that the \((\let{})\) rule can very easily be adapted to deal with recursive bindings (often written using \text{let rec} in place of \text{let}). All that is necessary is to replace \(S, S' \vdash B \sim B'\) with \(S', S' \vdash B \sim B'\).
The motivation for specialization was to produce a dictionary-free implementation of the input term. It is clear from the definition above that the output from the algorithm does not involve dictionary values, but it remains to show that the two terms are equal. This, in turn, means that we have to be more precise about what it means for two terms to be equal. For the purposes of this paper we will assume only the standard structural equality together with the two
4.1.5 The treatment of member functions
Specializations involving member functions can be handled a little more efficiently than suggested by the description above. In particular, given a specialization of the form $(m \ d \sim z')$ where $m$ is a member function and $d$ is an appropriate dictionary, there is no need to generate an additional binding for $z'$. Instead, we can extract the appropriate value $M$ from $d$ during specialization, find its specialized form $M'$ and use that in place of $z'$ in the rule (var-member). Thus specialization of member functions might be described by a rule of the form:
$$(\text{var-member}) \quad m \ e = M \quad S \vdash M \sim M' \quad S \vdash m \ e \sim M'$$
The expression $m \ e = M$ represents the process of evaluating $e$ to obtain a dictionary $d$, and extracting the implementation $M$ of the member function for $m$. This rule is essential for ensuring that the output programs produced by specialization do not include code for functions that would normally be included in dictionaries, even though they are never actually used in the program.
4.1.6 Termination
Were it not for the evaluation of dictionary expressions in rule (var-member) and the specialization of member functions in rule (var-member), it would be straightforward to prove termination of the specialization algorithm by induction on the structure of judgments of the form $S \vdash M \sim M'$. To establish these additional termination properties (for Gofor and Haskell), it is sufficient to observe that both the set of overlaid functions and the set of dictionaries involved in any given program are finite and hence there are only finitely many possible specializations. (We assume that a cache/memo-function is used to avoid repeating the specialization of any given function more than once.)
The fact that there are only finitely many dictionaries used in a given program depends critically on the underlying type system. In particular, it has been suggested that the Haskell type system could be modified to allow definitions such as:
f :: Eq a => a -> Bool
f x = x == x && f [x]
This would not be permitted in a standard Hindley/Milner type system since the function $f$ is used at two different instances within its own definition. Attempting to infer the type assigned to $f$ leads to undecidability, but this can be avoided if we insist that an explicit type signature is included as part of its definition. The set of dictionaries that are required to evaluate the expression $f \ 0$ is infinite and the specialization algorithm will not terminate with this program. Fortunately, examples like this are usually quite rare. If the Haskell type system is extended in this way, then it will be necessary to use the dictionary passing implementation to deal with examples like this, even if dictionaries can be avoided in most other parts of the program.
4.2 The relationship with partial evaluation
Techniques for program specialization have already been widely studied as an important component of partial evaluation. Broadly speaking, a partial evaluator attempts to
produce an optimized version of a program by distinguishing static data (known at compile-time) from dynamic data (which is not known until run-time). This process is often split into two stages:
- **Binding-time analysis**: to find (a safe approximation of) the set of expressions in a program that can be calculated at compile-time, and add suitable annotations to the source program.
- **Specialization**: to calculate a specialized version of the program using the binding-time annotations as a guide.
The specialization algorithm described here fits very neatly into this framework. One common approach to binding time analysis is to translate λ-terms into a two-level λ-calculus that distinguishes between dynamic and static applications and abstractions [5]. The dynamic versions of these operators are denoted by underlining, thus \( \underline{M} \underline{N} \) denotes an application that must be postponed until run-time, while \( M \underline{N} \) can be specialized at compile-time. Any \( \lambda \)-term can be embedded in the two-level system by underlining all applications and abstractions, but a good binding time analysis will attempt to avoid as many underlinings as possible.
For the purposes of the specialization algorithm described here, all the binding time analysis need do is mark standard abstractions and applications as delayed, flagging the corresponding dictionary constructs for specialization with the correspondence:
<table>
<thead>
<tr>
<th>Standard Operations</th>
<th>Dictionary Operations</th>
</tr>
</thead>
<tbody>
<tr>
<td>( \lambda x. M \sim \lambda x. M )</td>
<td>delayed</td>
</tr>
<tr>
<td>( M \underline{N} \sim M \underline{N} )</td>
<td>eliminated by specialization</td>
</tr>
<tr>
<td>( M e \sim \lambda v. M )</td>
<td></td>
</tr>
<tr>
<td>( M e \sim M e )</td>
<td></td>
</tr>
</tbody>
</table>
Thus dictionary specialization could be obtained using a more general partial evaluator, using the distinction between dictionaries and other values to provide binding-time information. Even better, we could use this information as a supplement to the results of a standard binding-time analysis to obtain some of the other benefits of partial evaluation in addition to eliminating dictionary values.
### 4.3 Specialization in practice
The specialization algorithm presented here has been implemented in a modified version of the Gofer compiler, translating input programs to C via an intermediate language resembling G-code.
Figure 3 gives a small sample of our results, comparing the size of the programs produced by the original dictionary-based implementation with those obtained by partial evaluation. For each program, we list the total number of supercombinators in the output program, the number of G-code instructions and the size of the stripped executable compiled with cc -O0 on a NeXTstation Turbo (68040) running NeXTstep 3.0. The figures on the first row are for the dictionary-based implementation and the expressions \( n/m \) indicates that a total of \( n \) words are required to hold the \( m \) distinct dictionaries that are required by the program. The figures in the second row are for the partially evaluated version, and each expression of the form \( n \sim m \) indicates that,
<table>
<thead>
<tr>
<th>Program name</th>
<th>Total number of supercombinators</th>
<th>G-code instructions</th>
<th>Executable size</th>
</tr>
</thead>
<tbody>
<tr>
<td>anna</td>
<td>1509 (814/151)</td>
<td>58,371</td>
<td>851,968</td>
</tr>
<tr>
<td>1560 (170→259)</td>
<td></td>
<td>56,931</td>
<td>819,200</td>
</tr>
<tr>
<td>veritas</td>
<td>1032 (105/22)</td>
<td>32,094</td>
<td>499,712</td>
</tr>
<tr>
<td>990 (36→49)</td>
<td></td>
<td>30,596</td>
<td>483,328</td>
</tr>
<tr>
<td>infer</td>
<td>394 (67/13)</td>
<td>6,069</td>
<td>131,072</td>
</tr>
<tr>
<td>361 (39→43)</td>
<td></td>
<td>5,210</td>
<td>114,688</td>
</tr>
<tr>
<td>prolog</td>
<td>256 (76/14)</td>
<td>5,550</td>
<td>114,688</td>
</tr>
<tr>
<td>177 (21→32)</td>
<td></td>
<td>3,207</td>
<td>81,920</td>
</tr>
<tr>
<td>expert</td>
<td>235 (66/12)</td>
<td>5,774</td>
<td>114,688</td>
</tr>
<tr>
<td>141 (23→28)</td>
<td></td>
<td>3,315</td>
<td>81,920</td>
</tr>
<tr>
<td>calendar</td>
<td>188 (46/8)</td>
<td>3,901</td>
<td>90,112</td>
</tr>
<tr>
<td>86 (8→9)</td>
<td></td>
<td>1,273</td>
<td>49,152</td>
</tr>
<tr>
<td>lattice</td>
<td>190 (293/48)</td>
<td>3,880</td>
<td>90,112</td>
</tr>
<tr>
<td>134 (47→101)</td>
<td></td>
<td>1,810</td>
<td>57,344</td>
</tr>
</tbody>
</table>
Figure 3: Code size indicators
of the total number of supercombinators used in the program, \( m \) supercombinators were generated by specialization from \( n \) distinct overloaded supercombinators in the original program.
The programs have been chosen as examples of realistic applications of the Gofer system:
- The largest program, anna is a strictness analyzer written by Julian Seward. Including the prelude file, the source code runs to a little over 15,000 lines spread over 30 script files.
- **veritas** is a theorem prover written by Gareth Howells and taken from a preliminary version of the Glasgow notif benchmark suite.
- **infer** is a Hindley/Milner type checker written by Philip Walder as a demonstration of the use of monads.
- **prolog** is an interpreter for a small subset of Prolog.
- **expert** is an minimal expert system written by Ian Hölzer.
- **calendar** is a small program for printing calendars, similar to the Unix `cal` command.
- **lattice** is a program for enumerating the elements of the lattice \( D_n \) where \( D_0 = \text{Bool} \) and \( D_{n+1} = D_n \rightarrow D_n \) as described in [10]. It is included here as an example of a program that makes particularly heavy use of overloading (as the figures indicate, 75% of the supercombinators in the output program are the result of specialization).
The same prelude file was used for all these tests; a version of the Gofer standard prelude modified to provide closer compatibility with Haskell (including, in particular, a full definition of the `Text` class). Some of these programs made use of Haskell-style derived instances. This allows the programmer to request automatically generated instance declarations for standard type classes when defining a new datatype. Our system does not currently support derived instances and hence it was sometimes necessary to add explicit declarations. It is worth mentioning that, in the case of the anna
benchmark, the code for derived instances caused an increase in the size of the final executable of over 15% for both versions of the compiler. These figures are of interest in their own right; we are not aware of any previous work to make a quantitative assessment of the degree to which overloading is used in realistic applications. For all of the examples listed here, the output program produced by specialization is smaller than the dictionary-based version; in fact, we have yet to find an example where the dictionary-based version of the code is smaller! Not surprisingly, the benefits are greatest for the smaller programs. But even for the larger examples it seems clear that the ability to eliminate redundant parts of dictionaries and to avoid manipulating dictionary parameters more than ‘pays’ for the increase in code size due to specialization.
In the special case of the anna the specialization algorithm increases compile-time (i.e. translation to C) by approximately 15%, from 20.3 user seconds for the dictionary passing version to 23.2 when specialization is used. However, the code generator is very simple minded and we would expect that a high quality, optimizing code generator would have a more significant effect. It is also possible that there would be further overheads in the presence of separate compilation; Gofer does not support the use of modules; a program is just a sequence of script files loaded one after the other.
The time required to translate Gofer code to C is only a fraction of the time required to compile the C code. Using anna again as a typical example, translation to C takes only 3% of the total compilation time. Furthermore, the fact that the specialized version of the program is a little smaller than the dictionary-based version means that the total compile-time is actually slightly lower when specialization is used. Clearly, there are much more pressing concerns than the relatively small costs associated with a more sophisticated C code generator.
The run-time performance of our programs is improved only marginally by the use of partial evaluation; our code generator does not carry out any of the optimizations described in Section 3.2; unlike most Haskell systems, the addition of explicit type signatures as described in Section 3.4 does not give any noticeable increase in performance for either the dictionary or specialization based implementations. In addition, the implementation of dictionaries in Gofer is already very efficient, avoiding most of the problems described in Section 3.3. In particular, all dictionary values are constructed before the execution of a program begins so there is no need to produce code for dictionary constructor functions; there are no problems with repeated construction, and dictionary components can be extracted without having to check for unevaluated dictionaries. We would expect much greater increases in run-time performance in a system using the standard Haskell implementation of dictionaries together with a more sophisticated code generator.
5 Goodbye to the monomorphism restriction!
One of the most controversial features of Haskell is the so-called monomorphism restriction which limits the combination of polymorphism and overloading in certain cases. The current definition of Haskell imposes a much less severe restriction than earlier versions when it was sometimes referred to informally as the ‘dreaded’ monomorphism restric-
tion. Nevertheless, it remains as an added complication to the language and still causes a few surprises for beginners. The principal motivation for using any form of monomorphism restriction is to avoid problems with the let ... in ... construct. From a type-theoretic perspective, this construct is intended purely as a means of defining new polymorphic values within a program. However, in practice, the same construct is also used for other purposes such as shared evaluation or creating cyclic data structures. Unfortunately, in an implementation of type class overloading based on the use of dictionaries, these two applications may conflict with one another. It is necessary to compromise either polymorphism or sharing for the benefit of the other.
To illustrate this, the Haskell report [7] suggests the following expression as a typical example:
\[
\text{let } x = \text{fact } 1000 \text{ in } (x, x). \\
\]
The \text{fact} function used here is assumed to be overloaded with type \(\text{Num } a \Rightarrow a \rightarrow a\). Furthermore, the integer value 1000 is implicitly treated as an overloaded constant of type \(\text{Num } a \Rightarrow a\). Applying an unrestricted form of the standard type checking algorithm to this expression allows us to assign a polymorphic type \(\text{Num } a \Rightarrow a\) to the local definition of \(x\) and use this value at two different instances to obtain a type \((\text{Num } a, \text{Num } b) \Rightarrow (a, b)\) for the complete expression. The corresponding translation is:
\[
\text{let } x \ d = \text{fact } d \ (\text{fromInteger } d \ 1000) \\
\quad \text{in } (x \ d_0, x \ d_0)
\]
where \(d_0\) and \(d_0\) are two (potentially distinct) dictionaries for the \text{Num} class. The problem here is that, whereas the user may have expected the definition of \(x\) to be shared by the two components of the pair, the translation may actually repeat the evaluation of \text{fact} 1000, even if the two components of the pair will actually be used at the same type! In effect, there are situations where the type system must choose between sharing and polymorphism. The problems and confusion occur when this choice differs from what the programmer expects.
In an implementation of type class overloading based on the techniques described in this paper, the need for any form of monomorphism restriction is significantly reduced\(^2\). For the example above, if the two components of the resulting pair are both subsequently used with distinct types then the first step in the specialization of the translation produces:
\[
\text{let } x_0 = \text{fact } d_0 \ (\text{fromInteger } d_0 \ 1000) \\
\quad x_0 = \text{fact } d_0 \ (\text{fromInteger } d_0 \ 1000)
\]
before going on to produce appropriate specializations of \text{fact} and \text{fromInteger}. If, on the other hand, both components are used at a single type then the first step in the specialization process gives:
\[
\text{let } x = \text{fact } d \ (\text{fromInteger } d \ 1000) \text{ in } (x, x)
\]
and there is no loss of sharing.
Thus the system is able to choose between sharing and polymorphism (and possibly other alternatives in-between) based on the way in which defined values are actually used in the program under consideration rather than making some, almost arbitrary decision based on the syntactic form of the definitions for those values.
\(^2\)I am indebted to Martin Odersky for this observation.
6 Specialized representation
The decision to implement all instances of a polymorphic function by a single section of code forces us to use a uniform representation for those arguments whose type may vary between different calls of that function. One common approach is to represent objects by a pointer to some part of the heap where the object is stored; this is often referred to as a boxed representation, while the object that is pointed to is called an unboxed value. The amount of storage required for the unboxed representation of a value (and of course, its interpretation) will vary depending on the type of the object. On the other hand, by using boxed values in the implementation of polymorphic functions, all objects are represented in the same way, independently of their type.
Unfortunately, the use of boxed representations for polymorphic functions makes it more difficult to use unboxed representations when the types of values are fully determined at compile-time. Extracting values from their boxed representation to carry out some operation and then boxing the result have significant overheads. For example, creating a new boxed value will often involve storage allocation. In addition, the use of boxed values may limit the usefulness of standard compiler optimizations such as passing function arguments and results in registers. Some solutions to this problem have been proposed but require, either that the language is extended to deal explicitly with boxed/unboxed representations as in [18], or that we use a more sophisticated type system to discover where coercions between boxed and unboxed representations are required as in [12, 13].
This section describes a new approach to these problems, avoiding the need for uniform boxed representations by generating specialized versions of polymorphic functions. Obviously, this fits in very closely with the work in the first part of the paper; indeed, we show how this can be described as a particular example of overloading using a system of parametric type classes [4].
We should point out that, unlike the work described in the previous sections of this paper, the ideas described here have not yet been implemented. A second caveat is that the use of non-uniform representations is likely to be more useful in a strict language than in a non-strict language. This is a result of the fact that types in the latter provide less information about the run-time representation of values than those in the former. For example, a value of type Int in a strict programming language can always be guaranteed to be an integer. In a non-strict language we must also allow for the possibility that the value is an unevaluated expression which must be evaluated before the corresponding integer value is obtained.
6.1 Datatypes and boxed values
We start by recalling how new datatypes are introduced in Haskell. For example, one standard way of defining a type of lists is given by:
data List a = Nil | Cons a (List a)
This is a compact way of defining several new related values, the most obvious of which are the unary type constructor _List_ and the constructor functions:
\[
\begin{align*}
\text{Nil} & : \rightarrow \text{List} \ a \rightarrow \text{List} \ a \\
\text{Cons} & : a \rightarrow \text{List} \ a \rightarrow \text{List} \ a
\end{align*}
\]
that can be used to build values of the new type. In addition, we must also provide some means of supporting pattern matching, for example, using a function:
\[
\text{caseList} \ :: \ \text{List} \ a \rightarrow b \rightarrow (a \rightarrow \text{List} \ a \rightarrow b) \rightarrow b.
\]
This last component uses a standard technique for encoding datatypes in the lambda-calculus; the intended semantics of _caseList_ can be described by:
\[
\text{caseList} \ d \ n \ c = \ \text{case d of Nil} \rightarrow n \ \\
\text{Cons} \ x \ zs \rightarrow c \ x \ zs
\]
For example, the familiar map function defined by:
\[
\begin{align*}
\text{map} & : (a \rightarrow b) \rightarrow \text{List} \ a \rightarrow \text{List} \ b \\
\text{map} \ f \ \text{Nil} & = \text{Nil} \\
\text{map} \ f \ (\text{Cons} \ x \ zs) & = \text{Cons} \ (f \ x) \ (\text{map} \ f \ zs)
\end{align*}
\]
might be implemented by translating it to:
\[
\text{map} \ f \ ys = \ \text{caseList} \ ys \ \text{Nil} \ ((x \ zs \rightarrow \text{Cons} \ (f \ x) \ (\text{map} \ f \ zs))
\]
(Note that we would not expect or require the programmer to make explicit use caseList; functions like this are intended for internal use only.)
Some authors do not consider functions like caseList to be one of the values defined by a datatype definition, but this is only possible because they have a particular concrete implementation of constructor functions and case expressions in mind. For example, the unboxed representations for expressions of the form Nil and Cons x zs might be:
\[
\begin{align*}
\text{Nil} & \quad \text{Cons} \ x \ zs
\end{align*}
\]
where each box represents a single machine word. If we use this representation for all types of list then the two components in a Cons value must be boxed values. Hence the singleton lists containing the values .42 :: Int and 2.71828 :: Double would be represented by:
\[
\begin{align*}
\text{Cons} & \quad \text{Cons} \\
.42 & \quad \text{Nil} \\
2.71828 & \quad \text{Nil}
\end{align*}
\]
respectively, assuming that floating point values of type Double require two machine words while integers of type Int require only one. (A concrete implementation may attach tags to the numeric values in these examples, but this has no real bearing on the current discussion.)
6.2 Specialized representations using overloading
A slightly more efficient way to represent the two lists above would be to use unboxed representations of the form:
\[
\begin{align*}
\text{Cons} & \quad .42 \quad \text{Null} \\
\text{Cons} & \quad 2.71828 \quad \text{Null}
\end{align*}
\]
allowing the size of a Cons value to vary and using a 'null pointer', Null, as the representation of Nil. The problem with this idea is that there is no simple rule for determining the size of the x field or the starting position of the xs field in a list of the form Cons x xs and hence it is difficult to implement functions like map that work with both kinds of list. One possibility would be to use different tags such as the ConsI and ConsD tags above and allow the implementation of map to obtain the required information by inspecting these tags. However, it would certainly be better if we could avoid this interpretive overhead.
A better way to deal with this problem is to treat the constructor functions and the associated pattern matching constructs as overloaded values:
\[
\text{class list :: List a where}
\]
\[
\text{Nil :: list}
\]
\[
\text{Cons :: a \rightarrow list \rightarrow list}
\]
\[
\text{caseList :: list \rightarrow b \rightarrow (a \rightarrow list \rightarrow b) \rightarrow b.}
\]
Note that parametric type classes [4] are necessary here because the implementation of a constructor function will, in general depend both on the datatype itself (in this case, List) and on the type of the arguments that it is applied to. These dependencies cannot be expressed using either standard Haskell type classes [7] or constructor classes [11]. Parametric type classes can be implemented using the same dictionary passing style described in Section 3, and hence the specialization techniques presented in this paper can be used to ensure that we do not incur any run-time costs from the use of overloading.
With this framework in mind, the definition of the map function in terms of caseList is unchanged, but the type of map, at least for the compiler's purposes becomes:
\[
\text{map :: (la :: List a, lb :: List b) \rightarrow (a \rightarrow b) \rightarrow (la \rightarrow lb)}
\]
\[
= \text{caseList ys Nil (\(x\) zs \rightarrow Cons (f x) (map f zs))}
\]
Note that this type reflects the fact that the representation for the two lists involved in this function. The implementation of caseList used in the definition depends on the representation of la, while the interpretation of Cons and Nil will depend on lb.
As we have already indicated, we would expect the use of overloading to deal with specialized representations to be largely hidden from the programmer. The information that would normally be obtained from class and instance declarations can be generated automatically within the compiler and the whole system can make use of many of the mechanisms already included in the compilation system for supporting the use of type classes.
6.3 Another chance for code explosion?
Some experimental work is required to assess whether code explosion problems are likely when specialized representations are used. Almost every function in a typical program makes use of some simple kind of data structure, so some degree of code explosion seems very likely.
Although we are not yet in a position either to confirm or refute this behaviour, we have carried out some preliminary tests to investigate the kind of code explosion that would occur in the most extreme case when every distinct monomorphic instance of a polymorphic function used in a given program is implemented by a distinct section of code. The results for some of the larger benchmarks are shown in Figure 4. These figures show the number of distinct binding groups that are actually used in the original program (poly) and the number of monomorphic binding groups that would be required in a fully specialized version of the same program (mono). Note that these figures do not take account of the use of dictionaries or of the introduction of new binding groups during compilation, for example, in the implementation of list comprehensions. The figures suggest a typical twofold increase in the number of binding groups but it is not clear how this will relate to code size. For example, the most commonly used function in anna is map with 187 distinct instances. But the code for this function is fairly small and some optimizing compilers might normally choose to expand its definition inline so that there will actually be very little noticeable change in code size for this example. The number of instances of other functions in the program are substantially lower than this.
The most frequently used data structures in all of these programs are lists and pairs and we have included the number of distinct instances of each in the table above. The infer program is a small exception; two of the monads defined in this program have 15 and 18 distinct uses respectively in comparison to the 14 instances of lists.
Further work is needed before we can judge whether the techniques for using specialized representations described here will be useful in practical systems. In the meantime, it is worth mentioning that, to the best of our knowledge, there does not seem to be any other work studying of the extent to which polymorphism is actually used in real programs. This kind of information would be useful in its own right, for example, helping to identify where program optimization is likely to have the greatest impact.
7 Further work
Haskell type classes provide a useful extension to a language with a polymorphic type system but the dictionary-passing style used in all current Haskell systems can incur substantial overheads. Expanding the definitions of all overloaded functions in a given program to avoid the problems caused by the use of dictionaries can, in theory, result in an exponential increase in the size of the program code. However, our experience with an implementation of type classes based on this approach suggests very strongly that this does not occur in realistic programs.
The biggest outstanding problem with the work described here is its interaction with separate compilation. In many systems, the source code for a program may be spread over
several modules. Each program module can be compiled separately. The standard approach is to parse, validate and type check each module and compile it to some appropriate intermediate language. This is then passed to a code generator to obtain an object code file. Once the object code files for all of the source modules in a given program have been produced, they can be passed to a linker that resolves inter-module references and generates the executable program. The complete process is illustrated in Figure 5.
![Diagram of compilation process]
Figure 5: Standard approach to separate compilation
One of the most important benefits of this approach is that, if we make a change to the source code, only those modules that are affected must be recompiled. The full set of object files is required to build the final executable program, but the cost of linking is usually fairly small. A second benefit is that it is not necessary to have all of the source code available when the program is linked; only the object code is required.
To make use of program specialization, we need to postpone code generation as illustrated in Figure 6. This requires a more sophisticated linker that works at a higher level — with the intermediate language rather than the object code. The main problem now is that, when source code changes, the high-level linker will produce a new program to be specialized and the complete specialized program will be passed through the code generator. As we have already mentioned in Section 4.3, code generation in our current implementation is by far the most time-consuming part of the compilation process. The result is that the cost of making even a simple change to the source code is very high.
There are a number of ways that this might be avoided; for example, by adopting some of the techniques used to support incremental compilation or further ideas from partial evaluation. Another interesting possibility would be to postpone some code generation until even later than suggested by Figure 6, so that specialized versions of some parts of the program could be generated dynamically at run-time. Similar techniques have been used with considerable success in the implementation of the object-oriented language Self [5].
![Diagram of specialization process]
Figure 6: Separate compilation with specialization
We should also point out that, despite the problems associated with dictionary passing, the level of performance provided by current Haskell systems is already good enough for a lot of program development work. We might therefore expect to use dictionary-based implementations during the prototyping and development stages, viewing specialization more as a way of improving the performance of the final product.
The current module system in Haskell has been criticized as one of the weakest parts of the language and there have been suggestions that future versions of Haskell might adopt a more powerful system. With the comments of this paper in mind, one of the factors that should strongly influence the choice of any replacement is the degree to which it supports optimization, analysis and specialization across module boundaries.
Acknowledgments
This work was supported in part by grants from DARPA, contract number N00014-91-J-4043, and from NSF, contract number CCR-9104987. Thanks to Martin Odersky and Kung Chen for their comments on this work, to Julian Seward for encouraging me to take my original experiments a little further and for providing me with my biggest benchmark, ana. Thanks also to Paul Hudak for getting me thinking about the relationship between datatype definitions and type classes.
References
|
{"Source-Url": "http://cpsc.yale.edu/sites/default/files/files/tr959.pdf", "len_cl100k_base": 15948, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 17145, "total-output-tokens": 17998, "length": "2e13", "weborganizer": {"__label__adult": 0.0003838539123535156, "__label__art_design": 0.00026988983154296875, "__label__crime_law": 0.0002903938293457031, "__label__education_jobs": 0.0005521774291992188, "__label__entertainment": 5.346536636352539e-05, "__label__fashion_beauty": 0.00016117095947265625, "__label__finance_business": 0.00018012523651123047, "__label__food_dining": 0.0003795623779296875, "__label__games": 0.000518798828125, "__label__hardware": 0.0007834434509277344, "__label__health": 0.000537872314453125, "__label__history": 0.00023758411407470703, "__label__home_hobbies": 8.7738037109375e-05, "__label__industrial": 0.0003609657287597656, "__label__literature": 0.00027561187744140625, "__label__politics": 0.00028896331787109375, "__label__religion": 0.0005450248718261719, "__label__science_tech": 0.00989532470703125, "__label__social_life": 8.249282836914062e-05, "__label__software": 0.00296783447265625, "__label__software_dev": 0.97998046875, "__label__sports_fitness": 0.0003459453582763672, "__label__transportation": 0.0005764961242675781, "__label__travel": 0.00021314620971679688}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 75034, 0.0183]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 75034, 0.66963]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 75034, 0.89441]], "google_gemma-3-12b-it_contains_pii": [[0, 221, false], [221, 5292, null], [5292, 12184, null], [12184, 17985, null], [17985, 20985, null], [20985, 27928, null], [27928, 34536, null], [34536, 39536, null], [39536, 42650, null], [42650, 49233, null], [49233, 56153, null], [56153, 62080, null], [62080, 68065, null], [68065, 71828, null], [71828, 75034, null]], "google_gemma-3-12b-it_is_public_document": [[0, 221, true], [221, 5292, null], [5292, 12184, null], [12184, 17985, null], [17985, 20985, null], [20985, 27928, null], [27928, 34536, null], [34536, 39536, null], [39536, 42650, null], [42650, 49233, null], [49233, 56153, null], [56153, 62080, null], [62080, 68065, null], [68065, 71828, null], [71828, 75034, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 75034, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 75034, null]], "pdf_page_numbers": [[0, 221, 1], [221, 5292, 2], [5292, 12184, 3], [12184, 17985, 4], [17985, 20985, 5], [20985, 27928, 6], [27928, 34536, 7], [34536, 39536, 8], [39536, 42650, 9], [42650, 49233, 10], [49233, 56153, 11], [56153, 62080, 12], [62080, 68065, 13], [68065, 71828, 14], [71828, 75034, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 75034, 0.05046]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
d99e2b36b53a3d5cd9efb2cc9491e831343af4fe
|
Surviving the SAS® Macro Jungle by Using Your Own Programming Toolkit
Kevin Russell, SAS Institute Inc., Cary, North Carolina
ABSTRACT
Almost every night there is a reality show on TV that shows someone trying to survive in a harsh environment by using just their wits. Although your environment is not as harsh, maybe you feel you do not have all the tools you need to survive in the macro programming jungle. This paper’s purpose is to provide you with more programming tools, to make life in the jungle a whole lot easier. For example, the new DOSUBL function is the flint that will ignite your code and enable you to dynamically invoke your macro using DATA step logic. Another tool is the stored compiled macro facility, which can provide protection from the elements by enabling you to keep your code safe from prying eyes. Also included is a discussion of the macro debugging system options, MLOGIC, SYMBOLGEN, and MPRINT. These options act as a compass to point you in the right direction. They can help guide you past a log riddled with errors to an error-free log that puts you back on the right path. CALL SYMPUTX is the new and improved version of CALL SYMPUT. CALL SYMPUTX automatically converts numeric values to character strings and even automatically removes trailing blanks, saving you steps and getting you out of the jungle faster. These tools, along with macro comments, enhancements to %PUT, the MFILE system option, read-only macro variables, the IN operator, and SASHELP.VMACRO, help equip all macro programmers with the tools that they need to survive the macro jungle.
INTRODUCTION
The macro language is an extremely powerful tool within SAS® software that enables you to add functionality to your code as well as make it much more dynamic. However, this power comes with a certain level of complexity. It is this complexity that can sometimes frustrate programmers and make them feel like the macro language is a jungle—difficult to navigate and full of unseen dangers.
This paper describes ten macro programming tools that programmers of all levels can add to their toolboxes. Although a few of these tools have been available for a while, some macro programmers might not yet be aware of them or familiar with their uses. The tools discussed in this paper are intended to help programmers better understand the macro language and program more effectively. For example, the DOSUBL function provides programmers with new functionality to invoke macros from within a DATA step based on DATA step logic, which makes it easier to accomplish complex coding tasks. Another useful tool, the stored compiled macro facility, enables programmers to protect their code from end users. This paper also covers system options that write essential information to the SAS® log to make debugging macro applications much simpler.
This paper discusses the following macro programming tools:
- The DOSUBL function
- The stored compiled macro facility
- Macro debugging system options
- The CALL SYMPUTX routine
- Using comments within a macro definition
- The %PUT statement
- The MFILE system option
- Read-only macro variables
- The macro IN operator
- SASHELP.VMACRO
THE DOSUBL FUNCTION
Quick Facts
- DOSUBL is a new and improved version of the CALL EXECUTE routine.
- DOSUBL was introduced in SAS® 9.4.
SAS Technical Support often receives questions such as the following:
- “How can I send the data for every hospital listed in my data set to a separate CSV file?”
- “How can I run a PROC REPORT for each region listed in my data set?”
- “How can I send an email to each manager listed in my data set?”
Each of these questions has something in common. Each question is asking how to execute a task based on the value of a data-set variable. In SAS, the best way to execute a repetitive task is to use the SAS® Macro language. The best way to invoke a macro based on a data-set variable is to use the new DOSUBL function. You can use DOSUBL the same way you use the CALL EXECUTE routine, but with some added functionality.
Like CALL EXECUTE, DOSUBL gives you the ability to perform two tasks:
- Conditionally execute a macro based on DATA step logic.
- Pass in a data-set variable’s value as the value of a macro parameter.
The following example shows how to use these abilities with DOSUBL. This example executes a REPORT procedure for each hospital listed in the HOSPITALS data set. Below is the sample data set that has data for two hospitals, including the hospital’s ID number, the quarter, and the number of patients in the hospital during that quarter.
```sas
data hospitals;
input hospital_id $ quarter number_of_patients;
datalines;
A100 1 125
A100 2 115
A100 3 130
A100 4 110
A200 1 200
A200 2 195
A200 3 180
A200 4 190
;
```
In the next step, the MYMAC macro uses the HOSP_ID parameter in a WHERE clause to subset the data in the HOSPITALS data set. Each time the macro is executed, the value of HOSP_ID changes so that a separate PROC REPORT is run for each hospital. The reports show the data for each hospital individually.
```sas
/* this macro runs a PROC REPORT for each hospital */
%macro mymac(hosp_id);
title "Data for hospital: &hosp_id";
proc report data=hospitals(where=(hospital_id=&hosp_id));
column hospital_id quarter number_of_patients;
define hospital_id / order;
run;
%mend;
```
The last step is the DATA null step that contains the DOSUBL function. This DATA step uses the BY statement to enable BY-group processing. This type of processing causes the DOSUBL function to be executed only when the BY group changes, which then invokes the MYMAC macro. In order to invoke the macro, the argument to the DOSUBL function must be a text string containing the macro invocation. In other words, the first time the DOSUBL function executes, the argument to the function is `%mymac(A100)`. Because there are two unique values for the BY variable in this example, this code invokes MYMAC twice, producing reports for both hospitals listed.
data _null_;
set hospitals;
by hospital_id;
/* this logic allows us to call the MYMACRO macro
each time the value of HOSPITAL_ID changes */
if first.hospital_id then do;
rc=dosubl(cats('%mymac(',hospital_id,');'));
end;
run;
In addition to the abilities illustrated in the above example, the DOSUBL function also provides you with the ability to
move macro variables to and from the calling environment.
The following example demonstrates this ability. This example shows the DOSUBL function being used to invoke the TRYIT macro, which then uses CALL SYMPUTX to create the macro variable MACVAR. Then, this macro variable is
resolved in the DATA step that contains the DOSUBL function.
**Note:** This code contains numbers that are bolded and enclosed in parentheses, which correspond to a numbered list
below that explains elements of the code.
```sas
%macro tryit(x);
data _null_;
if x=1 then macvar=2;
else macvar=3;
call symputx('macvar', macvar, 'g');
run;
%mend;
data _null_;
rc=dosubl('%tryit(1)');
x=symget('macvar');
put x='(should be 2)';
run;
```
1. The DOSUBL function executes the TRYIT macro, passing in a value of 1 for the X parameter. All of the code
within the TRYIT macro executes immediately.
2. Then, the CALL SYMPUTX statement creates the global macro variable MACVAR. The value of this macro
variable is returned to the calling DATA step.
3. This assignment statement uses the SYMGET function to resolve the macro variable MACVAR. SYMGET is
needed because the resolution of the macro variable MACVAR must be delayed until execution time.
This example illustrates the key difference between DOSUBL and CALL EXECUTE. When CALL EXECUTE is used
to invoke a macro, the macro executes immediately. Execution of SAS statements generated by the execution of the
macro are delayed until after a step boundary is reached. SAS macro statements, including macro variable
references, execute immediately.
When DOSUBL is used to invoke a macro, all code is executed immediately, including all SAS statements. This is
important in this example because of the timing of the CALL SYMPUTX call routine, which is a DATA step call
routine. So, in the example above, if the TRYIT macro was invoked using CALL EXECUTE, CALL SYMPUTX would
not execute until a step boundary was reached. This means that the macro variable MACVAR would not be available
in the calling DATA null step.
As you can see, the DOSUBL function is a powerful tool. DOSUBL can be the flint that ignites your code and enables
you to make your macro invocations data driven.
THE STORED COMPILED MACRO FACILITY
Quick Facts
- Always save your macro source code, because once the macro is compiled, you cannot re-create the source statements.
- The stored compiled macro facility compiles the code only once.
The stored compiled macro facility enables you to store large production jobs that are updated infrequently in a library that you specify within the SASMACR catalog. The macro code is compiled only the first time you submit the code. In all subsequent calls to the macro, the macro processor executes the compiled code. Skipping the compilation phase enables the code to run faster.
However, there is another reason that the stored compiled macro facility is useful. SAS Technical support often receives requests from customers about how they can share code they have written with another person without having that person be able to see the actual code. The answer is to use the stored compiled macro facility.
The following sections discuss three primary reasons why the stored compiled facility is successful at protecting your source code.
STORES MACRO CODE IN AN UNREADABLE MACHINE LANGUAGE
When a macro is compiled, the code is stored in an unreadable machine language as an entry in the SASMACR catalog. There is no way to see the actual macro code that created the entry.
PREVENTS USERS FROM USING MACRO DEBUGGING SYSTEM OPTIONS ON YOUR MACRO
If you specify the SECURE option in the %MACRO statement when a macro is compiled, the macro debugging system options have no effect when the user executes the macro. This means that if users have the MPRINT, SYMBOLGEN, and MLOGIC system options enabled in their SAS session, these options do not write any output to the log when the stored compiled macro is executed. The two logs below show the differences in the log output when you run a macro that was compiled without the SECURE option specified and when the macro was compiled with the SECURE option specified.
Output 1 shows the resulting log from executing the TEST macro without specifying the SECURE option.
```
503 %test
MLOGIC(TEST): Beginning execution.
SYMLOGGEN: Macro variable SYSDATE resolves to 07MAR16
MLOGIC(TEST): %IF condition &sysdate ne 31MAR16 is TRUE
MPRINT(TEST): data new;
MPRINT(TEST): set sashelp.class;
MPRINT(TEST): run;
NOTE: There were 19 observations read from the data set SASHELP.CLASS.
NOTE: The data set WORK.NEW has 19 observations and 5 variables.
NOTE: DATA statement used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
MPRINT(TEST): proc freq data=new;
MPRINT(TEST): table age;
MPRINT(TEST): run;
NOTE: There were 19 observations read from the data set WORK.NEW.
NOTE: PROCEDURE FREQ used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
MLOGIC(TEST): Ending execution.
```
Output 1. Log Output from Executing a Macro Not Compiled Using the SECURE Option
Although you cannot see the definition for the TEST macro in Output 1, you can see that a DATA step and a FREQ procedure step were conditionally executed based on the value of the automatic macro variable SYSDATE. The complete DATA step code and PROC FREQ code are visible in the log.
When you compile this same macro using the SECURE option, the following log is produced when the macro is executed:
```
NOTE: There were 19 observations read from the data set SASHELP.CLASS.
NOTE: The data set WORK.NEW has 19 observations and 5 variables.
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
NOTE: There were 19 observations read from the data set WORK.NEW.
NOTE: PROCEDURE FREQ used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
```
Output 2. Log Output from Executing a Macro Compiled Using the SECURE Option
As Output 2 shows, even if users specify the MPRINT, SYMBOLGEN, and MLOGIC system options, only NOTES, WARNINGS, and ERRORS are written to the log when the macro executes if the SECURE option is specified. The users cannot see any of the actual code in the log.
PREVENTS USERS FROM RETRIEVING YOUR MACRO SOURCE CODE
Finally, storing your macro as a stored compiled macro prevents users from being able to access the code. Once a macro has been compiled, there is no way to decompile it. So, if users have access only to the macro catalog, they are not able to retrieve the code that created the entries in the catalog.
For a complete discussion of the stored compiled macro facility, see the “Saving Macros Using the Stored Compiled Macro Facility” section of SAS® 9.4 Macro Language: Reference, Fourth Edition (support.sas.com/documentation/cdl/en/mcrolref/67912/HTML/default/viewer.htm#n0sjezyl65z1cpnlb6mqfo8115h2.htm).
Using the stored compiled macro facility is one of the best ways to protect your code from the elements and from prying eyes.
MACRO DEBUGGING SYSTEM OPTIONS
**Quick Facts**
- The SYMBOLGEN system option can also be specified as SGEN.
- SYMBOLGEN, MPRINT, and MLOGIC must be enabled.
A best practice for macro programmers is to *always* have the SYMBOLGEN, MPRINT, and MLOGIC system options enabled when developing a macro application. These system options write out information about the execution of your macro to help you with debugging any undesired results. If these options are not enabled, it can be nearly impossible to debug macro code.
When you are debugging your code, you need to know whether the values of your macro variables are correct. The SYMBOLGEN system option writes out the resolved value of a macro variable each time it is referenced, and it is one of the best ways to find this information.
The MPRINT system option writes out all the non-macro SAS statements that are generated by the macro’s execution. This means that MPRINT writes out code like an OPTIONS statement, LIBNAME statement, DATA step code, and PROC code that is contained within the macro definition. If the non-macro code in your macro definition is causing an error, the MPRINT output in the log is the best source of information to help you debug the error.
MLOGIC is the most informative of the three system options. MLOGIC writes the following out to the log:
- The beginning and ending of macro execution
- The location of an autocall macro’s definition
- The values of the macro parameters when the macro is invoked
- The execution of macro statements
- The true or false status for each %IF condition
You can use the output of the MLOGIC system option to help track where you are in the code when tracing its execution in the log. For example, if the outermost macro contains a %IF condition that determines which macro is going to be invoked next, the output of MLOGIC is the best tool to show how the condition was evaluated and which macro is going to be invoked next.
Output 3 is an example of a log that shows an error that was generated during macro execution when these system options were not enabled. The ERROR shows that the variable **GENDER** was referenced when reading the SASHELP.CLASS data set. The log does not show where in the code this error occurred or what syntax caused it.
```
18 %b
ERROR: Variable gender is not on file SASHELP.CLASS.
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.NEW may be incomplete. When this step was stopped there were 0 observations and 0 variables.
WARNING: Data set WORK.NEW was not replaced because this step was stopped.
NOTE: DATA statement used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
NOTE: No variables in data set WORK.NEW.
NOTE: PROCEDURE PRINT used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
```
**Output 3. Output Showing ERROR from Macro Execution**
Output 4 shows the log after running the exact same code, but with the SYMBOLGEN, MPRINT, and MLOGIC system options enabled before executing the code.
As you can see, much more information is written to the log:
```
5 %b
MLOGIC: Beginning compilation of B using the autocall file c:\dstep\b.sas.
MLOGIC: Ending compilation of B.
MLOGIC(B): Beginning execution.
MLOGIC(B): This macro was compiled from the autocall file c:\dstep\b.sas (6)
MLOGIC(B): %LET (variable name is V) (5)
MLOGIC(B): Beginning compilation of A using the autocall file c:\dstep\a.sas.
MLOGIC(B): Ending compilation of A.
MLOGIC(A): Beginning execution.
MLOGIC(A): This macro was compiled from the autocall file c:\dstep\a.sas
SYMBOLGEN: Macro variable V resolves to gender (4)
MLOGIC(A): Parameter VAR has value gender (3)
MPRINT(A): data new;
SYMBOLGEN: Macro variable VAR resolves to gender (2)
MPRINT(A): set sashelp.class(where=(gender='M'));
ERROR: Variable gender is not on file SASHELP.CLASS. (1)
MPRINT(A): run;
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.NEW may be incomplete. When this step was stopped there were 0 observations and 0 variables.
NOTE: DATA statement used (Total process time):
real time 0.01 seconds
cpu time 0.01 seconds
MPRINT(A): proc print;
MPRINT(A): run;
NOTE: No variables in data set WORK.NEW.
NOTE: PROCEDURE PRINT used (Total process time):
real time 0.03 seconds
cpu time 0.03 seconds
MLOGIC(A): Ending execution.
MLOGIC(B): Ending execution.
```
Output 4. Log Output from Macro Execution with Debugging System Options Enabled
The numbers in this list correspond to numbers bolded and enclosed in parentheses in Output 4 and contain an explanation of how you can use this output to debug a problem with macro code.
1. In the MPRINT output in the line above the ERROR, you see that GENDER is being referenced in a WHERE clause in a SET statement. You know that GENDER is not the correct variable name. So, you need to determine where the GENDER value is being introduced.
2. The SYMBOLGEN output in this line shows that the macro variable VAR resolves to GENDER. This lets you know that the value of VAR is what you need to investigate.
3. The MLOGIC output in this line shows that the parameter VAR has the value of GENDER.
4. The SYMBOLGEN output in this line provides a great clue about where the value of GENDER originates from. The SYMBOLGEN output shows that the macro variable V resolves to GENDER. Now you must investigate the value of the macro variable V.
5. The MLOGIC output in this line shows that the macro variable V is created with a %LET statement. So, the next step is to go to the code and change the %LET so that it lists the correct value. Note that 'MLOGIC' is followed by a parenthetical reference to the macro name that contains the code MLOGIC is commenting on. Now you know that you must go to the definition for macro B to fix the code.
6. The MLOGIC output in this line shows that macro B was compiled from the following location: `c:\dstep\b.sas`, which is where you must go to correct the error.
If you ever find yourself lost in the jungle, you could use the sun to determine which way is north, but using a compass is much easier. The next time you are lost in the macro jungle, let the macro debugging system options SYMBOLGEN, MPRINT, and MLOGIC be your compass to guide you out of the jungle.
THE CALL SYMPUTX ROUTINE
Quick Facts
- CALL SYMPUTX includes all the functionality of the CALL SYMPUT routine.
- CALL SYMPUTX has two required arguments (macro-variable and value) and one optional argument (symbol-table).
The CALL SYMPUTX routine is a new and improved version of the CALL SYMPUT routine. For a complete list of improvements, see “CALL SYMPUTX Routine” in SAS® Functions and CALL Routines: Reference, Fourth Edition (support.sas.com/documentation/cdl/en/lefunctionsref/67960/HTML/default/viewer.htm#rinexcs36ctgk5n1kuao7k9myz7y.htm). Here are two of the most beneficial improvements that CALL SYMPUTX offers:
- Left-justifies arguments and trims all trailing blanks.
- Enables you to specify the symbol table in which to store the macro variable.
LEFT-JUSTIFIES ARGUMENTS AND TRIMS ALL TRAILING BLANKS
The following example using CALL SYMPUT shows why this improvement is important. If the second argument to CALL SYMPUT contains a numeric value, that value will be formatted using the BEST12 format and will be right-justified when it is stored as the value of a macro variable. This behavior can cause unexpected problems when you resolve that macro variable in your SAS syntax if the variable is going to be used as a numeric suffix. Consider the following example.
This code uses CALL SYMPUT to create a macro variable whose value is going to be used as a numeric suffix:
```sas
/* CALL SYMPUT is used to create the macro variable N */
Call symput('n',total);
```
Then, it uses the macro variable N as a suffix in the DATA statement as shown below:
```sas
data new&n;
set mylib.salesdata(where=(quarter='1'));
run;
```
This code produces the following error:
```
cpu time 0.00 seconds
SYMBOLGEN: Macro variable N resolves to 8
20621
20622
20623 data new&n;
NOTE: Line generated by the macro variable "N".
20623 new 8
20623 _
20623 22
20623 200
ERROR 22-322: Syntax error, expecting one of the following: a name, a quoted string, (/, /, DATA, LAST, NULL.
ERROR 200-322: The symbol is not recognized and will be ignored.
20624 set mylib.salesdata(where=(quarter='1'));
20625 run;
NOTE: The SAS System stopped processing this step because of errors.
WARNING: The data set WORK.NEW may be incomplete. When this step was stopped there were 0 observations and 0 variables.
WARNING: Data set WORK.NEW was not replaced because this step was stopped.
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
```
Output 5. Log Output from Macro Variable N Referenced in a DATA Statement
This error occurs because the actual value of N is eleven spaces and then the number 8. These leading spaces in the macro variable value are causing the error. The spaces cause an unwanted gap between the data-set name `NEW` and the numeric suffix 8.
Before CALL SYMPUTX, you had to use the LEFT and TRIM functions to left-justify the value and remove the unwanted spaces:
```sas
Call symput('n',trim(left(total)));
```
When you use CALL SYMPUTX, the value of the numeric variable TOTAL is automatically left-justified and any trailing blanks that remain are removed:
```sas
Call symputx('n',total);
```
Now you can safely use the macro variable N as a suffix without causing any unexpected errors.
**SPECIFIES THE SCOPE OF THE MACRO VARIABLE**
The second big advantage CALL SYMPUTX has over CALL SYMPUT is the ability to specify the scope of the macro variable being created, which can be useful if you need to create a large, but unknown number of macro variables. **Scope** refers to the symbol table that the macro variable is stored in. CALL SYMPUTX has a third argument that enables you to specify the scope of the macro being created:
```sas
Call symputx(macro-variable, value <,< symbol-table>);
```
The two most common values for this argument are `G`, which specifies the global symbol table, and `I`, which specifies the most local symbol table that exists.
The following syntax enables you to create the global macro variables VAR1-VARn without having to specify a `%GLOBAL` statement for each variable. This example shows how to create a macro variable from each observation in the data set. This syntax is using the CATS function to concatenate the value of the automatic DATA step variable `_N_` to the prefix `var`:
```sas
Call symputx(cats('var',_n_),total,'g');
```
Creating a macro variable based on the value of a data-set variable is one of the most common tasks programmers perform using the macro language. Using CALL SYMPUTX instead of CALL SYMPUT makes this task easier, which gets you out of the jungle faster.
**USING COMMENTS WITHIN A MACRO DEFINITION**
<table>
<thead>
<tr>
<th>Quick Facts</th>
</tr>
</thead>
<tbody>
<tr>
<td>• Asterisk-style comments and macro-style comments might cause unexpected results in macro definitions.</td>
</tr>
<tr>
<td>• PL/1-style comments are read character-by-character, which allows them to contain special characters like macro triggers, semicolons, and unmatched quotation marks.</td>
</tr>
</tbody>
</table>
Using comments in your code is usually a good idea. Comments can make code easier to follow and understand for anyone who uses it. Comments can be especially helpful in code that is used and updated by multiple programmers. Comments at the beginning of the code can include a description of the entire program as well as information about who last updated the code and what changes were made.
When a macro definition is submitted, everything between the `%MACRO` statement and the `%MEND` statement is compiled. This can result in unexpected behavior when your macro definition contains comments. The following sections provide a description of what happens when the three different types of comments available in SAS are used within a macro definition.
ASTERISK-STYLE COMMENTS
Here is the syntax for asterisk-style comments:
* This is my comment;
Asterisk-style comments are simply stored as text when a macro is compiled. However, the contents of the comment are processed in the tokenizer, which means that special characters within the comment are seen by the word scanner. This can cause undesirable results if your comment contains a macro statement trigger, unmatched quotation marks, or a semicolon. For example, consider the following comment:
*The %let x=value in the following section is used to set the lower limit;
The % is recognized by the word scanner as a macro trigger that causes the %LET statement to execute. The result is the creation of the macro variable X with a value of 'value in the following section is used to set the lower limit'. The word scanner uses the semicolon that was intended to end the comment to actually end the %LET statement. Then, the semicolon at the end of the next statement in the code is used to end the comment.
MACRO-STYLE COMMENTS
Here is the syntax for macro-style comments:
%* This is my comment;
A macro-style comment is a macro statement, so it is processed by the macro processor when the % that begins the statement is encountered. Unlike an asterisk-style comment, a macro-style comment can contain a % without causing unexpected results. A % within a macro-style comment is not seen as a macro trigger, so no attempt is made to execute macro code within the comment. However, the contents of the macro-style comment are still tokenized. This means that unmatched quotation marks and semicolons can cause unexpected problems. For example, if you have a comment like the one below in your macro definition, you will encounter undesirable results:
%* The rest of the developer’s comments in this section discuss the metadata;
Because the contents of this comment are tokenized, the tokenizer sees the apostrophe as the beginning of a literal, which is a string of characters enclosed in quotation marks. To end the literal token, the tokenizer will continue to gather tokens until the closing quotation mark to end the literal is found. Because the close to the literal is never found, the word scanner interprets that all of the subsequent code is part of the literal. When the macro that contains the unmatched quotation mark is submitted, no code executes.
PL/1-STYLE COMMENTS
Here is the syntax for PL/1-style comments:
/* This is my comment */
As you can see, there are certain situations when using asterisk-style comments and macro-style comments within a macro definition can be very problematic. Because of these problems, it is a best practice to use only PL/1-style comments when defining a macro. PL/1-style comments can include the following special characters:
/* The following special characters can all be safely used within this type of comment: ' " % ; */
PL/1-style comments are safer to use because of how they are processed. Instead of looking at each token within the comment, the word scanner looks at each character, character-by-character. The result is that special characters like % and ; have no special meaning between the opening /* and the closing *//, making PL/1-style comments the safest method of including comments within your macro definition.
Using comments in your code can help the user better navigate the jungle. However, using the wrong style of comment in macro code can make it harder to navigate due to unexpected problems. So, every time you use comments in your macro code, you should use PL/1-style comments to make sure there are no issues with the contents of the comments.
THE %PUT STATEMENT
Quick Facts
- The %PUT statement has similar functionality to the PUT statement in the DATA step.
- The %PUT statement supports named output starting in SAS® 9.3.
One of the best ways to check your coding work is to use the %PUT statement. %PUT simply writes text or macro-variable information to the SAS log. The majority of the time, %PUT is used to write out the value of a macro variable. Here is an example in which the variable PROCEDURE contains an unknown number of comma-separated values. The objective is to capture the largest value of N into a macro variable. After the DATA step is complete, you must make sure that the value of the macro variable N is correct. You can use %PUT to do this.
```sas
571 data _null_;
572 set datain;
573 retain tmp;
574 n=countw(procedure,',');
575 if tmp>n then n=tmp;
576 else tmp=n;
577 call symputx('n',n);
578 run;
NOTE: There were 4 observations read from the data set WORK.DATAIN.
NOTE: DATA statement used (Total process time):
real time 0.00 seconds
cpu time 0.00 seconds
579 %put &=n;
N=6
```
Output 6. Log Output from %PUT
Because the data set used in this example contains only 4 observations, it was easy to make sure that 6 is indeed the correct value. Note the syntax for this %PUT statement, which is new for SAS 9.3:
```sas
%put &=macro-variable-name;
```
This syntax writes out the macro variable name, followed by an ‘=’, followed by the macro variable’s value. The variable name being followed by the ‘=’ makes the macro variable’s value easier to see when you look at the log.
The %PUT statement has multiple arguments that can be used to write out a specific group of macro variables. For a complete list of arguments, see the “%PUT Statement” section in SAS® Macro Language: Reference, Fourth Edition (support.sas.com/documentation/cdl/en/mcrolref/67912/HTML/default/viewer.htm#n189gyy83pmkt6n1bq2mmwtyb4oe.htm). _USER_ is the only argument detailed in this paper.
_USER_ shows all of the user-generated local and global macro variables. Here is the syntax:
```sas
%put _user_;
```
When you specify _USER_, the output shows every macro variable that you have created, including the macro variable’s name, scope, and value. This list can be extremely useful when you have created multiple macro variables and need to check your work.
Other than the macro debugging system options, the %PUT statement is one of the most useful tools that you can use to see whether your code is executing as expected and to inventory your macro variables.
THE MFILE SYSTEM OPTION
Quick Facts
- MFILE requires you to set the MPRINT option.
- To use MFILE, you must designate a fileref of MPRINT an external file. The non-macro code generated by MFILE is written to this external file.
An earlier section of the paper covered the “big three” macro debugging system options: SYMBOLGEN, MPRINT, and MLOGIC. This section discusses the macro system option MFILE that can be useful in debugging your code. MFILE enables you to route the non-macro code generated by your macro, which includes all the code that appears in the MPRINT output in the log, to an external file.
Here is a situation in which MFILE can be really useful. How many times have you seen notes similar to the following written to the SAS log?
```
NOTE: Invalid argument to function INPUT at line 839 column 10.
```
This note is returned because most SAS functions expect each of the function’s arguments to be a certain variable type. The INPUT function expects the first argument to be a character value that can be converted into a numeric value. If the first argument lists a character value that cannot be converted into a numeric value, the NOTE shown above is written to the log.
Notice that the NOTE includes a specific line number. When this NOTE is generated by code that is not inside a macro definition, this line number corresponds to the line number in the log that shows the syntax that produced this NOTE. However, if the code that generates this NOTE is within a macro definition, the line number included in the NOTE is not as helpful. Here is an example in which the DATA step within the TEST macro generates the same NOTE as above, but with one key difference:
```
149 150 %macro test;
151 data a;
152 set sashelp.class;
153 new=input(sex,1.);
154 run;
155 %mend;
156 %test
```
```
MLOGIC(TEST): Beginning execution.
MPRINT(TEST): data a;
MPRINT(TEST): set sashelp.class;
MPRINT(TEST): new=input(sex,1.);
MPRINT(TEST): run;
NOTE: Invalid argument to function INPUT at line 156 column 41.
Name=Alfred Sex=M Age=14 Height=69 Weight=112.5 new=. _ERROR_=1 _N_=1
```
Notice that the line number in the NOTE points to the line where the macro is invoked instead of pointing to the line that contains the INPUT function. The NOTE points to this line because it is the invocation of the macro that generates the INPUT function code that then generates the NOTE. Because there is currently no option other than having the NOTE point to the line where the macro is invoked, you can use the MFILE system option to debug.
Once MFILE has routed all the non-macro code generated by the macro to the specified file, it is much easier to debug the problem. Here is the syntax for the MFILE system option:
```
Filename mprint 'c:\mymacros\mycode.sas';
Options mprint mfile;
```
In the syntax above, notice the following points:
- The fileref is "mprint," which is required for the use of the MFILE option.
- The file listed within the quotation marks can have any name and be in any location.
- The MPRINT option is included in the OPTIONS statement as required for the use of the MFILE option.
The MYCODE.SAS file that is created by MFILE can now be executed outside of the macro definition. The same NOTE is still generated, but now the line number listed in the NOTE points to the exact line of code that generated the NOTE, which greatly helps the debugging process.
Although MFILE is not used as often as MLOGIC, MPRINT, and SYMBOLGEN, it can be just as useful at helping you navigate the jungle when debugging code if there are problems with the non-macro code contained in your macro definition.
**READ-ONLY MACRO VARIABLES**
**Quick Facts**
- Both global and local macro variables can be defined as read-only.
- If you omit a value when creating the read-only variable, the macro variable has a null value.
Another way to help protect your code is to use read-only macro variables. Once a macro variable has been defined as read-only, that macro variable’s value cannot be overwritten, nor can the macro variable be deleted. If a macro variable is defined as read-only, it also cannot be redefined within another scope. All read-only macro variables are available until the scope in which they were defined no longer exists.
You can use a read-only macro variable to prevent users from altering certain portions of the code. Consider this example in which there are multiple macros that all reference a single macro variable that resolves to someone’s user ID. To keep users from being able to change this variable’s value to another user ID, you can create the macro variable as read-only. You can use the %GLOBAL statement to create the macro variable as a global macro variable so that it is available for use in all macros. Starting in SAS 9.4, you can add the READONLY option to the %GLOBAL and %LOCAL statements to define the variable(s) listed as read-only. Here is the syntax:
```
%global / readonly user_id=sasid_123;
```
Now, if any attempt is made to re-declare the macro variable USER_ID, the following error is written to the log:
```
ERROR: The variable USER_ID was declared READONLY and cannot be modified or re-declared.
```
If an attempt is made to delete the macro variable USER_ID using %SYMDEL, this error message is written to the log:
```
ERROR: The variable USER_ID was declared READONLY and cannot be deleted.
```
Being able to protect your code is extremely important. Read-only macro variables are yet another tool that you can use to help you protect your code and keep users from altering it.
**THE MACRO IN OPERATOR**
**Quick Facts**
- The IN operator must be enabled by specifying the MINOPERATOR system option.
- The IN operator might require you to use the MINDELIMITER option.
A common programming need is the ability to determine whether a single value is contained in a specified list of values. For many releases of SAS, it has been possible to do this easily in the DATA step by using the IN operator. In the following example, if the value of MAKE is equal to any of the listed values, then the CARTYPE equals 'Luxury':
```
data new;
set sashelp.cars;
if make in('Acura' 'Audi' 'Lexus' 'Infiniti' 'Mercedes-Benz') then
cartype='Luxury';
```
Prior to SAS 9.3, the following syntax was needed to make the same type of evaluation:
```
%if %bquote(&make)=Acura or %bquote(&make)=Audi or %bquote(&make)=Lexus
or %bquote(&make)=Infiniti or %bquote(&make)=%str(Mercedes-Benz) %then %let
cartype=Luxury;
```
In the code above, note that MAKE must be compared to each possible value using the OR operator. Starting in SAS 9.3 however, the IN operator was introduced to the macro language. The following code performs the same evaluation as above, but now uses the IN operator:
```
%if %bquote(&make) in(Acura Audi Lexus Infiniti %str(Mercedes-Benz)) %then %let
cartype=Luxury;
```
As this example shows, the IN operator makes this %IF condition much easier to code.
By default, the IN operator is not available. You have to enable the IN operator by specifying the MINOPERATOR system option:
```
options minoperator;
```
Another option that you might need to specify is the MINDELIMITER= system option, which lets you specify the delimiter used between listed values. The default value for this option is a space. If you want to use any other character as a delimiter, you must set this option. Note that the MINOPERATOR and MINDELIMITER options can also be %MACRO statement options. If you want to use the IN operator only within a single macro, you can use the following syntax:
```
%macro test/ minoperator mindelimiter=',';
```
The IN operator in the macro language definitely makes coding certain %IF conditions much easier, which helps you get out of the jungle faster.
**SASHELP.VMACRO**
Quick Facts
- SASHELP.VMACRO is useful at keeping track of all the macro variables you create.
- SASHELP.VMACRO enables you to subset the view to see only the macro variables you are interested in.
SASHELP.VMACRO is an automatically generated view that contains a list of all the macro variables that currently exist in your SAS session. This list includes all the macro variables you have defined as well as all the macro variables that have been defined by the SAS system.
The contents of this view show you the scope, name, and value of the macro variable. The view also has a value called OFFSET. Because this is a view, the value of the macro variable can be stored only in 200-byte chunks. An OFFSET of >0 indicates that this observation is a continuation of the variable listed in the previous observation. If you access the SASHELP.VMACRO view from within a macro definition, you are able to view the local macro variables as well.
You can use SASHELP.VMACRO to help keep track of macro variables when you have created hundreds of them. If you have created only a few macro variables, then you can use %PUT _USER_ for this purpose. However, if you have many variables, it is much easier to read the information about the macro variables in the output window versus in the log window.
One benefit from having the macro-variable information stored in a view is that you can use logic to create a subset of the file. For example, you can use a WHERE clause similar to the following to subset the view so that you see only macro variables with a prefix of **MAKE**:
```
proc print data=sashelp.vmacro(where=(name='MAKE'));
run;
```
<table>
<thead>
<tr>
<th>obs</th>
<th>scope</th>
<th>name</th>
<th>offset</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>GLOBAL</td>
<td>MAKE1</td>
<td>0</td>
<td>Acura</td>
</tr>
<tr>
<td>2</td>
<td>GLOBAL</td>
<td>MAKE10</td>
<td>0</td>
<td>GMC</td>
</tr>
<tr>
<td>3</td>
<td>GLOBAL</td>
<td>MAKE11</td>
<td>0</td>
<td>Honda</td>
</tr>
<tr>
<td>4</td>
<td>GLOBAL</td>
<td>MAKE12</td>
<td>0</td>
<td>Hummer</td>
</tr>
<tr>
<td>5</td>
<td>GLOBAL</td>
<td>MAKE13</td>
<td>0</td>
<td>Hyundai</td>
</tr>
<tr>
<td>6</td>
<td>GLOBAL</td>
<td>MAKE14</td>
<td>0</td>
<td>Infiniti</td>
</tr>
<tr>
<td>7</td>
<td>GLOBAL</td>
<td>MAKE15</td>
<td>0</td>
<td>Isuzu</td>
</tr>
<tr>
<td>8</td>
<td>GLOBAL</td>
<td>MAKE16</td>
<td>0</td>
<td>Jaguar</td>
</tr>
<tr>
<td>9</td>
<td>GLOBAL</td>
<td>MAKE17</td>
<td>0</td>
<td>Jeep</td>
</tr>
<tr>
<td>10</td>
<td>GLOBAL</td>
<td>MAKE18</td>
<td>0</td>
<td>Kia</td>
</tr>
</tbody>
</table>
Output 8. Partial Output from the PRINT Procedure Statement
A helpful task that uses SASHELP.VMACRO is deleting all the existing user-defined global macro variables. The following example uses SASHELP.VMACRO and the %SYMDEL statement to delete all the user-defined global macro variables:
```
%macro delvars;
data vars;
set sashelp.vmacro;
run;
data _null_;
set vars;
temp=lag(name);
if scope='GLOBAL' and substr(name,1,3) ne 'SYS' and temp ne name then
rc=dosubl('%symdel '||trim(left(name))||';');
run;
%mend;
%delvars
```
The first step of this code block creates a temporary data set that contains the information from SASHELP.VMACRO. This is important because VMACRO is a SASHELP view that contains information about currently defined macro variables. Creating a data set from SASHELP.VMACRO avoids a potential macro-symbol table lock.
The next step checks the variable’s scope and ensures that the variable name does not begin with **SYS**. This is important because you do not want to mistakenly try to delete a macro variable defined by the SAS system. Finally, the DOSUBL function passes the macro variable name to the %SYMDEL statement, which is a macro statement that deletes global macro variables. After you run this code, all global macro variables that you created in this session will have been deleted.
The larger your application, the more likely that it is going to be complicated. SASHELP.VMACRO is an excellent tool to help you keep track of a large number of macro variables that are likely being created with a large application.
**CONCLUSION**
This paper has discussed ten tools that can be added to your macro programming toolbox. The tools discussed in this paper can make certain tasks in macro programming possible and can make other tasks easier. Hopefully, you can incorporate these tools into your own macro toolbox so that they can better equip you to survive the macro jungle.
REFERENCES
ACKNOWLEDGMENTS
I would like to thank my colleague, Russ Tyndall, for his assistance when I was writing this paper.
CONTACT INFORMATION
Your comments and questions are valued and encouraged. Contact the author at:
Kevin Russell
SAS Institute Inc.
SAS Campus Drive
Cary, NC 27513
Email: support@sas.com
Web: support.sas.com
SAS and all other SAS Institute Inc. product or service names are registered trademarks or trademarks of SAS Institute Inc. in the USA and other countries. ® indicates USA registration.
Other brand and product names are trademarks of their respective companies.
|
{"Source-Url": "https://www.pharmasug.org/proceedings/2016/BB/PharmaSUG-2016-BB11.pdf", "len_cl100k_base": 10493, "olmocr-version": "0.1.53", "pdf-total-pages": 16, "total-fallback-pages": 0, "total-input-tokens": 36258, "total-output-tokens": 11737, "length": "2e13", "weborganizer": {"__label__adult": 0.0002002716064453125, "__label__art_design": 0.00022220611572265625, "__label__crime_law": 0.0001633167266845703, "__label__education_jobs": 0.0008177757263183594, "__label__entertainment": 4.374980926513672e-05, "__label__fashion_beauty": 8.225440979003906e-05, "__label__finance_business": 0.0003888607025146485, "__label__food_dining": 0.00019407272338867188, "__label__games": 0.0002999305725097656, "__label__hardware": 0.000396728515625, "__label__health": 0.00016939640045166016, "__label__history": 0.00010508298873901369, "__label__home_hobbies": 5.888938903808594e-05, "__label__industrial": 0.00024771690368652344, "__label__literature": 0.00010031461715698242, "__label__politics": 0.00010985136032104492, "__label__religion": 0.00019800662994384768, "__label__science_tech": 0.003803253173828125, "__label__social_life": 5.751848220825195e-05, "__label__software": 0.0164337158203125, "__label__software_dev": 0.9755859375, "__label__sports_fitness": 0.00012874603271484375, "__label__transportation": 0.00020325183868408203, "__label__travel": 0.00011873245239257812}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 45338, 0.03699]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 45338, 0.60033]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 45338, 0.87242]], "google_gemma-3-12b-it_contains_pii": [[0, 3186, false], [3186, 6057, null], [6057, 8683, null], [8683, 11598, null], [11598, 14811, null], [14811, 16685, null], [16685, 20005, null], [20005, 22600, null], [22600, 25763, null], [25763, 29412, null], [29412, 32021, null], [32021, 34849, null], [34849, 37804, null], [37804, 41130, null], [41130, 43932, null], [43932, 45338, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3186, true], [3186, 6057, null], [6057, 8683, null], [8683, 11598, null], [11598, 14811, null], [14811, 16685, null], [16685, 20005, null], [20005, 22600, null], [22600, 25763, null], [25763, 29412, null], [29412, 32021, null], [32021, 34849, null], [34849, 37804, null], [37804, 41130, null], [41130, 43932, null], [43932, 45338, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 45338, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 45338, null]], "pdf_page_numbers": [[0, 3186, 1], [3186, 6057, 2], [6057, 8683, 3], [8683, 11598, 4], [11598, 14811, 5], [14811, 16685, 6], [16685, 20005, 7], [20005, 22600, 8], [22600, 25763, 9], [25763, 29412, 10], [29412, 32021, 11], [32021, 34849, 12], [34849, 37804, 13], [37804, 41130, 14], [41130, 43932, 15], [43932, 45338, 16]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 45338, 0.03156]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
991be7d4ee7830aa87ca22e68f0a24498247789b
|
CyberLiveApp: A Secure Sharing and Migration Approach for Live Virtual Desktop Applications in a Cloud Environment
Jianxin Li*, Yu Jia*, Lu Liu*, Tianyu Wo*
*School of computer Science & Engineering
Beihang University, Beijing, China
E-mail: {lijx, jiayu, woty} @act.buaa.edu.cn
+School of Computing and Mathematics
University of Derby, Derby, UK
E-mail: l.liu@derby.ac.uk
Abstract
In recent years we have witnessed the rapid advent of cloud computing, in which the remote software is delivered as a service and accessed by users using a thin client over the Internet. In particular, the traditional desktop application can execute in the remote virtual machines without re-architecture providing a personal desktop experience to users through remote display technologies. However, existing cloud desktop applications mainly achieve isolation environments using virtual machines (VMs), which cannot adequately support application-oriented collaborations between multiple users and VMs. In this paper, we propose a flexible collaboration approach, named CyberLiveApp, to enable live virtual desktop applications sharing based on a cloud and virtualization infrastructure. The CyberLiveApp supports secure application sharing and on-demand migration among multiple users or equipment. To support VM desktop sharing among multiple users, a secure access mechanism is developed to distinguish view privileges allowing window operation events to be tracked to compute hidden window areas in real time. A proxy-based window filtering mechanism is also proposed to deliver desktops to different users. To support application sharing and migration between VMs, we use the presentation streaming redirection mechanism and VM cloning service. These approaches have been preliminary evaluated on an extended MetaVNC. Results of evaluations have verified that these approaches are effective and useful.
Key words: Cloud Computing; Software as a Service (SaaS); Virtual Machine; Secure Accessing; Live Application Sharing and Migration
1. INTRODUCTION
The emergence of Internet-based computing paradigms, e.g., cloud computing [1][2] have allowed the Internet to develop into a data storage and computing centre. Large-scale computing, storage and data service resources can be brought together to build a virtual computing environment. The paradigms provide simple and transparent approaches to enable effective sharing and utilisation of applications over the Internet.
In a traditional computing environment, users need to locally install software under a granted license before use. The limitations of the traditional method have become more apparent as software has proliferated. Software users may be burdened with many complex tasks in terms of software installation, configuration, updating and even troubleshooting when dependency on the host operating system causes compatibility issues. In contrast, many companies, such as Amazon and Google have promoted the relative simplicity of the software as service (SaaS) concept [3]. Software can be installed in VMs with easier encapsulation and secure isolation. Users access software on demand through the Internet without any incumbent update and maintenance issues. For the provider there are two alternative methods of making the SaaS software available. One is to develop or redevelop software (e.g., GoogleDoc) based on Web technologies. This not only requires significant work, but may also encounter compatibility problems with the numerous current and developing browsers. The second approach is based on desktop virtualization, which separates the presentation and execution of applications. This provides a transparent way to deliver an application based remote virtual desktop.
Currently virtual desktops are delivered using remote display protocols such as VNC (Virtual Network Computing) [4][5] and RDP (Remote Desktop Protocol) [6]. These protocols generally provide methods for accessing a remote virtual desktop, users login to a VM and work on the desktop.
Secure collaboration has always been a field of intense interest [7]. As user terminal equipment continues to develop mobility, users want to have access their desktops at anytime and anywhere. This level of mobility is made possible in cloud computing where applications are executed in VMs. Providing a novel flexible collaboration service among live virtual desktop applications (live application in short) is the focus of our work. We are presenting some novel scenarios for live application sharing in single or multiple VMs. In a single VM, collaboration scenarios can be supported based on a shared desktop, for example, in a remote teaching system desktop sharing enables the instructor and students to work on the same view. The normal way to authorise remote desktop sharing is to simply share the desktop login accounts and passwords. In a cloud, a virtual machine monitor only provides coarse-grained access control with VM-level granularity. The authorization having only two possible results, success or failure, means users will either all have full access rights with consequent poor privacy and security, or have no concurrent access to the desktop. In particular, it is impractical to share the whole desktop including users’ private windows. Thus, a fine-grained access control mechanism with window-level granularity is required to provide security and privacy protection.
Example 1: Three applications (Document editing, Image viewing and Chatting) are running on a VM owned by User A. A wants to share the desktop with all these applications to User B, but block input from B’s keyboard and mouse. A also gives the authority of viewing the pictures on his virtual desktop to User C, but does not want to show C the document editing window and the chatting window.
In a traditional approach for application sharing among multiple VMs, when a user needs to share an application and related data with other users, binary copies of the application are generated. The replication process may involve significant installation and configuration time and may ultimately fail due to system incompatibilities. In a cloud computing environment, this situation can be easily handled through presentation redirection among application desktops or application data clone in the cloud.
Example 2: In a virtual machine environment, user A is operating a desktop with a drawing application window on it. After finishing his part of the drawing, A intends to let user B continue with it, which means A needs to migrate the application window to B’s desktop; While user C is interested in this drawing application and the drawing user A has finished, C hopes to have a complete copy of this application and this drawing, which means user A has to give a clone of the application and user data to user C.
To meet the above requirements, we have designed a live virtual desktop application sharing and migration system, named CyberLiveApp. The major contributions include:
(1). Multi-user Secure Application Accessing in a single VM. To enable secure live application sharing and collaboration among different users, we have designed a multi-user secure accessing mechanism with application-window-level granularity. A VM owner can configure desktop sharing policies and use a proxy to filter unnecessary or private desktop windows.
- Multi-user secure desktop accessing approach: Considering the VM security, sharing and collaboration needs, we have designed and implemented a multi-user secure accessing approach based on MetaVNC, extending the RFB protocol to support multi-user authentication, and provided the ability for users customised views.
- Window operation event tracking and real-time hidden area computation approach: As the access control objects, windows generally overlap each other and may change dynamically upon events such as resizing, minimizing, maximizing, and moving. We first track the events which affect the layout of multiple windows, and implement a real-time hidden area computation approach to extract a permitted desktop area on a virtual desktop.
• **Proxy-based window filtering mechanism:** In the existing remote control software, access control mechanisms are generally coarse-grained desktop-level. This does not satisfy the window sharing requirements. We implement a desktop view proxy for desktop delivery among different users. The proxy calculates permitted desktop areas and clips hidden areas based on VM owner’s specific security policy.
(2). **Application Sharing and Migration among Multiple VMs:** To enable collaborations among multiple VMs, we have designed a live application sharing and migration mechanism. Through presentation streaming redirection and VM cloning technology, an application can be easily shared or migrated. We also propose an algorithm for maintaining application state and message consistency during application sharing and migration.
• **Presentation streaming redirection approach:** Using live application presentation streaming, users can subscribe to software services and access the virtual desktop. In a cloud environment, all VMs are located in the same network. Due to the encapsulation and migration capabilities of the VM, and the favourable communication bandwidth among the hosts, sharing and migration of live applications between different clients can be achieved through redirection of application presentation streaming. During the migration and sharing process, a VNC connection on a particular client side can be easily created or closed.
• **Application state and message consistency algorithm:** Ensuring the consistency of all application states during application sharing and migration is a critical problem. It means all involved users should get the same view on a shared application, including the application configuration and all user data (stored in both disks memories). During application sharing, a target user should get a complete copy of the application. We achieve this by cloning the VM in which the target application is running. We have designed an algorithm to coordinate the communication sequences among users, and define application state change rules to ….
• **Virtual desktop application sharing & migration protocols:** To overcome the inflexibility of traditional application copy and desktop sharing, we have designed two protocols for virtual desktop application sharing and migration. In the protocols, we implement a desktop session management approach based on inter-process communication. With these protocols, clients and servers communicate via SOAP messages and application sharing is achieved based on VM cloning.
(3). All approaches mentioned above have been implemented in the CyberLiveApp based on extended MetaVNC and the virtual machine monitor KVM. Furthermore, we have performed simulations to verify that the approaches are effective and useful.
The rest of this paper is organized as follows. We discuss the requirements for live applications in Section 2. Section 3 presents the design of CyberLiveApp, the architecture and protocols. We elaborate implementation experiences in Section 4. The related work is discussed in Section 5. Finally, we conclude the paper in Section 6.
2. **Requirements Analysis**
In a VM, when a user wants to share applications on his/her virtual desktop to other users, basic requirements for CyberLiveApp are summarized as follows:
**Requirement 1:** Providing a multi-user accessing mechanism, and controlling viewable desktop areas at application window granularity.
**Requirement 2:** Providing the capability to enable/disable input devices such as keyboard and mouse. For instance, some users are allowed to browse some windows but not to operate or edit them.
Requirement 3: Preventing a third party from eavesdropping on the content of desktop during transmission, i.e., to ensure confidentiality of transmitted context through an encrypted tunnel.
As shown in Figure 1, there are three users connecting to the same VM to view its virtual desktop, but their permissions are different. Table 1 is an example of permission matrix. User A shares all the windows with user B, but does not permit B to operate the windows via his/her keyboard or mouse. User A also shares the desktop to user C after hiding the window areas of text editing and chatting program. User C is also not allowed to operate A’s desktop.
Figure 1: A scenario of secure remote access to a single VM from multiple users
<table>
<thead>
<tr>
<th>ACDS</th>
<th>Picture Browser</th>
<th>Office Word</th>
<th>MSN</th>
<th>Mouse & Keyboard Input</th>
</tr>
</thead>
<tbody>
<tr>
<td>Owner A</td>
<td>Y</td>
<td>Y</td>
<td>Y</td>
<td>Y</td>
</tr>
<tr>
<td>User B</td>
<td>Y</td>
<td>Y</td>
<td>Y</td>
<td>N</td>
</tr>
<tr>
<td>User C</td>
<td>Y</td>
<td>N</td>
<td>N</td>
<td>N</td>
</tr>
</tbody>
</table>
Figure 2: A scenario of secure remote access to multiple VMs
CyberLiveApp achieves the display of remote desktop based on MetaVNC, some key technologies are as follows:
- **Secure access control for multiple users**: The virtual desktop can be accessed by multiple users. Every user has a customized view, and can connect to the virtual desktop in a secure way.
- **Configuration of sharing policy among users**: The virtual desktop owner can specify policies for its applications, and configure the permitted users and their permissions as shown in Table 1.
- **The extraction of application windows**: For the convenience of administrators to assign browse permissions for different users, CyberLiveApp extracts all the windows from the operating system (OS), and stores them in a list. It first gets the handles of all the windows on the desktop, then obtains the processes they belong to, and finally extracts the names of the processes.
- **Hiding specific application windows**: CyberLiveApp selects private windows and calculates the hidden area related to these windows in accordance with the sharing policies.
- **The blocking of keyboard and mouse events**: Through intercepting keyboard and mouse events of different users, the server side of CyberLiveApp decides whether or not to block the keyboard and mouse input events.
Among multiple VMs, when a user wants to copy or migrate applications on a virtual desktop, the source and the destination of application sharing or migration should be specified. As shown in Figure 2, in the VM pool, user A has two VMs running App1 and App2, respectively. User A can connect to the virtual desktop to view App1 and App2 through a notebook computer (Client 1). When user A leaves, he can migrate the App1 to his mobile terminal (Client 2). User B is very interested in App2, and user A can...
easily send this application to user B’s client (Client 3).
The key technologies of live application sharing and migration among multiple VMs include:
• **Redirection of application presentation streaming among multiple client terminals:** In a cloud environment, all applications are maintained in a VM pool, where the virtual desktops are delivered to client terminals through VNC or RDP protocols. In case of application migration or sharing, application windows can be redirected to a new client terminal.
• **Management of VNC connections on the client side:** CyberLiveApp achieves the goal of remote desktop access based on MetaVNC. During the phase of application sharing and migration, an inter-processes communication technology is applied on each client to automatically create/close a specified VNC connection, thus achieving the redirection of application presentation streaming.
• **Application states consistency guarantee:** CyberLiveApp uses a consistent algorithm to regulate the communication sequence. Two protocols have been designed for virtual application sharing and migration, which will be introduced in section ...
3. **DESIGN OF CYBERLIVEAPP**
3.1 Secure Sharing of a Single VM Desktop among Multiple Users
Figure 3 shows the architecture of secure desktop sharing for multiple users. For every VM owned by a user, the display of running applications is delivered to the vncViewer on the client sides through a vncServer installed in the VM.
Figure 2: A scenario of live application sharing & migration between different VMs
The basic procedure of secure desktop sharing among multiple users is as follows:
1. **Extraction of application windows in the operating system**: To enable administrators to assign application permissions to users at window granularity, CyberLiveApp needs to extract all related windows from the operating system. Firstly, CyberLiveApp gets all of the windows handlers on a desktop. Secondly, CyberLiveApp uses the windows handlers to obtain related process handles which the windows belong to, by which we can get the application process names. Finally, CyberLiveApp creates an available application list to users for making security policies.
2. **Policy configuration on CyberLiveApp@Server side**: The owner of virtual desktop creates a list of those who are allowed to access his desktop and assign permissions. The policy is de facto an access control list. The policies include two types - one is a *permit policy* which defines the windows that a user can access, and the other is a *forbid policy* which defines the windows that a user cannot access. When a vncServer runs in the OS, you can right-click the MetaVNC icon to pop-up a menu. When one chooses Properties menu, some configuration options are showed on the tabs, and we add two extra tabs on MetaVNC options dialog to support such configuration.
3. **Authentication of requested users**: When a user wants to access the remote virtual desktop, it will firstly launch the vncViewer to send a connection request to the vncServer though the RFB protocol. The authentication module will authenticate the identity of the requesting user based on the local policy database. If the user is authenticated and acquires the permissions, the vncServer will build a connection with the vncViewer.
4. **The PrivayGate module functions**: In current MetaVNC functions, a vncClient object is created when the vncServer connection is created. Once some events occur on the server desktop, the vncServer will deliver updated desktop to every vncClient. Therefore, each client will get the exact same desktop view. In order to allow each user with a customized view, the vncServer works on the proxy mode to hide some specified windows according to the policies. The significance of our design is a breakthrough in the current MetaVNC structure. A PrivacyGate is used to send the desktop to each vncClient, which means that when the server desktop is changed, it will update the desktop view though a PrivacyGate module based on the *permit policy* or *deny policy*. The PrivacyGate module will hide the window area that the corresponding user has no browsing permission, and then deliver the filtered desktop view to every vncViewer.
5. **Hiding specific application windows of PrivacyGate**: In order to allow every user to have an independant view, the vncServer needs to hide the specified windows according to the policy. Firstly, CyberLiveApp gets the names of the invisible windows which administrator configured for the user. Through this name, CyberLiveApp calls a query function to obtain the handlers of the application window and then gets rectangle area of this window. Secondly, this rectangle area is added into the hidden area which could be a simple rectangle or a complex polygon. When setting the hidden area, some overlapped areas with the hidden windows belonging to the permitted top-level windows should be shown.
6. **Blocking input from keyboard and mouse at PrivacyGate**: Since some users are permitted to only browse, not operate, a desktop, CyberLiveApp blocks input of keyboard and mouse from these users. If the *input variable* state is “DISABLE”, the server will block the client’s inputs, and the user can only view the desktop windows, but cannot operate the server’s windows. If the *input variable* is “ENABLE”, the user’s inputs from the remote client will be handled and responded normally. We control the input operations through Windows hook function, it intercepts and processes the requests to decide whether to forward the input
events.
3.2 Application Sharing and Migration among Multiple VMs
To realize remote application access in a cloud, we use the VNC protocol to transfer the virtual desktop of a remote VM. The VNC protocol works at the buffer frame layer and supports the remote access to graphical user interfaces, and the mouse or keyboard inputs can be transferred to the remote application, thus achieving a transparent access to the applications. In such a presentation streaming-based software delivery mode, when a client wants to migrate or share an application to another client, the presentation streaming of this application should be redirected and the corresponding VM will be cloned in case of application sharing. Based on these considerations, we have designed the architecture for live application sharing and migration (shown in Figure 4). The key components are as follows:
- **Client Controller**: With a modified vncViewer to display application windows from multiple VM machines, the Client Controller manages multiple VNC connections between the vncViewer and vncServers. Using an inter-process communication technology, the Client Controller can close or create a specified VNC connection.
- **Server Controller**: It maintains information of all live users and applications in the VM pool. This component provides a unified management and processing of all clients’ requests, which includes application presentation streaming, and application sharing and migration service.
- **VM Manager**: It provides functionalities of monitoring, stopping, cloning or restarting a specified VM with running applications. VM Manager receives notifications from Server Controller to clone a VM or manage the VM pool.

3.2.1 A Consistent Algorithm for Application States and Messages
In CyberLiveApp, the Server Controller is eligible to identify all the clients’ requests and capable of responding to them by sending control messages to every Client Controller, while the VM Manager manages multiple VM instances in a VM pool. During the phases of application migration and sharing, application states or messages may change frequently. Therefore, we propose a consistent algorithm to ensure the consistency of various application and VM information.
The Server Controller maintains a table of operations of all virtual applications. When a client sends a request to the application, the Server Controller updates its operation. We use the symbol op to denote a requested operation to the application. All the operation variables are defined in Table 2.
<table>
<thead>
<tr>
<th>Variable op</th>
<th>Meaning</th>
</tr>
</thead>
<tbody>
<tr>
<td>v1</td>
<td>NORMAL</td>
</tr>
<tr>
<td>v2</td>
<td>SHARE</td>
</tr>
<tr>
<td>v3</td>
<td>DISCONNECT</td>
</tr>
<tr>
<td>v4</td>
<td>MIGRATE</td>
</tr>
<tr>
<td>v5</td>
<td>CLONE</td>
</tr>
</tbody>
</table>
The op field value of an application is one of the five types at one time. When an application’s op = ‘NORMAL’, that means there is no shared or migration process for this live application. During the
procedure of application sharing and migration, we use a tuple $s$ to describe application states between two clients:
$$s = <op_1, op_2>$$
where $op_1$ denotes the application operation that a client requests, and $op_2$ is the application operation that another client receives. During the procedure of application migration and sharing, an application’s state will be transferred according to the following order as shown in Table 3 and Table 4.
### Table 3: Application state transition during migration
<table>
<thead>
<tr>
<th>Order</th>
<th>$s = <v_1, v_3>$</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>$v_1, v_3$</td>
<td>Client 1 has no request</td>
</tr>
<tr>
<td>2</td>
<td>$v_4, v_3$</td>
<td>Client 1 sends a migration request to Client 2</td>
</tr>
<tr>
<td>3</td>
<td>$v_4, v_4$</td>
<td>Client 2 accepts the migration request</td>
</tr>
<tr>
<td>5</td>
<td>$v_3, v_1$</td>
<td>Client 1 closes the application connection, and Client 2 connects to it.</td>
</tr>
</tbody>
</table>
### Table 4: Application state transition during sharing
<table>
<thead>
<tr>
<th>Order</th>
<th>$s = <op_1, op_2>$</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>$v_1, v_3$</td>
<td>Client 1 has no request</td>
</tr>
<tr>
<td>2</td>
<td>$v_2, v_3$</td>
<td>Client 1 sends a sharing request to Client 2</td>
</tr>
<tr>
<td>3</td>
<td>$v_2, v_2$</td>
<td>Client 2 accepts the sharing request</td>
</tr>
<tr>
<td>4</td>
<td>$v_2, v_5$</td>
<td>VM Manager clones this application, and another instance will be started</td>
</tr>
<tr>
<td>5</td>
<td>$v_1, v_3$</td>
<td>Client 1 returns its initial state as order 1</td>
</tr>
</tbody>
</table>
A consistent algorithm for application states and messages is implemented in the Client Controller as shown in Figure 5 to illustrate how Server Controller deals with different ‘op’ values.
```java
monitor(appName)
Input: appName
1. s = requestState(appName) // gets the application s from Server Controller
2. if(!s.op1.Equals("NORMAL")){
3. ip = getIPbySWUUID(VM.swUUID); // gets the IP address where the software runs
4. if(s.op2.Equals("MIGRATE")){
5. VNCServer.disconnect(Client1); // disconnects the VNC connection
6. update(s,"DISCONNECT","NORMAL"); } // update its state
7. if(s.op2.Equals("SHARE")}{
8. swUUID=VMManager.clone(); // clone a VM whose ID is swUUID
9. update(s, "SHARE", "CLONE"); } // update its state
10. if(s.op2.Equals("DISCONNECT"){
11. update(s,s.op1,s.op2); } // accept the operation of SHARE or MIGRATE
12. if(s.op2.Equals("CLONE")}{
13. ip2 = getIPbySWUUID(swUUID); // get the IP address of the cloned VM
14. sendMsg(Client2,"NORMAL",ip2); // Notify Client2 to connect the cloned VM
15. }) }
```
Figure 5: A consistent algorithm for application state and messages
In this algorithm, RequestSendMsg() is responsible for updating the application states, and sending notifications to the clients. We have implemented a SOAPServer in the Server Controller, which receives SOAP messages from the Client Controller and updates the state of application.
### 3.2.2 Virtual Desktop Application Sharing & Migration Protocols
When a Client Controller requests to migrate or share a live application, both of them will work precisely as the algorithm indicates. Several steps are taken to complete the migration or sharing as shown in Figure 6 and Figure 7.
The steps of application migration are as follows:
Step 1: Client1 $\rightarrow$ ServerController: $[\text{AppName, MigrationSource, MigrationDes}]$ The Client 1 sends a migration request to ServerController with the $\text{AppName, MigrationSource}$ and $\text{MigrationDes}$. In
CyberLiveApp, all connected clients firstly register in ServerController, so that the Client 1 can choose the destination from the client list on LiveApp@Client side.
Step2: ServerController → Client2: \{AppName, VMInfo, MigrationSource, MigrationDes\}. The Client2 gets a migration notification from LiveApp@VM Pool side, and the VM IP address and VNCServer port are enclosed in VMInfo, so the VNCViewer can connect to a remote VNCServer to view the application. Sometimes, the Client 2 does not have a public IP address (e.g., it locates in a local network), so Server Controller cannot initialize a connection to Client 2. In CyberLiveApp, we can change the mode of Step 2 through actively querying to ServerController at a certain interval.
Step3: ClientController@Client2 → VNCViewer@Client2: \{VMInfo\}. The Client2’s ClientController creates a new Client2’s VNCViewer connection to the remote VNCServer running on the VM and the VNCServer will also close the connection with Client1. Therefore, the presentation streaming of Client1 can be redirected to Client2, and the application view and data are exactly the same due to no change in its running environment.
Step4: Client2 → ServerController: \{MigrationFinal\}. The Client2 sends a MigrationFinal message to the ServerController.
Step5: ServerController → Client1: \{MigrationComplement\}. The ServerController updates the meta information of VMPool, and sends a MigrationComplement message to Client1.
Step6: ClientController@Client1 → VNCViewer@Client1: \{VMInfo\}, Client1’s ClientController clears the connection record of Client1’s VNCViewer, and shows a migration success dialog on Client 1.
The steps of application sharing are as follows:
Step1: Client1 → ServerController: \{AppName, SharingSource, SharingDes\}. Client 1 sends an application sharing request to ServerContolller with the AppName, SharingSource and SharingDes. In CyberLiveApp, all connected clients firstly register in ServerController, so that Client 1 can choose the destination from the client list on LiveApp@Client side.
Step2: ServerController → Client2: \{AppName, SharingSource, SharingDes\}. Client2 gets a sharing notification from LiveApp@VM Pool side. Sometimes, Client 2 does not have a public IP address (e.g., it locates in a local network), so Server Controller cannot initialize a connection to the Client 2. In CyberLiveApp, we can change the mode of Step 2 through actively querying the ServerController at an interval.
Step3: Client2 → ServerController: \{CloneRequest\}. Client2 sends a clone request the ServerController after it accepts the sharing message from Client1.
Step4 & Step5: ServerController → VMManager: \{VMClone, VMInfo\}. ServerController sends a VM clone request to the VMManager, and VMManager clones a VM with Libvirt command.
Step6: ServerController → Client2: \{VMInfo\}. The cloned VM IP address and VNCServer port are enclosed in VMInfo, so the VNCViewer can connect to a remote VNCServer to view the application.
Step7: ClientController@Client2 → VNCViewer@Client2: \{VMInfo\}. Client2’s ClientController creates
a new Client2’s VNCViewer connection to the remote VNCServer running on the cloned VM. Therefore, Client2 can view the duplicated application like Client 1, and the initial application view and data are exactly the same.
Step8: Client2 → ServerController: [SharingFinal]. Client2 sends a SharingFinal message to the ServerController.
Step9: ServerController → Client1: [SharingComplement]. The ServerController updates the some meta information of VMPool, and sends a SharingComplement message to Client1, and Client1 will unlock its interaction.
In the term of application sharing, we intend to provide a completely duplicated application for the two clients. In CyberLiveApp, this requirement is met by cloning the VM in which the application runs. We will discuss the design and implementation of VM cloning in later section. When a Client Controller sends a VM cloning request to the Server Controller, the latter will send the VM id to VM Manager, who will return the new VM IP address after the cloning completes. In this new cloned VM, all the disk and memory data are the same as the original one, thus providing a duplicated application view.
4. System Examples and Simulations
Currently, we implemented a CyberLiveApp prototype system, and verified its viability through some evaluations. The core remote display protocol is based on the RFB implementation of MetaVNC 0.6.6.
4.1 Implementation Experience
4.1.1 Secure Sharing of a Single VM Desktop among Multiple Users
The MetaVNC allocates an unoccupied slot as the ClientID for the arrived client request according to the array vncClient *m_clientmap[MAX_CLIENTS]. Then, a vncClient object will be initialized for this connection, and its attributes are set according to the passed parameters. After that, -MetaVNC calls vncClient::Init method to pass the clientID instance pointer. Finally, this user will be added into the unauthorized user list of vncServer through m_clientmap[clientid] = client.
(1) Multi-user Authentication
In the authentication entry function vncServer::Authenticated (vncClientId clientid) of MetaVNC, it firstly gets the vncClient object from the unauthorized list, and removes it from the unauth list. If the user is the first vncServer client, a vncDesktop object is created by calling m_desktop->Init(this). Next, it allocates a vncBuffer *buffer = new vncBuffer (m_desktop), and sets this buffer by calling vncClient::SetBuffer to add this user into auth list.
Multi-user authentication feature is implemented in the vncClient.cpp file of MetaVNC project. There are two classes named vncClient and vncClientThread in vncClient.cpp. vncClient is used to send updated image to the client while vncClientThread is the server’s service thread which is used to receive message sent from the client. Authentication function is implemented in vncClientThread because there are lots of interactions with the client. CyberLiveApp implements the Authentication’s function in BOOL vncClientThread::InitAuthenticate() at line 209. We added a new security type named rfbSecTypeMultiUser. If the client supports this security type, it will be used; otherwise the default authentication method will be used. In the new authentication process, client returns the challenges and username to the server. When the server receives this username, it checks whether this user exists. If so, the server compares the received password hash with the hash value stored locally. If the two usernames and passwords match, the authentication is successful, then the client and the server will further negotiate to prepare for sending remote desktop. Some source codes are shown in Figure 8.
```
list[3] = (CARD8)rfbSecTypeMultiUser; //support for Multi-user extension
if (type == (CARD8)rfbSecTypeMultiUser) {
vnclog.Print(LL_INTINFO, VNCLOG("enabling Multi-user protocol extensions\n"));
m_client->m_protocol_tightvnc = TRUE;
m_client->m_protocol_multiUser = TRUE;
if (!NegotiateTunneling())
return FALSE;
if (!NegotiateAuthenticationForMultiUser(rfbSecTypeMultiUser))
return FALSE;
if (secType == rfbSecTypeVncAuth)
secType = rfbSecTypeMultiUser;
} switch (secType){
case rfbSecTypeNone:
vnclog.Print(LL_CLIENTS, VNCLOG("no authentication necessary\n"));
return AuthenticateNone();
case rfbSecTypeVncAuth:
vnclog.Print(LL_CLIENTS, VNCLOG("performing VNC authentication\n"));
return AuthenticateVNC();
case rfbSecTypeMultiUser:
vnclog.Print(LL_CLIENTS, VNCLOG("performing VNC multi-user authentication\n"));
return AuthenticateForMultiUser();
}
```
Figure 8: Part of source codes in InitAuthenticate()
(2) Proxy-based Windows Filtering
In the protocol of MetaVNC, the client thread in vncServer is used to receive requests from the clients and send update information to them, and this is one of the most predominant functionalities of vncServer. The vncClient class is responsible for sending data, which is implemented in the function vncClient::SendUpdate. The basic procedure is like this: firstly, vncClient calls SendRFBMsg, then calls the function SendCursorShapeUpdate to send the mouse shape update, and calls function SendCursorPosUpdate to send the mouse position update, and then calls function SendTpDecRgn to reset the region. Finally, vncClient calls SendRectangles to send the related data for updated rectangle.
The existing service threads can only request display update or send display update, which cannot meet the requirements of multiple user accesses. The major work of CyberLiveApp includes:
- Firstly, the access control module reads some configuration information, such as username, password and windows list. The information will be sent to other modules, and we define the functions of BOOL WritePrivateProfileString and DWORD GetPrivateProfileString to
modify the policy file.
- We can only get the window’s name from the authentication module, but we ultimately need to get the permitted window area. Therefore, we implement a transformation function in `SendUpdate` of `vncClient` object. Firstly, we get the application path name of the current windows on the desktop, and further get the windows rectangle area based on the application windows.
Two dialogs shown in Figure 9 are extended on metaVNC to set user permissions and windows permissions.

(3) Windows Region Hide
We need to deal with layer and overlap relations of multiple windows, so as to calculate the hidden areas. We implement this in the function `SendUpdate` of the `vncClient` object. Firstly, we use `GetForegroundWindow` function to get the handle of the top window, and we set a flag variable. If the top window is a hidden window, it will be easy. If the top window is not a hidden window, we should get the window’s size and remove this rectangle area from the hidden area with `tpRegion.SubtractRect`, so that user can view the top window which he is using.
There is a `vncRegion` object named `toBeSent` in the function of `SendUpdate()` in `vncClient.cpp`. We call `addRect` function in `vncRegion.cpp` to add the updated area into `toBeSent`. Then, we call `Rectangles()` function to get the `rectList` which includes the information of the rectangle area to be sent. Finally we call `SendRectangles(rectList)` function to send the update rectangle.
Figure 10 shows an example in which three clients connecting to the same virtual desktop and they gets different desktop views due to various permissions.

4.1.2 Application sharing for multiple VMs
In CyberLiveApp, the Client Controller manages multiple `vncViewer` processes, and the inter-process communication is based on Windows `COPYDATA` messages. We have used some Windows
predefined messages such as VM_CLOSE, VM_USER, VM_COPY-DATA, as well as messages VM_NEWCONNECTION, VM_CON_END, VM_KILL_ALL, VM_SEND_SUBS_HWND defined by ourselves. For instance, VM_NEWCONNECTION is a message to create a new VNC connection, while VM_CON_END is a message to close a VNC connection. Since the original vncViewer project does not provide a function for closing a specified connection, we add a function KillConnection(TCHAR *host, int port) in the file VNCviewerApp32.cpp, and it calls function kill() to close a specified connection. While on the side of Client Controller, we use DllImport("user32.dll") to send a COPYDATA message to the vncViewer process though SendMessage(int hWnd, int Msg,int wParam,int lParam).
VM Manager manages all VMs in the VM pool, and its main functions are to create, start or clone a specified VM with the support of the Libvirt library. Libvirt library is a Linux® API realizing the virtualization functions of Linux, it supports a variety of virtual machine monitors including Xen and KVM [12] (we use KVM in CyberLiveApp). Libvirt provides a mechanism of saving the memory mirroring of a live VM and starting a VM based on the memory mirroring. When the VM Manager wants to clone a VM, it will firstly saves the memory mirroring and disk mirroring of this VM, which is set to Suspend state during the cloning, and restoring it after the cloning. The procedure of VM cloning is shown as follows.
Step1: Copying the original VM disk mirroring file. The user can also configure a copy-on-write (COW) to reduce the image copying time.
Step2: Saving the VM memory mirroring.
Step3: Restarting the original VM based on the memory mirroring.
Step4: Modifying the network configuration and the disk mirroring path in the memory mirroring file.
Step5: Restoring a new VM based on the modified memory mirroring and copied disk mirroring file.
Figure 11 shows some snapshots of CyberLiveApp for application migration and sharing. When we start a Client Controller, it will display an icon on the task bar, and provide an easy way to subscribe for applications. All of these applications are maintained in the VM pool, after subscription, the Client Controller will automatically create shortcuts for these subscribed applications in the Windows Start menu. When a user sponsors to migrate or share a running application with another client, he firstly selects the target client from the online client list registered on the Server Controller. After migration, the application presentation streaming is closed in the sponsor client and redirected to the migration target client. However, after sharing, the presentation streaming will not be closed in the sponsor client, and the sharing target client will get an application streaming from the cloned VM. Therefore, they get the same application and user data at the same time within different clients, but then they can run independently.
4.2 Simulation Results
We next present an experimental study of the CyberLiveApp prototype. We examine the following performance aspects: (a) overhead of multiple users’ authentication in CyberLiveApp, (b) network traffic of multiple users’ access for a VM, (c) cost of live application migration, and (d) cost of VM clone for application sharing. The simulation scenarios are shown in Figure 12.
Simulation Environment Setup: The Server Controller, Client2 and Client3 running on machines with Intel(R) Core(TM) 2 CPU 6400 @2.13GHZ, 4GB RAM, Ubuntu 9.04 (Linux 2.6.28) operating system. Client1 is an IBM T61 computer with an Intel(R) Core(TM)2Duo CPU 2.2GHz, 4GB RAM, Windows 7 operating system. These machines are with 100Mbps Internet connection. Client1 and Client2 are owned by User1. Unless specified separately, each experiment is executed five times and the average value is chosen.
4.2.1 Desktop Sharing for a VM
Simulation 1: In this experiment, we measure the total time of VNCServer update for multi-user access control in CyberLiveApp. We simulate multiple clients on the three computers to connect to the VNCServer on the side of ServerController. The total VNCServer update time is recorded by increasing the number of concurrent clients from 1 to 5.
The experimental results are shown in Figure 13, which shows that the overall VNCServer update time almost increases linearly with the number of concurrent clients, and multi-user desktop access for a VM in CyberLiveApp is scalable. The bar chart also indicates that the VNCServer update time in CyberLiveApp is higher than in MetaVNC, but the overhead incurred by the multi-user authentication mechanism is less than 20%.
Simulation 2: In this experiment, we want to measure the network traffic impact due to Windows actions. We use a software macro to run two types of windows operations, in which one is moving the windows quickly, and another is maximizing/minimizing windows. We respectively record the total traffic in a period of time on MetaVNC and CyberLiveApp, where the total network traffic is recorded with Wireshark.
The experimental results are shown in Table 5 and Figure 14. We can see that these two systems almost have the same network traffic under the two different types of operations. Moreover, the frequent updating of a window will dramatically increase the network traffic. In all, the traffic overhead due to multi-user authentication in CyberLiveApp is fewer.
Table 5: Network traffic comparison between MetaVNC and CyberLiveApp
<table>
<thead>
<tr>
<th>System</th>
<th>Operation</th>
<th>Moving Windows</th>
<th>Maximizing/Minimizing Windows</th>
</tr>
</thead>
<tbody>
<tr>
<td>MetaVNC</td>
<td>Moving Windows</td>
<td>15781 KB</td>
<td>1151 KB</td>
</tr>
<tr>
<td>CyberLiveApp</td>
<td>Moving Windows</td>
<td>15990 KB</td>
<td>1173 KB</td>
</tr>
</tbody>
</table>
4.2.2 Application migration and clone for multiple VMs
The two simulations below mainly focus on the time cost for application migration or sharing. We analyzed and compared the time consumed for application’s migration or sharing under different configurations.
Simulation 3: In this experiment, we use two clients to simulate a scenario of live application migration. If a client has a public IP address, the total migration time is similar to the interpretation of Step 2 in Figure 6. However, in a cloud computing environment, the client generally does not have a public IP address, so the client should use a query mechanism to get the notification of ServerController. We test the application migration time for this scenario under different query intervals.
The experimental results are shown in Figure 15 and Figure 16. Figure 15 shows the migration time tested for 10 times, and the migration time is less than 200 ms if the query interval time is 100 ms. Figure 16 shows the average migration time for different query intervals tested for 10 times, and the application migration time almost increases linearly with the time of query interval.
Simulation 4: In this experiment, we also use two clients to simulate a scenario of live application sharing. The environment is the same, and the client does not have a public IP address. Based on our designing, the sharing time will add an extra VM cloning time compared with the application migration scenario. Therefore, we mainly test the VM clone time under different size of VM image.
When a VM is cloned, VM Manager needs to save the VM’s memory mirroring, copy the disk mirroring and restart the VM. Therefore, the clone time consists of three parts:
• $T_1$: Time for saving the memory mirroring file.
• $T_2$: Time for copying VM disk COW (copy-on-write) file.
• $T_3$: Time for restarting the VM.
The selected Windows XP VM memory is 512M in our experiment. After twenty times of repeated tests, we concluded the average time cost for $T_1$ is 9.308s and $T_3$ is 0.879s. The time of $T_2$ is related to the size of VM disk mirroring file. We tested the time cost for copying COW files in size of 64M, 128M, 256M, 512M and 1024M respectively, and the average time cost is shown in Table 7 and Figure 16 below.
<table>
<thead>
<tr>
<th>Table 6: Average Time Cost for copying disk mirroring file in different sizes</th>
</tr>
</thead>
<tbody>
<tr>
<td>Size</td>
</tr>
<tr>
<td>T2b</td>
</tr>
</tbody>
</table>
As shown in Figure 17, $T_2$ is increased linearly with the increasing of size of COW disk mirroring file. In summary, the virtualized application’s sharing time is mainly related to the following two factors: notification query time interval in the Client Controller and the size of disk COW image of VM.
5. RELATED WORK
Desktop virtualization technology provides access to cloud computing environments from anywhere in the world, on whatever operating systems. It has become an irresistible trend, and is ranked the second among the ten hottest technologies selected by InfoWorld in 2010 [8]. Forrester predicted: starting from 2010, the desktop virtualization technology will be gradually adopted by large enterprises.
Microsoft has launched the Client-Hosted Desktop Virtualization and the Server-Based Desktop Virtualization. The latter virtualization technology allows the separation of software execution and presentation by adopting some remote desktop protocols, such as RDP. Virtual Desktop Infrastructure (VDI), a desktop delivery model developed by Microsoft, allows users to access desktops running in the datacenter. VMware View is developed by VMware to achieve the isolation of operating system, applications and user data, which avoids problems brought by the tightly-coupled architecture. Citrix [6] also launched XenDesktop to achieve the desktop virtualization. A FlexCast technology is used to meet the different demands of desktop environment for different users in an enterprise. These produces break the traditional tightly-coupled software execution environment, and provide flexible desktop access approaches. However, they do not meet the demands for live application sharing and migration or secure sharing of a virtual desktop. Besides, these products also face a compatibility problem under different operation systems.
The reprehensive projects on desktop virtualization include THINC [8][12][13], Citrix XenDesktop [6][15], Microsoft Terminal Service [6] and some VNC systems [5][14]. THINC is a remote display system architecture for high-performance thin-client computing in both LAN and WAN environments. THINC enables higher-level graphics primitives used by applications to be transparently mapped to a few simple low-level primitives that can be implemented easily and efficiently. Citrix provides full VDC (Virtual Desktop Computing) using their ICA protocol in parallel with Ardence image and provisioning manager and desktop server hypervisor. Recently, XenClient extends the benefits of desktop virtualization to mobile users offering improved control for IT with increased flexibility for users. RDP enhancements in Windows Server 2008 and in recent MS client Operating Systems will also address some of the problems identified in relation to video and other graphics-intensive applications over RDP. VNC [4][16][17][18] is based on the PRB protocol which is a simple and powerful remote display protocol. Unlike other remote display protocols such as the X Window System and Citrix’s ICA, the VNC protocol is totally independent of operating system, windowing system, and applications. RealVNC [14]proposes different remote display solutions for the client access, the software is executed at remote servers; user client just gets the presentation desktop. This solution only focuses on the
separation of execution and presentation, but does not involve the software deployment and execution related fields. MetaVNC [5] pursues a remote desktop environment that users can control applications on different hosts seamlessly. MetaVNC is a window aware VNC, and it merges windows of multiple remote desktops into a single desktop screen.
Besides, some products and research work emerged to address the software service requirements for mobile equipment in recent years. Microsoft Application Virtualization (App-V, named SoftGrid previously) is a core component of the Microsoft desktop optimization pack for software assurance, it transforms applications into centrally managed virtual services that are never installed and do not conflict with other applications. Progressive Deployment System (PDS) [19], Yang’s work [20] and FVM [21] employee OS-level virtualization technology to reduce the deploying, updating and management labor cost of IT as well as the execution environment isolation. All the virtual software packages are managed at central server sites. When a user wants to use some software, the software package will be delivered to the local machine in a streaming way. MobiDesk is a mobile virtual desktop computing hosting infrastructure, and it transparently virtualizes a user’s computing session by abstracting underlying system resources in three key areas: display, operating system, and network. It provides a thin virtualization layer that decouples a user’s computing session from any particular end-user device, and moves all application logic to hosting providers.
In summary, there are some desktop virtualization approaches to providing remote access to a cloud computing environment. However, these approaches only focus on displaying the remote desktop, but do not consider flexible collaboration for live application sharing and migration.
6. CONCLUSION
In a cloud computing environment, users can utilise SaaS subscriptions instead of traditional software vendors perpetual-use licenses. We have developed a dynamic prototype system named CyberLiveApp to support application sharing and migration on-demand between multiple clients. CyberLiveApp provides the two key services: secure multi-user sharing service for virtual desktop of a VM and multi-VM application sharing and migration. We have designed a mechanism for tracking windows operation events and hidden window areas are rapidly computed. To filter various windows, a proxy-based filtering mechanism is used to deliver a custom desktop to different users. To support multi-VM applications sharing, we have developed a presentation streaming redirection approach for virtual desktops; an application state consistency algorithm and two protocols are proposed. All of these methods have been implemented in CyberLiveApp based on extended MetaVNC and virtual machine monitor KVM. We have experimentally verified that these approaches are effective and useful. Several extensions to this work are being planned for future development. We are currently developing a virtualization-based software as a service platform, and we are exploring methods to integrate the CyberLiveApp into cloud-based computing environments for flexible collaboration.
Acknowledgment
The authors gratefully acknowledge the anonymous reviewers for their helpful suggestions and comments, and thank Shuang Yang, Yanmin Zhu, Liang Zhong, and Jin Li for their helps on this work. This work is partially supported by Program for New Century Excellent Talents in University 2010, National Nature Science Foundation of China (No. 60903149), China 863 Program (No. 2009AA01Z419), and China 973 Fundamental R&D Program (No. 2011CB302603).
REFERENCES
|
{"Source-Url": "http://derby.openrepository.com/derby/bitstream/10545/214399/1/CyberLiveApp%2520A%2520Secure%2520Sharing%2520and%2520Migration%2520Approach%2520for%2520Live%2520Virtual%2520Desktop%2520Applications%2520in%2520a%2520Cloud%2520Environment.pdf", "len_cl100k_base": 11318, "olmocr-version": "0.1.50", "pdf-total-pages": 20, "total-fallback-pages": 0, "total-input-tokens": 58334, "total-output-tokens": 13453, "length": "2e13", "weborganizer": {"__label__adult": 0.00035309791564941406, "__label__art_design": 0.0005526542663574219, "__label__crime_law": 0.0004515647888183594, "__label__education_jobs": 0.0024280548095703125, "__label__entertainment": 0.0001767873764038086, "__label__fashion_beauty": 0.0001633167266845703, "__label__finance_business": 0.0005974769592285156, "__label__food_dining": 0.0003037452697753906, "__label__games": 0.0010585784912109375, "__label__hardware": 0.004192352294921875, "__label__health": 0.0005278587341308594, "__label__history": 0.0004105567932128906, "__label__home_hobbies": 0.00013506412506103516, "__label__industrial": 0.0004146099090576172, "__label__literature": 0.0003383159637451172, "__label__politics": 0.0002435445785522461, "__label__religion": 0.00040340423583984375, "__label__science_tech": 0.2108154296875, "__label__social_life": 0.0001983642578125, "__label__software": 0.1768798828125, "__label__software_dev": 0.59814453125, "__label__sports_fitness": 0.00021469593048095703, "__label__transportation": 0.00045871734619140625, "__label__travel": 0.0002397298812866211}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 57601, 0.02369]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 57601, 0.10444]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 57601, 0.8679]], "google_gemma-3-12b-it_contains_pii": [[0, 3742, false], [3742, 8118, null], [8118, 11785, null], [11785, 14678, null], [14678, 16239, null], [16239, 20272, null], [20272, 23327, null], [23327, 26797, null], [26797, 29907, null], [29907, 32372, null], [32372, 35780, null], [35780, 37786, null], [37786, 40721, null], [40721, 42416, null], [42416, 44751, null], [44751, 46075, null], [46075, 49414, null], [49414, 53333, null], [53333, 57577, null], [57577, 57601, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3742, true], [3742, 8118, null], [8118, 11785, null], [11785, 14678, null], [14678, 16239, null], [16239, 20272, null], [20272, 23327, null], [23327, 26797, null], [26797, 29907, null], [29907, 32372, null], [32372, 35780, null], [35780, 37786, null], [37786, 40721, null], [40721, 42416, null], [42416, 44751, null], [44751, 46075, null], [46075, 49414, null], [49414, 53333, null], [53333, 57577, null], [57577, 57601, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 57601, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 57601, null]], "pdf_page_numbers": [[0, 3742, 1], [3742, 8118, 2], [8118, 11785, 3], [11785, 14678, 4], [14678, 16239, 5], [16239, 20272, 6], [20272, 23327, 7], [23327, 26797, 8], [26797, 29907, 9], [29907, 32372, 10], [32372, 35780, 11], [35780, 37786, 12], [37786, 40721, 13], [40721, 42416, 14], [42416, 44751, 15], [44751, 46075, 16], [46075, 49414, 17], [49414, 53333, 18], [53333, 57577, 19], [57577, 57601, 20]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 57601, 0.125]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
a0a155fc3182b389efb7bf7fd570dc4439f5dc77
|
Lecture Notes on Software Process Improvement
Laurie Honour Werth
February 1993
Lecture Notes on Software Process Improvement
Laurie Honour Werth
University of Texas at Austin
Approved for public release.
Distribution unlimited.
Table of Contents
Preface iii
1. Overview of Software Process and Quality Improvement 1
1.1. Fundamental Process and Process Management Concepts 1
1.2. Historical Background 3
2. The Software Engineering Institute Capability Maturity Model 5
2.1. Uses of the CMM 5
3. Capability Maturity Model Practices 8
4. Components of the CMM 9
4.1. Maturity Level 10
4.2. Key Process Areas 11
4.3. Key Practices 12
4.4. Maturity Questionnaire 12
5. Conclusions 13
Bibliography 15
Appendix A: Classroom Experiences with Software Process 19
Appendix B: Software Process Assessment Questionnaire 23
Attachments 31
List of Figures
Figure 1. Five levels of software process maturity [Weber91] 2
Figure 2. Common steps in SPAs and SCEs 6
Figure 3. Capability maturity model (CMM) structure 9
Figure 4. Example of CMM structure 10
Figure 5. Results of GAO survey of software contracts 13
List of Tables
Table 1. Shewart improvement cycle [Deming86] 3
Table 2. Comparison between SPA and SCE 7
Table 3. Key process areas (KPAs) by maturity level [Paulk91] 11
Preface
Software process improvement is not usually covered in standard software engineering textbooks. However, because it is a topic of great interest to the software industry, both faculty and students should be familiar with it. The goal of this package is to provide the basis for an introductory 30 to 60 minute lecture on the software process and its improvement.
The material in the main body of the document is intended primarily for instructors. In conjunction with the student-oriented document described below, it provides technical information from which an instructor can prepare a lecture. Two appendices provide additional information for instructors. Appendix A is a brief description of the use of the software process material in a university software engineering class at the University of Texas at Austin. This classroom example might be used as an illustration for students to relate the process concepts to their own software development work. Appendix B presents the Software Engineering Institute's (SEI) process maturity questionnaire from which instructors and students can gain some insight into how a software process is assessed.
A document titled “Introduction to Software Process Improvement” is attached; it is intended for students. It describes the SEI capability maturity model (CMM), the maturity questionnaire, and SEI procedures that are based on the questionnaire: software process assessment and software capability evaluation. Instructors may photocopy this document and distribute it to students to augment their textbook. (This document is also available electronically in PostScript format via the Internet, from which students can print their own copies. For details, send a request to Internet address education@sei.cmu.edu.)
Finally, the package contains overhead transparency masters that instructors may find useful in delivery of their lectures.
How to Use the Materials
These materials are introductory in nature, and they assume that the student audience is a beginning software engineering class. However, these materials may also be useful to prepare a talk for computer professionals and managers, or to prepare a general professionalism talk for computer science and engineering students.
Although the main body of this package is intended for instructors, it may be distributed to students if the instructor desires. Industry audiences, for example, may want to see the additional CMM material or even the questionnaire from Appendix B. However,
many of the maturity questionnaire concepts will not be familiar to college students unless they have had work experience or they have already had this material in class, so students may become overloaded by the terminology contained in the questionnaire and other supplementary material.
In the future we hope to add advice on applying the process improvement concepts to a software engineering class project, as well as additional materials on software process metrics.
References
The student document does not contain a bibliography or citations because we have assumed that undergraduate students are unlikely to seek additional reading unless specifically assigned by the instructor. The bibliography in the instructor's document does contain all the references. References in the student document to an author's name can usually be found under that author's name in the instructor's bibliography. The surveys of software process maturity levels mentioned on page 4 may be found in [Humphrey89b]. References for the process improvements at Hughes Aircraft, Raytheon, and NASA are in [Humphrey91], [Dion92], and [Humphrey92], respectively.
Lecture Notes on
Software Process Improvement
1. Overview of Software Process and Quality Improvement
Today, concern for quality has become an international movement. England requires quality programs to be certified and audited. Europe will soon offer certification for software development companies that meet the standards described in ISO 9000 (International Standards Organization number 9000) [Arter92]. Japan has awarded the Deming Prize for years [Masaaki86].
In the United States, the Department of Commerce and NASA give major awards, such as the highly coveted Malcolm Baldridge Quality Award [Garvin91], for quality improvement. Many companies have begun to implement quality improvement or total quality management (TQM) programs throughout the company, not just in software development.
1.1. Fundamental Process and Process Management Concepts
Process is a term used to describe the people, methods, and tools used to produce software products. Improving the quality of the product is believed to be based on improving the process used to develop the product. Because software is intangible and not subject to the same physical constraints as hardware and many manufacturing products, defining the software process can be difficult.
Software engineering process is defined as the system of all tasks and the supporting tools, standards, methods, and practices involved in the production and evolution of a software product throughout the software life cycle. Process-driven software development implies that organizational process is adapted to meet project and product quality goals. Software development should be guided by an explicit process, with environment and tools integrated to support this process. Process definition is a prerequisite to process improvement. Defined processes promote collaboration and teamwork by making activities, roles, and dependencies visible. Process management supports improvement of the defined process through measurement and feedback.
Current implementations of process management combine three steps: definition, control, and improvement [Card89]. Process definition provides an exact description for the work to be performed. The current process is used as a baseline against which changes will be compared. Process control works to keep significant quality parameters within some predefined limits. Process improvement involves analyzing problems for root causes.
causes and working to correct them. *Product* quality is seen as a result of continuously improving *process* quality. A process is said to be under *statistical control* if its future performance can be predicted within established statistical limits [Deming86].
Watts Humphrey incorporates these concepts into a software-oriented model in his book *Managing the Software Process* [Humphrey87]. Based on work begun at IBM, this model adapts the ideas to software development, providing five *maturity levels*, shown in Figure 1, which define an effective, staged progression toward a statistically controlled software process. Humphrey's work became the foundation of SEI software process improvement and the SEI capability maturity model (CMM) [Paulk91, Paulk93].
The basic ideas of statistical process control have been known and practiced in other areas for at least 60 years. However, these methods represent significant change for most businesses and institutions. Resources must be provided to allow each organiza-
tion to adapt the ideas to their own environment gradually, over time. This is not a quick fix or a band-aid approach to improving software quality.
The capability maturity model defines the five stages or levels through which a company must move in order to improve process and resulting product quality. Each level of the model is the foundation for the next, so it is important not to try to move too quickly or to skip levels. Care must be taken that measures not be misused, either to evaluate individuals or to compare dissimilar projects. Still, the benefits experienced by organizations that have applied these software improvement methods have outweighed the costs. The productivity and quality improvements can help us retain our lead in the global software marketplace.
1.2. Historical Background
Walter Shewart, a physicist, worked at AT&T Bell Labs in statistical process control in the 1930s. W. Edwards Deming based his work on the Shewart improvement cycle (a sequence of four steps that are repeated indefinitely; see Table 1), which he successfully adapted to Japanese industry after World War II. Current Japanese management strategy continues to focus on quality improvement because the Japanese believe that the productivity and profit improvements will follow naturally. Many companies are applying the ideas of quality or process improvement across their organization. Software process improvement is the application of these concepts to software development.
<table>
<thead>
<tr>
<th>1. Plan</th>
</tr>
</thead>
<tbody>
<tr>
<td>Define the problem</td>
</tr>
<tr>
<td>State improvement objectives</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>2. Do</th>
</tr>
</thead>
<tbody>
<tr>
<td>Identify possible problem causes</td>
</tr>
<tr>
<td>Establish baselines</td>
</tr>
<tr>
<td>Test changes</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>3. Check</th>
</tr>
</thead>
<tbody>
<tr>
<td>Collect data</td>
</tr>
<tr>
<td>Evaluate data</td>
</tr>
</tbody>
</table>
<table>
<thead>
<tr>
<th>4. Act</th>
</tr>
</thead>
<tbody>
<tr>
<td>Implement system change</td>
</tr>
<tr>
<td>Determine effectiveness</td>
</tr>
</tbody>
</table>
Table 1. Shewart improvement cycle [Deming86]
Shewhart's *Plan-Act-Check-Do* paradigm is the basis for the SEI process improvement program. Shewhart's paradigm, applied to both the software product and process, generally consists of the following activities:
**Plan**
The SEI capability maturity model is a general framework or plan for developing five increasingly improved levels (initial, repeatable, defined, managed, and optimizing) of software *process maturity*. Because the CMM is designed to be generic, each organization must customize its process improvement plan for its own application(s), environment, and company organization. The five levels are designed as a logical progression, so each level must be achieved, in order, from one to five. It is not possible to skip levels.
**Act**
Because software is not produced by a manufacturing process, software designers must both strive to meet the users’ functional requirements for the *product* and design for correct implementation and easy maintainability. There will usually be many examples of process improvements that are needed. Efforts should focus on high-leverage points, and action plans to correct the defects must be evaluated for effectiveness. Software tools to automate and standardize the process may aid in institutionalizing improvements, but tools are not a cure-all.
**Check**
Software inspections and peer reviews are the major *product* control mechanism used. Quantifiable inspections results such as change requests provide the foundation for measurable process control and improvement. Audits are the most usual *process* verification process. Auditors need to examine not only whether the standards, procedures, and tools are adequate, but they also to see how well the project is following the prescribed process plans.
**Do**
Software quality control is often specified both by the customer acceptance criteria in the contract or requirements specification and by whether the *software product* meets written standards. Software measures are used to measure product quality in a quantifiable way. The SEI has already published a *core set of measures* [Florac92] which can be used as a basis and enhanced by the organization as needed, though these measures are still under active development. The most common *process* quality control approach is tracking actual against expected performance. Causes for significant deviation from the plan are found and corrected. In the later stages of the maturity model, the organization strives to actively prevent problems and errors rather than to wait to detect them in the later phases of the software development project.
2. The Software Engineering Institute Capability Maturity Model
The basic concept of a maturity framework was inspired by Crosby's quality management maturity grid and its five evolutionary stages in adopting quality practices [Crosby79]. This maturity framework was adapted for software by Radice and others at IBM [Radice85, Radice88]. Humphrey brought the maturity framework from IBM to the SEI in 1986, adding the concept of maturity levels. Various aspects of the maturity model are described in SEI technical reports [Fowler90, Weber91, Florac92] and Humphrey's book [Humphrey87].
Process management fundamentals are firmly grounded in science and engineering principles. They have been strongly influenced by the work on statistical process control developed by leaders such as Deming and Juran [Deming86, Juran88]. The SEI method incorporates a growing body of experience with techniques for cost and size estimation, configuration management, and other software quality improvement approaches. The field of technology transfer has evolved to the point that it now provides operative methods for helping organizations adapt to technological changes. This work has been combined to provide a foundation for learning about and improving the software development process.
The software field is young, and more modern tools and methods will evolve over time. Software organizations and applications are far too diverse to fit easily into a single process model. The SEI maturity model provides a framework as well as a method for evaluating and improving the software engineering process within an organization. The guidelines do not mandate particular methodologies, tools, or organizational structure.
2.1. Uses of the CMM
The capability maturity model, developed by the Software Engineering Institute, is designed to help both development organizations and customers (government organizations or companies who acquire software). Software organizations need to understand the quality of their software process and how to improve it. Organizations contracting for software need ways to evaluate a potential contractor's capability to carry out the work.
The CMM has four intended uses [Weber91] to help organizations improve their software process capabilities:
1. Identify improvements
2. Identify risks in selecting contractors
3. Implement a process improvement program
4. Guide definition and development of the software process
Over the last few years, the SEI has expanded and refined the CMM with input from many professionals from both government and industry. The current version [Paulk93a, Paulk93b] is based on several years' experience applying the model to soft-
A software process assessment is an in-house determination, primarily of the weaknesses of the software process in an organization as a whole. It is an internal tool that an organization can choose as a part of an overall program for improving its ability to produce high-quality products on time and within budget. The objectives of the SPA method are to (1) identify strengths, weaknesses, and existing improvement activities on which to base an organization-wide improvement effort and (2) to get organizational buy-in to that effort. The method is used to help an organization identify key areas for improvement, begin to baseline its software process, and initiate improvements.
A software capability evaluation is an independent evaluation of an organization's software process as it relates to a particular acquisition. It is a tool that helps an external group (an “acquirer”) determine the organization's ability to produce a particular product having high quality and to produce it on time and within budget. The objective of the SCE method is to identify strengths, weaknesses, and existing improvement activities in a supplier's software process that best indicate the risk associated with using that supplier for a particular software acquisition. The method is used to identify software risks, help in mitigating these risks, and motivate initiation of improvement programs.
The common steps in SPAs and SCEs are summarized in Figure 2. Additional similarities and differences between SPAs and SCEs are shown in Table 2 and are elaborated in [SEI92].
The SEI maturity questionnaire (see Appendix 2) is used for both SPA and SCE, but there are differences in how it is used in each method. These differences include the objectives, the make-up of the site visitation teams, the criteria for determining scope and for defining findings, and the ownership of the results. In view of these differences,
the outcomes of assessments and evaluations are not likely to be interchangeable or directly comparable. The SCE team may conclude that a particular weakness has low risk associated with it for the acquisition and therefore discount it (for example, subcontract management in an acquisition that may not involve subcontracts), while a SPA team might recommend corrective action as a high priority for the same weakness (since other projects involve subcontractors). Both views would be valid for their respective purposes.
There is considerable interest in the software community in using assessments and in the concept of continuous quality improvement that forms the basis of the methodology. The SEI has licensed independent training and consulting companies (SPA associates) to provide training and assistance in applying the SPA method to a particular environment. Software process conferences, software engineering process groups in companies, local software process improvement network (SPIN) groups, and tool support are beginning to emerge.
3. Capability Maturity Model Practices
The capability maturity model describes the characteristics of a mature software process. The model also shows how an immature software process can evolve into a well-managed mature one. The overall structure of the model is shown in Figure 3. Major components of the CMM, as shown in the figure, include:
- **Maturity level:** five levels or plateaus on the path to a mature software process.
- **Process capability:** capability refers to expected results, that is, what can we predict from this organization’s next project based on their current process capability?
- **Key process areas:** a cluster of related activities that, when performed collectively, achieve a set of goals considered important for enhancing process capability. These each contain common features.
- **Goals:** the high-level objectives to be achieved by the key practices for that specific key process area.
- **Key practices:** the policies, procedures, and activities that most significantly contribute to the institutionalization and implementation of the key process area.
- **Questions:** yes/no questions that sample the key practices.
Figure 4 shows an example, or a particular instantiation, of the parts of the CMM structure to illustrate the relationships among the parts. In this figure, one sees the relationship between the components (maturity levels, key process areas, key practices, and questions). At the repeatable maturity level, in the key process area of software project planning, one of the key practices is to estimate project size. Thus, a typical question from the maturity questionnaire might be “Do you use a documented procedure to estimate software size?”
4. Components of the CMM
Each of the major components of the capability maturity model is described in more detail below. The SEI technical report, *Key Practices of the Capability Maturity Model* [Weber91], elaborates the key practices that correspond to each maturity level; these practices can be used to guide both software process improvements and capability evaluations.
4.1. Maturity Level
Each *maturity level* in the CMM indicates a certain software *process capability*, describing how the software organization is expected to function: initial or ad hoc, repeatable, defined, managed, or optimizing. Each level represents an improvement in the software process. An organization's software capability can be improved by advancing through
these five stages or levels. Each maturity level allows management to gain a better understanding of the software process. Each level provides the foundation necessary to meet the goals of the next highest maturity level. Each maturity level has been decomposed into parts or key process areas as shown in Figures 3 and 4.
4.2. Key Process Areas
Key process areas (KPAs) identify areas on which an organization should focus in order to improve its software development processes. Each key process area is made up of key practices that contribute to achieving the goals of the KPA. Goals can be used to resolve whether an organization or project has adequately implemented a key process area. Goals signify the scope, boundaries, and intent of each key process area.
Key process areas are building blocks—fundamental activities for organizations trying to improve their software process. Other process areas exist, but these were selected as particularly effective in improving process capability. Each key process area is unique.
to a single maturity level. Table 3 shows the key process areas required for each maturity level. Note that there are no KPAs for the first or “initial” level.
4.3. Key Practices
*Key practices* are the lowest level, specific details of the CMM. Key practices define each key process area in Table 3 by specifying policies, procedures, and activities that contribute to satisfying its goal. They are a working definition of the key process area.
Key practices provide a link between the CMM and the maturity questionnaire. Specific questions relate to specific key practices. Industry experience and empirical studies were used to identify the key practices chosen by the SEI. Each key practice describes, but does not mandate, how that practice should be performed. The SEI technical report previously cited [Weber91] provides extensive definitions and guidance on the interpretation of key practices.
4.4. Maturity Questionnaire
The *maturity questionnaire* consists of questions about the software process that sample the practices in each key process area. (See the example question in Figure 4). All the questions used in the maturity questionnaire can be found in Appendix B.
The maturity questionnaire is a springboard for an assessment or evaluation team’s visit. The CMM provides a hierarchical structure that guides the team in investigating an organization’s software process. Answers to the questions identify process strengths and weaknesses in terms of key process areas. Questions in the maturity questionnaire are designed to determine the presence or absence of the various key practices. Questions are not open-ended, but are intended to obtain a quantified result from the following answers: yes, no, don’t know, and not applicable. A more detailed and open-ended questioning process begins after the responses to the maturity questionnaire have been analyzed.
The SCE team identifies strengths, weaknesses, and improvement activities that they consider to be most relevant to performance on the acquisition contract. A group in the acquisition agency then transforms the findings into acquisition risks and/or technical ratings, which, along with other criteria, the agency can use to select a source or monitor a contract.
The SPA team also analyzes the questionnaire data to determine the current software process maturity level, identify key findings (that is, determine what will impede capability to produce quality software), and note strengths the organization can build upon. The team presents the results to senior management and, often, to the entire organization that was assessed. The team often enlists the aid of others within the organization to make recommendations for process improvement actions. An action planning group (often a software engineering process group, under the guidance of a management steering committee) develops the strategies for accomplishing long-term process improvement and determines what improvements are achievable within a specific time...
frame. They work with many others in the organization to create an action plan and implement it.
5. Conclusions
While great strides have been made in developing software engineering methodologies and techniques, companies have been unable to consistently produce high-quality software. Stories of software problems appear on a regular basis, for example [Neumann92]. Large amounts of money have been spent on projects that have produced little usable software, as illustrated graphically in the results of a General Accounting Office (GAO) survey shown in Figure 5.

Success projects have been largely based on individual or dedicated team effort rather than on software development methods [Humphrey89a]. We have come to understand that benefits of better methods and tools cannot be realized in undisciplined projects. In the typical "firefighting" mode in which immature organizations function, software quality is compromised to meet unrealistic schedules.
Process improvement ideas for software are similar to current business practices based on total quality management, popularized, beginning ten years ago, by books such as *Quality is Free* [Crosby79] and *In Search of Excellence* [Peters82]. Many of the process management and quality improvement concepts have been adapted from the work statistical process control done by W. Edwards Deming and Joseph Juran [Deming86, Juran88, Juran89]. The SEI developed the capability maturity model, based on this earlier work by quality experts, as a framework for evaluating and guiding software process improvement. As an organization increases in maturity, the difference between targeted and actual results decreases across the project. Development time and cost decrease, while productivity and quality increase. With an objective basis for measuring
quality and setting improvement priorities, time and costs become more predictable as rework and errors are removed from the system [Humphrey89a].
Companies report that improvements in work environment and motivation have turned out to be an even greater benefit than the cost saving that resulted from using the CMM [Henry92, Mays90]. (See also Table 2 in the attached student document *Introduction to Software Process.*) In a mature organization, everyone knows the processes and their own responsibilities. Workers become empowered by their involvement in developing the process descriptions and by the ability to update processes as needed. Internal processes of projects become more visible. Managers know current project status and can monitor quality and customer satisfaction.
Software process issues become even more important in the classroom, where the students are inexperienced. Using the CMM role definitions and job descriptions in classes can ease students’ transition to working as a cohesive software engineering team in a professional environment. They have a better appreciation of why software development can be so difficult, and they have a meta-model for reducing this complexity. Even without applying the ideas on the class project, students can gain a clearer idea of the complications inherent in developing large software products and how they can be managed. Knowledge of software process concepts has proved helpful to students in talking to software company recruiters as well.
Knowledge transferred from the university to industry should begin to include process material in software engineering classes. The importance of software process is vital information needed to prepare computer science students for the challenges of modern software technology.
Bibliography
Appendix A: Classroom Experiences with Software Process
Introduction
Various earlier efforts by the author to incorporate software engineering techniques into a course at the University of Texas at Austin have been previously described [Werth88, Werth89, Werth90, Werth91]. Over the years, using higher level software such as MacApp, HyperCard, and Oracle in a Macintosh II laboratory, we developed tools for the software engineering class itself to provide support for testing, costing, version control, analysis and design, software process assessment, and others. A successful collaboration with a local company provided valuable experience for students using industry-strength CASE tools. In 1992 we explored the area of software process improvement, both by teaching the foundations and by applying it directly to the class project.
Our reasoning was that if software process improves the commercial software development environment, then the application of software process techniques should also strengthen the classroom environment. Two positive effects could be expected. First, successful experience with the techniques on the class project would result in students even better prepared to meet the challenges of modern software technology. Second, the use of quality improvement techniques, applied to the software engineering project as currently taught, would be a step in the direction of improving academic education as suggested, for example, by Peter Denning [Denning92].
Course Description
Starting with Tomayko’s model [Tomayko87] in the spring 1992 semester, we began to develop process plans and tools for the class project. This project provided an early design and prototype for a metrics tool to collect and analyze defect reports, as described by the Software Engineering Institute (SEI) [Florac91]. In the fall semester, students employed these plans and tools to complete the design and implementation of Dante’s Defect Tracker.
The spring effort was based on disjoint subteams for design, implementation, testing and evaluation, documentation, configuration management, and quality assurance. In the fall, we integrated the process teams within the technical teams, providing a matrix management scheme. Each of the four technical teams (design, implementation, testing, and documentation) elected one person to each of the following process teams: project administration, system administration, configuration management, quality assurance, and documentation specialists. This new organization seemed to match more closely the roles that evolved during the spring semester’s effort, as well as incorporate
natural liaison and communication of process procedures within the technical teams. Because of lack of experience, undergraduates find it easier to monitor and impose control when they are members of both the technical and the process teams.
Technical teams met and developed documents appropriate to their role: functional and design specifications by the design team; software product with programmer's manual by the implementation team; test plans, test cases, results, and reports by test and evaluation; and the user's manual(s) by the documentation team. Process teams developed or enhanced existing plans to describe their process function and wrote process legacies to pass along their increased understanding of their process role(s) for future teams.
Each Friday, at the status meeting held during class, one technical team presented their work, while process teams made announcements and reported progress. Everyone in the class acted as either the status meeting moderator or recorder at some point during the course. Agendas and minutes were sent by e-mail to class members. Status meetings worked very well, greatly improving communication and student process learning, as well as reducing the instructor workload. Our industry “user,” Herb Krasner, attended these meetings as his schedule permitted.
Walkthroughs or reviews were held during the week, often after class on Monday or Wednesday, in preparation for the Friday presentation. Attendees included the presenting team and appropriate representatives from related technical and process teams.
The configuration control board (CCB) consisted of each team's configuration management representative, along with the head of quality assurance, the external auditor (a teaching assistant), and CEO (the instructor). Overall project management and coordination gravitated to the CCB meetings, held in the lab before class. Since other teams' members were often working in the lab during this time and all teams were represented, many questions and issues were resolved quickly and easily. Results were announced or further discussion took place immediately after the CCB meeting, during class.
Lessons Learned
Student learning included the usual lessons such as the discovery of the complexity of software development, the need for communication and teamwork, and the importance of configuration management. Understanding of these issues was considerably deeper with the new course organization, however.
While this semester's class was relatively low in work experience and leadership skill, and relatively high in weak egos, significant learning took place due to the improved process structure. In fact, process improvement worked well enough to be instrumental in allowing us to bypass some of the battles between certain members of the design and implementation teams. More centralized project management may help here also.
Reducing the process learning startup time is of major importance, and several improvements are under development. We used an excellent book, The Team Handbook
[Scholtes89], as a supplementary process text, but additional class time needs to be used to practice the techniques. Students' skills are weak enough that teamwork cannot be learned solely from outside homework assignments. The students themselves suggested assignments, quizzes, or other means to ensure that everyone learn roles and processes early. Informal liaisons between the technical teams may need to be made explicit and enforced. Further work on developing written job descriptions and process plans will remedy some remaining deficiencies.
Technical writing and presentation skills are critical to process improvement and need to be strengthened. Some science college and departmental efforts in this direction may help. Our department's Contemporary Issues in Computer Science elective would be an ideal prerequisite, as it is designed to incorporate writing and presentation skills within a discussion of social, ethical, and professional issues. Relegating advanced methodology and CASE tool training to additional, probably separate, courses will allow the course to concentrate more on the project and ensure that all have the necessary technical skills, as well as making the course workload more equitable.
These techniques lead naturally to an analysis of the educational environment itself. When processes work smoothly, the underlying environment and infrastructure weaknesses become more apparent. Process improvement applied to the students' working environment identifies bottlenecks. In a time of limited resources, this is especially helpful for guiding instructors in directing their course organization efforts.
Conclusions
As usual, the instructor learned more than the students during the semester. Having explicit process roles and duties greatly improved students' learning on the software engineering project. While it is difficult to quantify, individual process skills and experiences seem to affect the quality of the end-products in a substantive way. The technical analysis, design, and testing techniques employed are important; but the empowerment, shared learning, and more stable environment provided by quality improvement efforts seem instrumental in increasing the learning benefits of the software engineering project course. As the students observed, the whole is indeed greater the sum of the parts. Learning and applying software process can improve software engineering education by giving students a meta-model to understand and help them manage the complexities of a large software development project. Teaching and applying software process is a vital part of increasing the amount of technology transferred as students move from the classroom to industry.
References
Appendix B: Software Process Assessment Questionnaire
Five levels of process maturity have been defined for the assessment of software engineering organizations:
- **Level 1** - Initial
- **Level 2** - Repeatable
- **Level 3** - Defined
- **Level 4** - Managed
- **Level 5** - Optimized
**Level 1 - Initial Process** - The initial environment has ill-defined procedures and controls. While positive responses to some of the organizational questions are likely, the organization does not consistently apply software engineering management to the process, nor does it use modern tools and technology.
**Level 2 - Repeatable Process** - At Maturity Level 2, the organization uses standard methods and practices for managing software development activities such as cost estimating, scheduling, requirements changes, code changes, and status reviews. The organization will provide positive responses to most of the following questions (* indicates a question of greater importance in determining the CMM level).
1.1.1 For each project involving software development, is there a designated software manager?
1.1.2 Does the project software manager report directly to the project (or project development) manager?
*1.1.3 Does the Software Quality Assurance (SQA) function have a management reporting channel separate from the software development project management?
*1.1.6 Is there a software configuration control function for each project that involves software development?
1.2.2 Is there a required training program for all newly appointed development managers designed to familiarize them with software project management?
1.3.1 Is a *mechanism* used for maintaining awareness of the state-of-the-art in software engineering technology?
2.1.3 Is a formal procedure used in the management review of each software development prior to making contractual commitments?
2.1.4 Is a formal procedure used to assure periodic management review of the status of each software development project?
2.1.5 Is there a mechanism for assuring that software subcontractors, if any, follow a disciplined software development process?
2.1.7 For each project, are independent audits conducted for each step of the software development process?
2.1.9 Are coding standards applied to each software development project?
2.1.14 Is a formal procedure used to make estimates of software size?
2.1.15 Is a formal procedure used to produce software development schedules?
2.1.16 Are formal procedures applied to estimating software development cost?
2.1.17 Is a mechanism used for ensuring that the software design teams understand each software requirement?
2.2.1 Are software staffing profiles maintained of actual staffing versus planned staffing?
2.2.2 Are profiles of software size maintained for each software configuration item, over time?
2.2.4 Are statistics on software code and test errors gathered?
2.2.7 Are profiles maintained of actual versus planned software units designed, over time?
2.2.8 Are profiles maintained of actual versus planned software units completing unit testing, over time?
2.2.9 Are profiles maintained of actual versus planned software units integrated, over time?
2.2.10 Are target computer memory utilization estimates and actuals tracked?
2.2.11 Are target computer throughput utilization estimates and actuals tracked?
2.2.12 Is target computer I/O channel utilization tracked?
2.2.16 Are software trouble reports resulting from testing tracked to closure?
2.2.18 Is test progress tracked by deliverable software component and compared to the plan?
2.2.19 Are profiles maintained of software build/release content versus time?
*2.4.1 Does senior management have a *mechanism* for the regular review of the status of software development projects?
2.4.5 Is a *mechanism* used for regular technical interchanges with the customer?
*2.4.7 Do software development first-line managers sign off on their schedules and cost estimates?
*2.4.9 Is a *mechanism* used for controlling changes to the software requirements?
*2.4.17 Is a *mechanism* used for controlling changes to the code? (Who can make changes and under which circumstances?)
2.4.20 Is there a *mechanism* for assuring that regression testing is routinely performed?
**Level 3 - Defined Process** - At Maturity Level 3, the organization not only defines its process in terms of software engineering standards and methods, it also has made a series of organizational and methodological improvements. These specifically include design and code review, training programs for programmers and review leaders, and increased organizational focus on software engineering. A major improvement in this phase is the establishment and staffing of a software engineering process group that focuses on the software engineering process and the adequacy with which it is implemented. In addition to the questions for Level 2, organizations at Level 3 will respond "yes" to most of the following questions.
1.1.4 Is there a designated individual or team responsible for the control of software interfaces?
1.1.5 Is software system engineering represented on the system design team?
1.1.7 Is there a software engineering *process group function*?
1.2.1 Does each software developer have a private computer-supported work station/terminal?
*1.2.3 Is there a required software engineering training program for software developers?
1.2.4 Is there a required software engineering training program for first-line supervisors of software development?
*1.2.5 Is a formal training program required for design and code *review leaders*?
1.3.2 Is a mechanism used for evaluating technologies used by the organization versus those externally available?
*2.1.1 Does the software organization use a standardized and documented software development process on each project?
2.1.2 Does the standard software development process documentation describe the use of tools and techniques?
2.1.6 Are standards used for the content of software development files/folders?
2.1.8 Is a mechanism used for assessing existing designs and code for reuse in new applications?
2.1.10 Are standards applied to the preparation of unit test cases?
2.1.11 Are code maintainability standards applied?
2.1.18 Are man-machine interface standards applied to each appropriate software development project?
*2.2.3 Are statistics on software design errors gathered?
*2.2.15 Are the action items resulting from design reviews tracked to closure?
*2.2.17 Are the action items resulting from code reviews tracked to closure?
2.4.3 Is a mechanism used for identifying and resolving system engineering issues that affect software?
2.4.4 Is a mechanism used for independently calling integration and test issues to the attention of the project manager?
*2.4.6 Is a mechanism used for ensuring compliance with the software engineering standards?
2.4.8 Is a mechanism used for ensuring traceability between the software requirements and top-level design?
2.4.11 Is a mechanism used for ensuring traceability between the software top-level and detailed designs?
*2.4.12 Are internal software design reviews conducted?
*2.4.13 Is a mechanism used for controlling changes to the software design?
2.4.14 Is a mechanism used for ensuring traceability between the software detailed design and the code?
2.4.15 Are formal records maintained of unit (module) development progress?
*2.4.16 Are software code reviews conducted?
2.4.18 Is a mechanism used for configuration management of the software tools used in the development process?
*2.4.19 Is a mechanism used for verifying that the samples examined by Software Quality Assurance are truly representative of the work performed?
*2.4.21 Is there a mechanism for assuring the adequacy of regression testing?
2.4.22 Are formal test case reviews conducted?
Level 4 - Managed Process - At Maturity Level 4, the organization typically bases its operating decisions on quantitative process data, and conducts extensive analyses of the data gathered during software engineering reviews and tests. Tools are used increasingly to control and manage the design process as well as to support data gathering and analysis. The organization is learning to project expected errors with reasonable accuracy. In addition to questions for Levels 2 and 3, organizations at Level 4 will respond “yes” to most of the following questions.
1.3.3 Is a mechanism used for deciding when to insert new technology into the development process?
*1.3.4 Is a mechanism used for managing and supporting the introduction of new technologies?
2.1.12 Are internal design review standards applied?
*2.1.13 Are code review standards applied?
*2.2.5 Are design errors projected and compared to actuals?
*2.2.6 Are code and test errors projected and compared to actuals?
*2.2.13 Are design and code review coverages measured and recorded?
*2.2.14 Is test coverage measured and recorded for each phase of functional testing?
*2.3.1 Has a managed and controlled process database been established for process metrics data across all projects?
*2.3.2 Are the review data gathered during design reviews analyzed?
*2.3.3 Is the effort data from code reviews and tests analyzed to determine the likely distribution and characteristics of the errors remaining in the product?
*2.3.4 Are analyses of errors conducted to determine their process related causes?
*2.3.8 Is review efficiency analyzed for each project?
2.3.9 Is software productivity analyzed for major process steps?
*2.4.2 Is a mechanism used for periodically assessing the software engineering process and implementing indicated improvements?
2.4.10 Is there a formal management process for determining if the prototyping of software functions is an appropriate part of the design process?
Level 5 - Optimized Process - At Maturity Level 5, organizations have not only achieved a high degree of control over their process, they have a major focus on improving and optimizing its operation. This includes more sophisticated analyses of the error and cost data gathered during the process as well as the introducing of comprehensive error cause analysis and prevention studies.
*1.3.5 Is a mechanism used for identifying and replacing obsolete technologies?
*2.3.5 Is a mechanism used for error cause analysis?
*2.3.6 Are the error causes reviewed to determine the process changes required to prevent them?
*2.3.7 Is a mechanism used for initiating error prevention actions?
Technology Addendum
*3.1 Is automated configuration control used to control and track change activity throughout the software development process?
3.2 Are computer tools used to assist in tracing software requirements to software design?
3.3 Are formal design notations such as PDL used in program design?
3.4 Are computer tools used to assist in tracing the software design to the code?
*3.5 Is the majority of product development implemented in a high-order language?
3.6 Are automated test input data generators used for testing?
3.7 Are computer tools used to measure test coverage?
3.8 Are computer tools used to track every required function and assure that it is tested/verified?
3.9 Are automated tools used to analyze the size and change activity in software components?
3.10 Are automated tools used to analyze software complexity?
3.11 Are automated tools used to analyze cross references between modules?
*3.12 Are interactive source-level debuggers used?
*3.13 Are the software development and maintenance personnel provided with interactive documentation facilities?
*3.14 Are computer tools used for tracking and reporting the status of the software in the software development library?
3.15 Are prototyping methods used in designing the critical performance elements of the software?
3.16 Are prototyping methods used in designing the critical elements of the man-machine interface?
Attachments
Two attachments follow. The first, titled “Introduction to Software Process Improvement,” is intended as supplementary reading for students. Its pages are numbered separately from the body of this educational materials package.
The second attachment consists of nine overhead transparency masters, the contents of which are taken from the body of this document and from the student document. They include:
- Software Process Maturity Levels (Figure 1; student document Figure 1)
- Shewart Improvement Cycle (Table 1)
- Common Steps in SPAs and SCEs (Figure 2; student document Figure 2)
- Comparison Between SCE and SPA (Table 2; student document Table 3)
- Capability Maturity Model Structure (Figure 3)
- Example of CMM Structure (Figure 4)
- Key Process Areas by Maturity Level (Table 4; student document Table 1)
- Software Systems Development is Prone to Waste (Figure 5)
- On-Board Shuttle Software Improvement (student document Table 2)
Introduction
The crisis in software has been well documented. In order to compete successfully in the international market, we, as software professionals, need to improve both the quality of our software products and our ability to work within time and budget constraints. These improvements depend strongly on process as well as technology.
Modern technology can help us combat the software crisis, yet as Fred Brooks warns us, there is no technological “silver bullet” to rescue us. Talented people are important in any software organization. Nevertheless, people need to be supported by a good working environment. Software development is hampered by changing requirements, unpredictable schedules, lack of standards, and insufficient training more than by a lack of effort on the part of professionals. Curtis, Krasner, and Iscoe documented these issues effectively in their report describing their interviews with software professionals. In short, problems with the process, rather than the technology, cause a substantial number of the problems in software development and maintenance.
This brief document begins with a history of the Software Engineering Institute (SEI) and its software process work. Terminology is introduced and the five levels of the SEI capability maturity model (CMM) are defined. Possible uses and future directions of the model are provided.
Background and Definitions
The Software Engineering Institute was established at Carnegie Mellon University in Pittsburgh, Pennsylvania in 1984, under a Department of Defense contract. Its mission is to provide leadership in advancing the state of the practice of software engineering to improve the quality of systems that depend on software. The software process work began two years later. One of the results was a software process maturity model. In 1987, the SEI and MITRE Corporation produced the first maturity questionnaire, a set of yes-no questions that address organization and management issues, as well as the technical software development process. Over the next few years, the SEI developed two methods for using the questionnaire to appraise an organization’s software process.
After an extensive review process, the capability maturity model (CMM) for software replaced the software process maturity model in 1991. The CMM summarizes general software process practices for each of five maturity levels. Once the current level of operation is established using the maturity questionnaire, improving a company's software process involves implementing the software engineering practices needed to reach each of the five levels, in order, from lowest to highest.
**What is Software Process and How Can It be Improved?**
It is important to understand the vocabulary used in describing the software process and the maturity model. These terms are used in a particular way, and it is important to know their meaning in order to comprehend the model. It is also necessary to understand that a software process model is not a mathematical formula. In this context, it is a description of how to conduct the process of software development.
*Software process* is defined as a set of activities that begin with the identification of a need and concludes with the retirement of a product that satisfies the need; or more completely, as a set of activities, methods, practices, and transformations that people use to develop and maintain software and its associated products (e.g., project plans, design documents, code, test cases, user manuals).
*Software process capability* describes the range of expected results achieved from a software process. But capability is not the same as performance. Software process performance is the actual results achieved from following a software process. That is, results achieved (performance) differ from results expected (capability).
Many software process techniques, such as quality assurance, configuration management, inspections, and reviews, are described in most software engineering textbooks and will not be covered here. From a general problem-solving point of view, project management may be described simply as:
- identifying what is to be done
- deciding how to do it
- monitoring what is being done
- evaluating the outcome
Most managers try to do the first and second steps above, describing the *what* and *how* using plans and schedules. However, even though managers know that requirements will change, schedules will slip, and all the other typical problems will likely occur on the project, few attempt to build these dynamic events into their plans. In addition, managers need to monitor project activities and to adjust the plans as modifications occur. To improve the software development process, it is necessary to evaluate the success of the project and avoid repeating problems in the future. The CMM addresses these latter, less well-understood, issues in an effort to improve the software development process.
The scientific, closed-loop model of management can be explained most simply as follows. Project plans are used as hypotheses, and project results are evaluated to verify or validate these hypotheses. Statistical, or closed-loop, process management is based on measurement. First a baseline is determined. After improvements are instituted, measurements are repeated. Results are compared against the hypotheses or predictions to measure progress. This process comparison is repeated with the goal of reducing the differences between the predicted results and the actual results. Thus, the project is managed, but the management process is meta-managed.
W. E. Deming, one of the pioneers of applying statistical process control in industry, describes process improvement as a continuous cycle which follows these steps:
1. Understand the status of the development process.
2. Develop a vision of the desired process.
3. List improvement actions in priority order.
4. Generate a plan to accomplish the required actions.
5. Commit the resources to execute the plan.
**SEI Capability Maturity Model**
The SEI capability maturity model is derived from the ideas of quality improvement applied to software development. The five-level improvement model is shown in Figure 1. The five stages are called maturity levels. Each represents an improvement in the software process. An organization’s software capability can be improved by advancing through these five stages or levels. The CMM helps organizations to select improvement strategies based on current process maturity status and to identify critical issues in quality and process improvement.
The following descriptions outline the primary characteristics of the software process for each level of the CMM.
1. Initial
The initial software process is characterized as ad hoc. Typically, the organization operates without formal procedures, cost estimates or project plans. There are few mechanisms to ensure that procedures are followed. Tools, if they exist, are not well integrated. Change control is lax or nonexistent. Senior management neither hears about nor understands software problems and issues. Success generally depends on the efforts of individuals, not the organization. Not too surprisingly, most software organizations—86% in an early survey—were at the initial level.
2. Repeatable
At the repeatable level, project controls have been established over quality assurance, change control, cost, and schedule. This discipline enables earlier successes to
be repeated, though the organization may have problems applying these techniques to new applications. An SEI survey found 16% of the companies at the repeatable level.
3. Defined
The defined software process, for both management and engineering activities, is documented, standardized, and integrated across the organization. The process is visible; that is, it can be examined and improvements suggested. Typically, the organization has established a software engineering process group (SEPG) to lead the improvement effort, keep management informed on progress, and facilitate introducing other software engineering methods.
An early SEI study found only one percent of organizations surveyed at the defined level, though more recently several large companies have achieved this stage for
some of their development groups. Organizations need to achieve the defined maturity level to consistently produce quality software on time and within budget.
4. Managed
Achieving the fourth, or managed, level requires that measures of software process and product quality be collected so that process effectiveness can be determined quantitatively. A process database and adequate resources are needed to continually plan, implement, and track process improvements.
5. Optimizing
At the optimizing level, quantitative feedback data from the process allows continuous process improvement. Data gathering has been partially automated. Management has changed its emphasis from product maintenance to process analysis and improvement. Defect cause analysis and defect prevention are the most important activities added at this level.
As maturity increases, differences between targeted and actual results decrease; costs decrease and development time shortens; and productivity and quality increase. The process becomes more predictable as rework is prevented and the risk level is reduced. See Table 1 for the specific process areas added at each maturity level. It is important to note that maturity levels cannot be skipped as each level is the foundation for the next.
Progress through the maturity levels requires high-level management backing and long-term commitment. It requires fundamental modifications in the way managers and software practitioners do their jobs, and this takes time to accomplish. Software process improvement should not even be started without considerable levels of corporate-wide encouragement and support.
One SEI report summarizes the capability maturity model in this way.
“The CMM provides a conceptual structure for improving the management and development of software products in a disciplined and consistent way. It does not guarantee that software products will be successfully built or that all problems in software engineering will be resolved. The CMM identifies practices for a mature software process, but it is not meant to be either exhaustive or dictatorial. While the maturity questionnaire samples key indicators of an effect, software process and the CMM identifies the characteristics of an effective software process, the mature organization addresses all issues essential to a successful project—including people and technology—as well as process.”
Level 2: Repeatable
Requirements Management
Software Project Planning
Software Project Tracking and Oversight
Software Subcontract Management, if applicable
Software Quality Assurance
Software Configuration Management
Level 3: Defined
Organization Process Focus
Organization Process Definition
Training Program
Integrated Software Management
Software Product Engineering
Intergroup Coordination
Peer Reviews
Level 4: Managed
Process Measurement and Analysis
Quality Management
Level 5: Optimizing
Defect Prevention
Technology Innovation
Process Change Management
Table 1. Key process areas (KPA) by maturity level
How Is the Maturity Model Used?
Several companies have already reported benefits from applying the capability maturity model. A process improvement investment of $400,000 produced an annual savings of $2,000,000 at Hughes Aircraft. Raytheon saved about $9.2 million by eliminating rework on a base of about $115 million in software development costs. At IBM Houston, the NASA space shuttle on-board software development group showed the results depicted in Table 2.
There are two major ways the maturity model can be applied: for software process assessment (SPA) and for software capability evaluation (SCE). Both methods are based on the capability maturity model and maturity questionnaire. Together, the model and questionnaire provide a way to identify and compare organizations’ strengths
<table>
<thead>
<tr>
<th></th>
<th>1982</th>
<th>1985</th>
</tr>
</thead>
<tbody>
<tr>
<td>Early error detection (% errors found)</td>
<td>48</td>
<td>80</td>
</tr>
<tr>
<td>Reconfiguration time (weeks)</td>
<td>11</td>
<td>5</td>
</tr>
<tr>
<td>Reconfiguration effort (person-years)</td>
<td>10.5</td>
<td>4.5</td>
</tr>
<tr>
<td>Product error rate (errors per 1000 lines of code)</td>
<td>2.0</td>
<td>0.11</td>
</tr>
</tbody>
</table>
Table 2. On-board shuttle software improvements
There are differences between the two methods, SPA and SCE, as summarized in Table 3. These differences include the objectives, the make-up of the site visitation teams, the criteria for determining scope and for defining findings, and the ownership of the results. In view of these differences, the outcomes of assessments and evaluations are not likely to be interchangeable or directly comparable. The SCE team may conclude that a particular weakness has low risk associated with it for the acquisition and therefore discount it (for example, subcontract management in an acquisition that may not involve subcontracts), while a SPA team might recommend corrective action as a high priority for the same weakness (since other projects involve subcontractors). Both views would be valid for their respective purposes.
**Software Process Assessment**
A software process assessment is a means for organizations to identify their strengths, weaknesses, existing improvement activities, and key areas for improvement. It enables them to determine the current state of their software process and to develop action plans for improvement.
Assessments are performed by a team of 6-10 experienced software professionals. The majority are from the organization being assessed. In the past, individual teams have been trained by the SEI. More recently, the SEI has trained and licensed SPA associates to provide these services commercially. A SPA associate often works collaboratively with team members. In selected cases, the SEI does so.
An organization spends two to six months (elapsed time) preparing for an assessment, beginning with management commitment to the process improvement effort. Other preparations include selecting the assessment team, and selecting the representatives of software projects and functional areas (such as testing and quality assurance) who will participate in the on-site assessment activities.
The assessment team helps to prepare the rest of the organization for the assessment and for the ensuing process improvement activities. In addition to making detailed plans and a schedule, they tell everyone what to expect and concentrate on building support for process improvement and the assessment. The team spends five days on site.
They analyze the information they get from the maturity questionnaire, individual interviews with project leaders, and group discussions with practitioners (functional area representatives). To encourage interviewees to be open, the SPA team treats the information as confidential; they report only composite findings and give no attribution to individuals or projects. Occasionally, the team looks at documents to clarify information from the discussions.
The team uses the maturity model to help them categorize data. They determine the current software process maturity, identify key findings (that is, they determine what will impede capability to produce quality software), and note strengths the organization can build upon. Decisions are made by consensus, which helps to counter possible bias in any individual’s conclusions about the data. In addition, project leaders and practitioners who were interviewed review the team’s findings and give feedback.
The team presents the results of the assessment to senior management and, often, to the entire organization that was assessed. They recommend what can be done to address their findings. Many teams brainstorm a preliminary list of recommendations and enlist others in the organization to help flesh it out. Later, the team writes a final report that presents findings and recommendations in detail. The SEI recommends that the report be widely available in the organization.
After the assessment, an action planning group (often a software engineering process group, under the guidance of a management steering committee) develops the strategies for accomplishing long-term process improvement and determines what improvements are achievable within a specific time frame. They work with many others in the organi-
<table>
<thead>
<tr>
<th>SCE</th>
<th>SPA</th>
</tr>
</thead>
<tbody>
<tr>
<td>Used by acquisition organization for source selection and contract monitoring</td>
<td>Used by organization to improve software process</td>
</tr>
<tr>
<td>Results to the organization and the acquirer</td>
<td>Results to organization only</td>
</tr>
<tr>
<td>Substantiates current practice</td>
<td>Assesses current practice</td>
</tr>
<tr>
<td>Assesses commitment to improve</td>
<td>Acts as catalyst for process improvement</td>
</tr>
<tr>
<td>Analyzes contract performance potential</td>
<td>Provides input to improvement action plan</td>
</tr>
<tr>
<td>Independent evaluation—no organization members on team</td>
<td>Collaborative—organization members on team, with representative from licensed SPA associate or SEI</td>
</tr>
<tr>
<td>Applies to performance for a particular contract</td>
<td>Applies to organization overall, not individual projects</td>
</tr>
</tbody>
</table>
Table 3. Comparison between SCE and SPA
zation to create an action plan and implement it. To be effective, they must combine improvement plans with other organizational plans such as the business plan. Members of the SPA team often become involved in these activities; their involvement is one of the significant differences between a process assessment and a capability evaluation.
As an organization’s software process matures, periodic reassessments allow them to identify new priorities and strategies for further improvement. The SEI recommends reassessments approximately every two years.
Software Capability Evaluation
A software capability evaluation is an independent evaluation of an organization's software process as it relates to a particular acquisition. It is a tool that helps an external group (an “acquirer”) determine the organization’s ability to produce a particular product having high quality and to produce it on time and within budget.
Evaluations are performed by a trained and experienced team of 4-6 members. The members are not part of the organization being evaluated. Rather, they come from acquisition organizations, such as certain government agencies.
An SCE team looks at projects that perform work similar to that required by the new contract. Thus, the selected projects are usually similar to the acquisition in application domain, size, and life-cycle phases. They may not be representative of the organization as a whole.
During a planning period of several weeks, the organization being evaluated submits a choice of projects for selection, along with information about the projects and about the organization in general. The SCE team selects projects, reviews high-level documents from the organization, and makes detailed plans and a schedule for the site visit.
The SCE team spends three days on site interviewing project and organization personnel, one at a time. Team members may talk to as few as 10 or as many as 30 people. They also review documents from one to four projects, depending on the particular application of the SCE method (contract monitoring or source selection). As in the SPA method, the SCE team does not attribute information to individuals but holds their responses in confidence.
While still on site, the team identifies strengths, weaknesses, and improvement activities that they consider to be most relevant to performance on the acquisition contract. Consensus among the team plays a major role in countering possible bias in the way any individual might form conclusions about the data. The team does not assign a maturity level, but rather builds a profile of strengths and weaknesses relevant to the specific acquisition.
The SCE team presents their findings to the organization that was evaluated. To foster process improvement, the SEI strongly recommends that the presentation include all the detailed SCE findings that are delivered to the acquisition agency.
Ownership of the SCE findings is with the acquirer. A group in the acquisition agency transforms the findings of the SCE team into acquisition risks and/or technical ratings. To ensure objectivity and integrity, the SCE team deliberately avoids interpreting its own findings. The acquisition agency uses the SCE findings and other criteria to select a source or monitor a contract.
A Final Comment
Software process maturity requires a long-term commitment to continuous process improvement. The CMM does not address all issues important for successful projects. The CMM does not imply or limit the choice to a particular life-cycle model. Specific software technologies such as reuse or prototyping are neither required nor excluded. The use of DoD-STD-2167A is not dictated. Projects’ documents and products do not have to match the CMM exactly. Particular organizational or project structures are not mandated. Suggested software practices are generic, intended to provide flexibility. Each project or organization must clarify these practices for its specific situation.
Software Process Maturity Levels
Optimizing (5)
- Process change management
- Technology innovation
- Defect prevention
Managed (4)
- Quality management
- Process measurement and analysis
Defined (3)
- Peer reviews
- Intergroup coordination
- Software product engineering
- Integrated software management
- Training program
- Organization process definition
- Organization process focus
Repeatable (2)
- Software configuration management
- Software quality assurance
- Software subcontracts management
- Software project tracking and oversight
- Software project planning
- Requirements management
Initial (1)
- Software project tracking and oversight
- Software project planning
- Requirements management
Shewart Improvement Cycle
1. Plan
Define the problem
State improvement objectives
2. Do
Identify possible problem causes
Establish baselines
Test changes
3. Check
Collect data
Evaluate data
4. Act
Implement system change
Determine effectiveness
Common Steps in SPAs and SCEs
1. Team Selection and Training
2. Maturity Questionnaire
3. Response Analysis
4. On-Site Visit
5. Findings
6. KPA Profile
7. Report of Results
Capability Maturity Model Structure
Maturity Levels
Process Capability
Goals
Implementation or Institutionalization Activities
Key Process Areas
achieves organized by
Common Features
address contain
Key Practices
describe
Infrastructure or Activities
Example of CMM Structure
**Maturity Level:**
Level 2, Repeatable
**Process Capability:**
Disciplined process
**Goal:**
A plan is developed that appropriately and realistically covers the software activities and commitments
**Key Process Area:**
Software Project Planning
**Key Practice:**
Estimates for the size of software products are derived according to a documented procedure
**Activity:**
Use a documented procedure to estimate software size (e.g., lines of code, function points)
Key Process Areas by Maturity Level
Level 2: Repeatable
- Requirements Management
- Software Project Planning
- Software Project Tracking and Oversight
- Software Subcontract Management, if applicable
- Software Quality Assurance
- Software Configuration Management
Level 3: Defined
- Organization Process Focus
- Organization Process Definition
- Training Program
- Integrated Software Management
- Software Product Engineering
- Intergroup Coordination
- Peer Reviews
Level 4: Managed
- Process Measurement and Analysis
- Quality Management
Level 5: Optimizing
- Defect Prevention
- Technology Innovation
- Process Change Management
Software Systems Development is Prone to Waste
- Software paid for but not delivered: 29.7%
- Software used but later reworked or abandoned: 19%
- Software that could be used after changes: ~3%
- Software delivered but never used: 47%
Year 1982: Nine Contracts Totalling $6.8 Million
On-Board Shuttle Software Improvements
<table>
<thead>
<tr>
<th></th>
<th>1982</th>
<th>1985</th>
</tr>
</thead>
<tbody>
<tr>
<td>Early error detection (% errors found)</td>
<td>48</td>
<td>80</td>
</tr>
<tr>
<td>Reconfiguration time (weeks)</td>
<td>11</td>
<td>5</td>
</tr>
<tr>
<td>Reconfiguration effort (person-years)</td>
<td>10.5</td>
<td>4.5</td>
</tr>
<tr>
<td>Product error rate (errors/1000 lines of code)</td>
<td>2.0</td>
<td>0.11</td>
</tr>
<tr>
<td>SCE</td>
<td>SPA</td>
<td></td>
</tr>
<tr>
<td>-----------------------------------------------</td>
<td>-----------------------------------------------</td>
<td></td>
</tr>
<tr>
<td>Used by acquisition organization for source selection and contract monitoring</td>
<td>Used by organization to improve software process</td>
<td></td>
</tr>
<tr>
<td>Results to the organization and the acquirer</td>
<td>Results to organization only</td>
<td></td>
</tr>
<tr>
<td>Substantiates current practice</td>
<td>Assesses current practice</td>
<td></td>
</tr>
<tr>
<td>Assesses commitment to improve</td>
<td>Acts as catalyst for process improvement</td>
<td></td>
</tr>
<tr>
<td>Analyzes contract performance potential</td>
<td>Provides input to improvement action plan</td>
<td></td>
</tr>
<tr>
<td>Independent evaluation—no organization members on team</td>
<td>Collaborative—organization members on team, with representative of licensed SPA associate or SEI</td>
<td></td>
</tr>
<tr>
<td>Applies to performance for a particular contract</td>
<td>Applies to organization overall, not individual projects</td>
<td></td>
</tr>
</tbody>
</table>
Software process improvement is not usually covered in standard software engineering textbooks. However, being a topic of great interest to the software industry, both faculty and students should be familiar with it. The goal of this package is to provide the basis for an introductory 30 to 60 minute lecture on the software process and its improvement.
The Software Engineering Institute (SEI) is a federally funded research and development center, operated by Carnegie Mellon University under contract with the United States Department of Defense.
The SEI Graduate Curriculum Project is developing a wide range of materials to support software engineering education. A curriculum module (CM) identifies and outlines the content of a specific topic area, and is intended to be used by an instructor in designing a course. A support materials package (SM) contains materials related to a module that may be helpful in teaching a course. An educational materials package (EM) contains other materials not necessarily related to a curriculum module. Other publications include software engineering curriculum recommendations and course designs.
SEI educational materials are being made available to educators throughout the academic, industrial, and government communities. The use of these materials in a course does not in any way constitute an endorsement of the course by the SEI, by Carnegie Mellon University, or by the United States government.
Permission to make copies or derivative works of SEI curriculum modules, support materials, and educational materials listed below is granted, without fee, provided that the copies and derivative works are not made or distributed for direct commercial advantage, and that all copies and derivative works cite the original document by title, author's name, and document number and give notice that the copying is by permission of Carnegie Mellon University.
Comments on SEI educational materials and requests for additional information should be addressed to SEI Products, Software Engineering Institute, Carnegie Mellon University, Pittsburgh, Pennsylvania 15213. Electronic mail can be sent to education@sei.cmu.edu on the Internet.
<table>
<thead>
<tr>
<th>Curriculum Modules (* Support Materials available)</th>
<th>Educational Materials</th>
</tr>
</thead>
<tbody>
<tr>
<td>CM-1 [superseded by CM-19]</td>
<td>EM-1 Software Maintenance Exercises for a Software Engineering Project Course</td>
</tr>
<tr>
<td>CM-2 Introduction to Software Design</td>
<td>EM-2 APSE Interactive Monitor: An Artifact for Software Engineering Education</td>
</tr>
<tr>
<td>CM-4 Software Configuration Management*</td>
<td>EM-4 A Software Engineering Project Course with a Real Client</td>
</tr>
<tr>
<td>CM-5 Information Protection</td>
<td>EM-5 Scenes of Software Inspections: Video Dramatizations for the Classroom</td>
</tr>
<tr>
<td>CM-6 Software Safety</td>
<td>EM-6 Materials to Support Teaching a Project-Intensive Introduction to Software Engineering</td>
</tr>
<tr>
<td>CM-7 Assurance of Software Quality</td>
<td>EM-7 Materials for Teaching Software Inspections</td>
</tr>
<tr>
<td>CM-8 Formal Specification of Software*</td>
<td>EM-8 Lecture Notes on Software Process Improvement</td>
</tr>
<tr>
<td>CM-9 Unit Analysis and Testing</td>
<td></td>
</tr>
<tr>
<td>CM-10 Models of Software Evolution: Life Cycle and Process</td>
<td></td>
</tr>
<tr>
<td>CM-11 Software Specifications: A Framework</td>
<td></td>
</tr>
<tr>
<td>CM-12 Software Metrics</td>
<td></td>
</tr>
<tr>
<td>CM-13 Introduction to Software Verification and Validation</td>
<td></td>
</tr>
<tr>
<td>CM-14 Intellectual Property Protection for Software</td>
<td></td>
</tr>
<tr>
<td>CM-15 [no longer available]</td>
<td></td>
</tr>
<tr>
<td>CM-16 Software Development Using VDM</td>
<td></td>
</tr>
<tr>
<td>CM-17 User Interface Development*</td>
<td></td>
</tr>
<tr>
<td>CM-18 [superseded by CM-23]</td>
<td></td>
</tr>
<tr>
<td>CM-19 Software Requirements</td>
<td></td>
</tr>
<tr>
<td>CM-20 Formal Verification of Programs</td>
<td></td>
</tr>
<tr>
<td>CM-21 Software Project Management</td>
<td></td>
</tr>
<tr>
<td>CM-22 Software Design Methods for Real-Time Systems</td>
<td></td>
</tr>
<tr>
<td>CM-23 Technical Writing for Software Engineers</td>
<td></td>
</tr>
<tr>
<td>CM-24 Concepts of Concurrent Programming</td>
<td></td>
</tr>
<tr>
<td>CM-25 Language and System Support for Concurrent Programming</td>
<td></td>
</tr>
<tr>
<td>CM-26 Understanding Program Dependencies</td>
<td></td>
</tr>
<tr>
<td>CM-27 Formal Specification and Verification of Concurrent Programs</td>
<td></td>
</tr>
</tbody>
</table>
|
{"Source-Url": "https://apps.dtic.mil/dtic/tr/fulltext/u2/a265200.pdf", "len_cl100k_base": 15941, "olmocr-version": "0.1.42", "pdf-total-pages": 59, "total-fallback-pages": 0, "total-input-tokens": 109587, "total-output-tokens": 20140, "length": "2e13", "weborganizer": {"__label__adult": 0.0007252693176269531, "__label__art_design": 0.0007534027099609375, "__label__crime_law": 0.00044035911560058594, "__label__education_jobs": 0.028350830078125, "__label__entertainment": 0.00013971328735351562, "__label__fashion_beauty": 0.0003609657287597656, "__label__finance_business": 0.0010089874267578125, "__label__food_dining": 0.0006613731384277344, "__label__games": 0.0011873245239257812, "__label__hardware": 0.0008535385131835938, "__label__health": 0.0005970001220703125, "__label__history": 0.0005879402160644531, "__label__home_hobbies": 0.0002703666687011719, "__label__industrial": 0.0006270408630371094, "__label__literature": 0.0007505416870117188, "__label__politics": 0.0004863739013671875, "__label__religion": 0.0006709098815917969, "__label__science_tech": 0.00609588623046875, "__label__social_life": 0.00029730796813964844, "__label__software": 0.005359649658203125, "__label__software_dev": 0.9482421875, "__label__sports_fitness": 0.0005865097045898438, "__label__transportation": 0.0007824897766113281, "__label__travel": 0.0003857612609863281}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 87393, 0.02685]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 87393, 0.49515]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 87393, 0.92014]], "google_gemma-3-12b-it_contains_pii": [[0, 81, false], [81, 232, null], [232, 232, null], [232, 861, null], [861, 1304, null], [1304, 3815, null], [3815, 4962, null], [4962, 7391, null], [7391, 8415, null], [8415, 10443, null], [10443, 13063, null], [13063, 15752, null], [15752, 16436, null], [16436, 17667, null], [17667, 20426, null], [20426, 20804, null], [20804, 21176, null], [21176, 22209, null], [22209, 25223, null], [25223, 27097, null], [27097, 28889, null], [28889, 30775, null], [30775, 33238, null], [33238, 34461, null], [34461, 37101, null], [37101, 40164, null], [40164, 43199, null], [43199, 44184, null], [44184, 45930, null], [45930, 47680, null], [47680, 49804, null], [49804, 51541, null], [51541, 53536, null], [53536, 55402, null], [55402, 56121, null], [56121, 57080, null], [57080, 59253, null], [59253, 62051, null], [62051, 64609, null], [64609, 65403, null], [65403, 67811, null], [67811, 69226, null], [69226, 71545, null], [71545, 72342, null], [72342, 74736, null], [74736, 77401, null], [77401, 78720, null], [78720, 79431, null], [79431, 79704, null], [79704, 79878, null], [79878, 80140, null], [80140, 80633, null], [80633, 81272, null], [81272, 81558, null], [81558, 81924, null], [81924, 82914, null], [82914, 83269, null], [83269, 83269, null], [83269, 87393, null]], "google_gemma-3-12b-it_is_public_document": [[0, 81, true], [81, 232, null], [232, 232, null], [232, 861, null], [861, 1304, null], [1304, 3815, null], [3815, 4962, null], [4962, 7391, null], [7391, 8415, null], [8415, 10443, null], [10443, 13063, null], [13063, 15752, null], [15752, 16436, null], [16436, 17667, null], [17667, 20426, null], [20426, 20804, null], [20804, 21176, null], [21176, 22209, null], [22209, 25223, null], [25223, 27097, null], [27097, 28889, null], [28889, 30775, null], [30775, 33238, null], [33238, 34461, null], [34461, 37101, null], [37101, 40164, null], [40164, 43199, null], [43199, 44184, null], [44184, 45930, null], [45930, 47680, null], [47680, 49804, null], [49804, 51541, null], [51541, 53536, null], [53536, 55402, null], [55402, 56121, null], [56121, 57080, null], [57080, 59253, null], [59253, 62051, null], [62051, 64609, null], [64609, 65403, null], [65403, 67811, null], [67811, 69226, null], [69226, 71545, null], [71545, 72342, null], [72342, 74736, null], [74736, 77401, null], [77401, 78720, null], [78720, 79431, null], [79431, 79704, null], [79704, 79878, null], [79878, 80140, null], [80140, 80633, null], [80633, 81272, null], [81272, 81558, null], [81558, 81924, null], [81924, 82914, null], [82914, 83269, null], [83269, 83269, null], [83269, 87393, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 87393, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 87393, null]], "pdf_page_numbers": [[0, 81, 1], [81, 232, 2], [232, 232, 3], [232, 861, 4], [861, 1304, 5], [1304, 3815, 6], [3815, 4962, 7], [4962, 7391, 8], [7391, 8415, 9], [8415, 10443, 10], [10443, 13063, 11], [13063, 15752, 12], [15752, 16436, 13], [16436, 17667, 14], [17667, 20426, 15], [20426, 20804, 16], [20804, 21176, 17], [21176, 22209, 18], [22209, 25223, 19], [25223, 27097, 20], [27097, 28889, 21], [28889, 30775, 22], [30775, 33238, 23], [33238, 34461, 24], [34461, 37101, 25], [37101, 40164, 26], [40164, 43199, 27], [43199, 44184, 28], [44184, 45930, 29], [45930, 47680, 30], [47680, 49804, 31], [49804, 51541, 32], [51541, 53536, 33], [53536, 55402, 34], [55402, 56121, 35], [56121, 57080, 36], [57080, 59253, 37], [59253, 62051, 38], [62051, 64609, 39], [64609, 65403, 40], [65403, 67811, 41], [67811, 69226, 42], [69226, 71545, 43], [71545, 72342, 44], [72342, 74736, 45], [74736, 77401, 46], [77401, 78720, 47], [78720, 79431, 48], [79431, 79704, 49], [79704, 79878, 50], [79878, 80140, 51], [80140, 80633, 52], [80633, 81272, 53], [81272, 81558, 54], [81558, 81924, 55], [81924, 82914, 56], [82914, 83269, 57], [83269, 83269, 58], [83269, 87393, 59]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 87393, 0.12583]]}
|
olmocr_science_pdfs
|
2024-11-22
|
2024-11-22
|
b834ca1eb31f33c7486d8821e00a54ff3aaeed42
|
Security Analysis of Java Web Applications Using String Constraint Analysis
Citation
Permanent link
http://nrs.harvard.edu/urn-3:HUL.InstRepos:14398534
Terms of Use
This article was downloaded from Harvard University’s DASH repository, and is made available under the terms and conditions applicable to Other Posted Material, as set forth at http://nrs.harvard.edu/urn-3:HUL.InstRepos:dash.current.terms-of-use#LAA
Share Your Story
The Harvard community has made this article openly available. Please share how this access benefits you. Submit a story.
Accessibility
# Contents
<table>
<thead>
<tr>
<th>Section</th>
<th>Page</th>
</tr>
</thead>
<tbody>
<tr>
<td>Contents</td>
<td>1</td>
</tr>
<tr>
<td>Abstract</td>
<td>3</td>
</tr>
<tr>
<td>Acknowledgements</td>
<td>4</td>
</tr>
<tr>
<td>1 Introduction</td>
<td>5</td>
</tr>
<tr>
<td>1.1 Motivation</td>
<td>6</td>
</tr>
<tr>
<td>2 Related work</td>
<td>7</td>
</tr>
<tr>
<td>2.1 String analysis</td>
<td>7</td>
</tr>
<tr>
<td>2.2 Static analysis of web applications</td>
<td>8</td>
</tr>
<tr>
<td>2.3 String solvers</td>
<td>8</td>
</tr>
<tr>
<td>3 Technical Background</td>
<td>9</td>
</tr>
<tr>
<td>3.1 String-based Security Vulnerabilities</td>
<td>9</td>
</tr>
<tr>
<td>3.1.1 SQL Injection</td>
<td>9</td>
</tr>
<tr>
<td>3.1.2 Cross-site scripting</td>
<td>10</td>
</tr>
<tr>
<td>3.1.2.1 Persistent (stored) XSS</td>
<td>10</td>
</tr>
<tr>
<td>3.1.2.2 Reflected XSS</td>
<td>11</td>
</tr>
<tr>
<td>3.2 Java bytecode</td>
<td>12</td>
</tr>
<tr>
<td>3.3 Dataflow analysis</td>
<td>12</td>
</tr>
<tr>
<td>3.3.1 Call graphs</td>
<td>13</td>
</tr>
<tr>
<td>3.3.2 Static single assignment</td>
<td>14</td>
</tr>
<tr>
<td>3.3.3 Intraprocedural analysis</td>
<td>14</td>
</tr>
<tr>
<td>3.3.4 Interprocedural analysis</td>
<td>14</td>
</tr>
<tr>
<td>3.4 Satisfiable modulo theory</td>
<td>15</td>
</tr>
<tr>
<td>3.4.1 String solvers</td>
<td>15</td>
</tr>
<tr>
<td>3.5 Contribution</td>
<td>17</td>
</tr>
<tr>
<td>4 Design</td>
<td>18</td>
</tr>
<tr>
<td>4.1 Concepts</td>
<td>18</td>
</tr>
<tr>
<td>4.1.1 String Variables</td>
<td>18</td>
</tr>
<tr>
<td>4.1.1.1 Local variables</td>
<td>18</td>
</tr>
<tr>
<td>4.1.1.2 Field variables</td>
<td>19</td>
</tr>
<tr>
<td>4.1.1.3 Formal variables</td>
<td>19</td>
</tr>
<tr>
<td>4.1.2 String Constraints</td>
<td>20</td>
</tr>
<tr>
<td>4.2 Constraint Generation</td>
<td>21</td>
</tr>
</tbody>
</table>
Abstract
Web applications are exposed to myriad security vulnerabilities related to malicious user string input. In order to detect such vulnerabilities in Java web applications, this project employs string constraint analysis, which approximates the values that a string variable in a program can take on. In string constraint analysis, program analysis generates string constraints – assertions about the relationships between string variables. We design and implement a dataflow analysis for Java programs that generates string constraints and passes those constraints to the CVC4 SMT solver to find a satisfying assignment of string variables. Using example programs, we illustrate the feasibility of the system in detecting certain types of web application vulnerabilities, such as SQL injection and cross-site scripting.
I would like to thank my three thesis readers, each having played a crucial role in my undergraduate experience as a computer scientist.
This work would not have been possible without my advisor, Professor Steve Chong. I had always been interested in programming languages since stumbling upon the seemingly esoteric programming language blog, Lambda the Ultimate. Through Steve’s courses and advising, I was able to pursue my curiosity to the fullest. I appreciate the extraordinary amount of attention that he gives to undergraduate researchers and his initiative in uniting undergraduate thesis writers in computer science.
I would have been much worse prepared for the undertaking of a thesis without Professor Krszysztof Gajos, who patiently guided me through my first major research project. He has provided me with invaluable advice for both maturing as a researcher – guiding me in the right direction, but always encouraging autonomy – and as an individual – pushing me to find my “superpowers” outside of academia.
Finally, I am grateful to Professor Greg Morrisett, whose undergraduate compilers course provided a crucial foundation for my understanding of dataflow analysis. Many of your students, including me, pick up your passion for the beauty of functional programming.
This project was made possible by the incredible patience of Andrew Johnson. It depended on his work with the Accrue Bytecode analysis framework. More importantly, I am thankful of the time that he took to answer my flood of questioning emails.
I cherish the opportunities provided by the Harvard Computer Science department. The faculty is incredibly supportive, and I believe that a positive undergraduate research experience is within grasp for any student in the department.
Thank you to Ruth Fong for her encouragement and support in my quest to become a computer scientist.
I owe my life to my family, who is forever supportive of my endeavors – especially research. Thank you, Mom, Dad, and Richard.
Chapter 1
Introduction
Web applications are exposed to myriad security vulnerabilities related to malicious user string input. Web servers often accept arbitrary user input through a variety of sources, such as form fields, URL parameters, and cookies. Common examples of such vulnerabilities are SQL injection, where an attacker can manipulate the database, or cross-site scripting, where an attacker can execute arbitrary code in a user’s browser.
These security flaws can potentially be prevented by analyzing the code of the web application beforehand. In order to detect such vulnerabilities in Java web applications, this project employs string constraint analysis, which approximates the values that a string variable in a program can take on. A string constraint asserts a relationship between string variables. For example, consider the following constraint for string-typed variables $x, y, z$. If we have the constraint that $x$ is the concatenation of $y, z$, then we assert that the string values that $x$ could take on is equivalent to the set of string values that $y$ could take on concatenated with the set of string values that $z$ could take on.
If we know what values a string variable can take on at a given point in time, then we may be able to detect a vulnerability. For example, consider a basic application that takes user input and submits it to the SQL server. If our analysis finds that the query string variable fits the form of a valid SQL query that allows the user to arbitrarily manipulate the database, then we conclude that the program contains a SQL injection vulnerability.
We design and implement a dataflow analysis for Java programs that generates string constraints using dataflow analysis. It translates these constraints to the language of a satisfiable modulo theory solver to find a satisfying assignment of the string variables in the program. Using example programs, we illustrate the feasibility of the system in detecting certain types of web application vulnerabilities.
1.1 Motivation
Web applications that store or manipulate user input are at risk of security vulnerabilities. This is extremely common. Many vulnerabilities caused by untrusted data, such as cross-site scripting and SQL injection attacks, are ranked in the top 10 most common web attacks by the Open Web Application Security Project [10].
Ultimately, these security vulnerabilities are caused by developer error in the design of the application. Sensitive strings may be improperly sanitized, allowing users to provide malicious strings that exploit some aspect of the application. Static analysis aims to analyze an application codebase without actually executing code, which can be a convenient way for developers to secure code. This project offers another approach to static analysis, leveraging the capabilities of satisfiable modulo theory solvers to detect potential vulnerabilities.
Chapter 2
Related work
2.1 String analysis
Past work has used string constraint analysis to analyze string expressions of programs and detect security vulnerabilities.
Christensen et al. design an algorithm that associates each string expression with a context-free grammar. The context-free grammar represents the set of strings that can be generated by a string expression [2]. In this case, the constraints are used to represent context-free grammars, which are eventually approximated with regular languages.
The result of this work was released as the Java String Analyzer (JSA), which computes the resulting automata for each string expression in a Java program. AMNESIA, a system for detecting SQL injection attacks in Java web applications, combines JSA string solving with runtime monitoring [5].
Fu et al. describe a formalism for string constraints called Simple Linear String Equations. They implement an algorithm to solve these constraints for Java. This system is packaged as the constraint solver SUSHI. They apply the constraint solver to XSS detection [3].
BEK uses a representation of symbolic finite automata with SMT solvers to develop a language and system for analyzing string sanitization functions, which are often the source of cross-site scripting vulnerabilities [6].
2.2 Static analysis of web applications
Much work has been done in security analysis of web applications using various static analysis techniques. Due to the sheer volume of work done in this area, the projects are not enumerated here.
A particularly relevant project is Framework For Frameworks (F4F). It uses taint analysis – tracking the flow of potentially sensitive information in a program – to support modern Java web application frameworks, such as Java EE and Struts. Similar to this project, it uses parts of the Watson Libraries for Analysis (WALA) framework [15]. A core part of the F4F project is creating an end-to-end system for static analysis of a web application, handling analysis of difficult portions of frameworks such as XML configurations.
2.3 String solvers
Although this work does not directly explore techniques for SMT solvers, theorem proving, and string formulas, it leverages existing work in string solvers. This work uses the string theory capabilities of the SMT solver CVC4 [1]. Support for the string theories was recently added to CVC4, allowing string formulas that assert relations such as string equality, concatenation, length, substring, and set membership [8].
Kaluza, a string solver developed as part of the JavaScript symbolic execution framework Kudzu, uses a constraint language that supports regular expressions, length, and concatenation. The Kaluza string solver uses part of the HAMPI implementation to solve constraints [14].
Similar to CVC4, Z3-str is a project built on top of Microsoft’s existing theorem prover, Z3, allowing it to integrate with logic over other datatypes. The authors apply Z3-str to finding remote code execution vulnerabilities [16].
Other existing string solvers take different approaches to defining and solving string constraints. HAMPI solves string constraints primarily by checking for membership of a string in a context-free grammar [7]. For instance, HAMPI allows the user to define regular and context-free languages and assert membership of a string variable in the language. The authors evaluate the tool on PHP programs containing SQL injection vulnerabilities.
Chapter 3
Technical Background
3.1 String-based Security Vulnerabilities
In this project, we focus on the applications of string solving to two types of vulnerabilities: SQL injection and cross-site scripting.
3.1.1 SQL Injection
*SQL injections* are string-based vulnerabilities where untrusted input manipulates SQL statements submitted to the database. Because an attacker can construct arbitrary queries, this vulnerability gives the attacker power over the database – selecting sensitive data, modifying existing data, or administrating the database [11].
**Example: Classical SQL Injection** Consider the following example from the OWASP SQL Injection testing page [13].
Suppose the following query is constructed dynamically with variables $\text{ exttt{username}}$ and $\text{ exttt{password}}$.
\[
\text{SELECT * FROM Users WHERE Username='}\text{ exttt{username}}\text{' AND Password='}\text{ exttt{password}}\text{'}
\]
Given a query result set containing multiple users, the server will likely authenticate the user using the first set of matching credentials. Note that if the user provides a username and an *incorrect* password, the resulting query set will be empty. However, suppose instead that a malicious user chooses to provide the following input:
\[
\text{ exttt{username}} = "1' or '1' = '1"
\]
\[
\text{ exttt{password}} = "1' or '1' = '1"
\]
Let us examine the resulting query by substituting in the values of the variable:
```
SELECT * FROM Users WHERE Username='1' OR '1' = '1'
AND Password='1' OR '1' = '1'
```
Since '1' = '1' is always true, then this SQL statement has the effect of selecting all users from the database – authenticating the attacker as the first user in the resulting query set. Additionally, the first user in the database is often the administrative user.
### 3.1.2 Cross-site scripting
Cross-site scripting (XSS) is a category of web application vulnerabilities where untrusted input allows an attacker to execute arbitrary code on behalf of visiting users to a webpage.
There are two main categories of XSS vulnerabilities: persistent and reflected.
#### 3.1.2.1 Persistent (stored) XSS
In persistent XSS, malicious users provide input that is persisted into the database, such that rendering the input allows the malicious user to run an arbitrary script. Since this information is stored in the server and later rendered in the webpage, this allows an attacker to run scripts on the clients of all future users.
**Example** An example of a persistent XSS vulnerability is unsanitized comments on a blog. Suppose a blog displays a list of comments below each blog post. In the case of a benign user, a comment will likely only contain formatting HTML and text. However, suppose a malicious user submits the following comment:
```
<script type="text/javascript">alert(1);
</script>
```
Since the comments use unescaped HTML, future visitors will view the comment, consequently running the script contained in the body. An `alert` is fairly benign, but an attacker could replace the comment body with arbitrary JavaScript.
Most modern blogs protect against such a straightforward exploit, but this example conveys the basic idea behind persistent XSS: an attacker can store information in the database that will be rendered to future visitors of the page, running a potentially malicious script.
3.1.2.2 Reflected XSS
In reflected XSS, malicious users provide input in a web request that is later rendered onto the page by the server. Potential vectors for this input include URL parameters, form fields, and cookies. This is called reflected XSS, since the input is “reflected” back onto the page by the server’s response, such as an error message or user notification.
In contrast with persistent XSS, where the script will be run to all future visitors of a web page, reflected XSS is frequently delivered to victims through a carefully crafted URL.
Example: Query Parameter Consider the example of a search engine that includes the search query in the URL. For example:
http://searchengine.com/search.php?q=programming
The web page itself will likely display the search query on the user-facing page. However, a malicious user can also craft the following search query:
http://searchengine.com/search.php?q=<script>alert(1);</script>
The user input is reflected in the contents of the webpage. An attacker could send a URL with more malignant code to victims – potentially masked behind a link shortener – where the code would execute upon visiting the link.
Example: Form field Consider the following example from the OWASP testing page, illustrating the ability to run arbitrary JavaScript without using a <script> tag. [12] Consider an HTML form that pre-populates a field with some unsanitized input from the user (INPUT_FROM_USER).
<input type="text" name="state" value="INPUT_FROM_USER">
Suppose an attacker provides the following input:
" onfocus="alert(document.cookie)"
Substituting in the user input, the resulting input field becomes:
<input type="text" name="state" value="" onfocus="alert(document.cookie)">
### 3.2 Java bytecode
Unlike programming languages like C, where source code compiles directly to assembly, Java source code compiles into Java bytecode. Java bytecode serves as platform-independent instructions for the Java virtual machine.
In this project, we perform our analysis on Java bytecode rather than Java source code. We are only concerned with a subset of Java bytecode instructions – in particular, those dealing with fields, variables, and function calls. To give a broad illustration of the functions of bytecode, summaries of the bytecode instructions relevant to this work are detailed below. Each one has an example of the approximate corresponding scenario in Java source code.
<table>
<thead>
<tr>
<th>Operation</th>
<th>Description</th>
<th>Code example</th>
</tr>
</thead>
<tbody>
<tr>
<td>getstatic</td>
<td>Get static field from class</td>
<td>local = foo.staticf</td>
</tr>
<tr>
<td>putstatic</td>
<td>Set static field in class</td>
<td>foo.staticf = local</td>
</tr>
<tr>
<td>getfield</td>
<td>Get field in object</td>
<td>local = foo.f</td>
</tr>
<tr>
<td>putfield</td>
<td>Set field in object</td>
<td>foo.f = local</td>
</tr>
<tr>
<td>ret/return</td>
<td>Return a local variable or void from a subroutine</td>
<td>return local</td>
</tr>
<tr>
<td>invokedynamic</td>
<td>Various types of method invocations</td>
<td>s.toString(); foo.bar()</td>
</tr>
</tbody>
</table>
**Table 3.1: Examples of relevant Java bytecode instructions [9]**
### 3.3 Dataflow analysis
*Dataflow analysis* describes analysis performed to determine facts about a program at given points in the program. An example of dataflow analysis is liveness analysis, where, for any given point in the program, the analysis computes the set of live variables – variables whose values may be used in the future.
Dataflow analysis uses a *control flow graph* of the program. A control flow graph is a directed graph where each node contains a statement. In this case, each node is an instruction of Java bytecode.
In practice, instructions are represented by an *intermediate representation* of Java bytecode instructions. Intermediate representation refers to a representation of a language using a data structures – useful for dataflow analysis, compilation to a target language, or optimization.
In our analysis, the dataflow analysis is used to compute constraints for mutable string builder variables. This is described in more detail later.
3.3.1 Call graphs
*Pointer analysis* is a type of analysis that determines which memory locations a pointer can point to. In this project, an existing pointer analysis is used to generate a *call graph*. A call graph is a directed graph that captures the relationship between method calls in a program.
A *context-sensitive* call graph distinguishes between different call stacks with which a method may be called. This is more precise than a non-context-sensitive call graph. For example, it differentiates between the case when a same method is called multiple times but with different arguments.
In a context-sensitive analysis, each call graph node consists of two parts: a method and a *calling context*. The contents of a calling context can vary with analysis, but a calling context captures information about a call, potentially distinguishing two different calls of the same method. For example, a simple calling context could contain the line number of the method call, and two calls to a method from different lines of source code would have different calling contexts.
The example below, due to Grove et al. [4], shows a context-sensitive call graph. In the figure, the method `test()` calls `A()`, `B()`, each of which call the method `sumArea()`. However, the subscripts `0`, `1` on the nodes denote different calling contexts of the calls to `sumArea()` – one is called from within `A()`, while the other is called from within `B()`.

3.3.2 Static single assignment
Certain intermediate representations satisfy the property of static single assignment. In static single assignment, variables in bytecode can be the left-hand side of an assignment at most once. For example, if the same variable is assigned twice in source code:
\[
\begin{align*}
x & := y \\
u & := x \\
x & := z \\
v & := x
\end{align*}
\]
The resulting SSA representation of these instructions will create new variables for each instance of the variable $x$.
\[
\begin{align*}
x_1 & := y \\
u & := x_1 \\
x_2 & := z \\
v & := x_2
\end{align*}
\]
The intermediate representation used in this project is partial static single assignment. While local variables follow the constraints of static single assignments, the variables representing the field of an object can have multiple assignments.
3.3.3 Intraprocedural analysis
In intraprocedural dataflow analysis, the results of the analysis are derived from a single function. An intraprocedural analysis computes facts by flowing over each bytecode instruction within a method.
When an intraprocedural analysis stands alone, the results of invoking another function are approximated rather than analyzing and using the results of the invoked function. Often, however, an intraprocedural analysis is combined with an interprocedural analysis to compute facts about a whole program.
3.3.4 Interprocedural analysis
While intraprocedural analysis analyzes the contents of a single method, interprocedural dataflow analysis accounts for method invocations. Each time a method is invoked in an intraprocedural analysis, an interprocedural analysis framework triggers another intraprocedural analysis of the invoked method. An interprocedural analysis framework will track the results and compute a fixpoint for facts, handling cases such as recursive functions.
3.4 Satisfiable modulo theory
Satisfiable modulo theories (SMT) are a type of decision problem – a problem that
returns a yes or no answer. SMT generalizes the Boolean satifiability problem (SAT).
In the SAT decision problem, one must determine whether a boolean formula has a
satisfying assignment. For example, the formula:
\[(x \land y) \lor (y \land \neg z)\]
has the following satisfying assignment:
\[x = \text{true}, y = \text{true}, z = \text{false}\]
In contrast, SMT generalizes SAT. Boolean variables can be replaced with other predi-
cates, expanding the formulas beyond boolean variables. Each of these types are referred
to as theories. An SMT problem can incorporate the theory of real numbers, the the-
ory of lists, and so on. In this work, we are particularly interested in SMT problems
employing the theory of strings – solving formulas with string predicates.
3.4.1 String solvers
The term string solver will be used throughout this work, referring specifically to SMT
solvers with the capability of solving string formulas. Just as SAT solvers find satisfying
boolean assignments for assertions, string solvers find satisfying string assignments.
Consider the following example with string predicates. If we have the following asser-
tions:
\[(s = \langle \text{any string} \rangle) \land (r = \text{"bar"}) \land (t = \text{concat}(s, t)) \land (t \text{ begins with "foo"})\]
A solution that satisfies these formulas would be:
\[s = \text{"foo"}, r = \text{"bar"}, t = \text{"foobar"}\]
However, note that the following would also be a solution:
\[s = \text{"fooooooooddaaa"}, r = \text{"bar"}, t = \text{"foobar"}\]
Given the original formula, a string solver would either return at least one solution or indicate that no solution exists.
3.5 Contribution
The primary contribution of this work is a tool that leverages an existing string solver for solving string constraints for Java bytecode programs, illustrating the feasibility of an end-to-end pipeline for generating and solving string constraints. We built a tool that achieves this through the following components:
1. A dataflow analysis that generates string constraints from Java programs
2. A translation from string constraints to the language of SMT solvers
Chapter 4
Design
In this section, we describe the design of the analysis that generates string constraints from a given Java program.
4.1 Concepts
4.1.1 String Variables
In this project, a *string variable* represents a string manipulated or computed by the program. Concretely, this encompasses immutable Java `String` or mutable `StringBuilder` types. String variables encapsulate two types of variables within a program:
1. *Program variables*, which represent local variables or object fields.
2. *Formal variables*, which represent the formal arguments or return values of a method.
Ultimately, the purpose of string variables is to determine the string values that a string variable can take on in the input program. Given string variables, we will declare constraints such as “the string value that `sv1` takes on is equal to that of `sv2`”. The domain of constraints is described in section 4.1.2.
4.1.1.1 Local variables
A *local variable* refers to any variable declared within a method.
In the example source code below, a string variable would be associated with each of the variables `foo`, `bar`:
public void myMethod(String a) {
String foo = a;
String bar = String.concat(a, a);
}
4.1.1.2 Field variables
A field variable is a type of program variable representing a field in a Java object.
In the example source code below, both f0, f1 would be represented in the analysis by field variables. String literals are also represented by string variables, and in the example below, the string "foo" would be represented by a third string variable.
public class Foo {
private String f0;
private static String f1 = "foo";
// ...
}
4.1.1.3 Formal variables
Formal variables are used to summarize information about methods. A formal variable corresponds to either a method argument or a method return value. The high-level concepts are described below, and its use is described in further detail in section 4.2.2.1 on summary nodes.
In the case of method arguments, a formal string variable is associated with each string parameter of a method and its call graph node. For example, given two call graph nodes for the same method, each will have a different formal string variable associated with the same string-typed method parameter.
Consider the following method with string-valued arguments:
public void myMethod(String arg0, int arg1, String arg2) {
// ...
}
There will be a formal string variable associated with the string-valued arguments arg0 and arg2.
In the case of return values, a formal string variable is used to represent the value returned by a method. A string method will return some program variable. This program
variable will be associated with the formal return variable for the method. This association is described in more detail in section 4.2.2. This applies only to methods that return a string type, e.g.:
```java
public String anotherMethod() {
// ...
}
```
### 4.1.2 String Constraints
*String constraints* are used to describe the relationship between string variables. They capture information about the string values that a string variable can take on in the program.
The domain of string constraints generated by this analysis is described below.
We first define the following domains:
- $v \in \text{Var}$: string variables
- $s \in \text{String}$: string literals (e.g., “foo”)
- $m \in \text{CGNode}$: call graph nodes
Let $\sigma$ be a solution to the constraints, having the domain:
$$\sigma : \text{Var} \rightarrow \text{String}$$
$\sigma$ maps string variables to string literals. For example, an explicit instance of $\sigma$ would be:
$$\sigma_0 = \{ v_1 \mapsto "foo"; v_2 \mapsto "bar" \}$$
For some constraint $C$, we say that the solution $\sigma$ *satisfies the constraint* $C$ if:
$$\sigma \models C$$
The Table 4.1 defines the domain of constraints on the left side. On the right side, it defines how a solution $\sigma$ satisfies the constraint.
\begin{align*}
v &= s \\
v_1 &= v_2 + v_3 \\
v_1 &= v_2 \\
v &= \phi(v_1, \ldots, v_n) \\
m(v_1, \ldots, v_n) \lor \cdots \lor m(v_n, \ldots, v_n)
\end{align*}
\begin{align*}
\sigma &\models v = S \iff \sigma(v) = S \\
\sigma &\models v_1 = v_2 + v_3 \iff \sigma(v_1) = \sigma(v_2) + \sigma(v_3) \\
\sigma &\models v_1 = v_2 \iff \sigma(v_1) = \sigma(v_2) \\
\sigma &\models v = \phi(v_1, \ldots, v_n) \iff \exists i \in \{1, \ldots, n\}. \sigma(v) = \sigma(v_i) \\
\sigma &\models m(v_1, \ldots, v_n) \lor \cdots \lor m(v_n, \ldots, v_n) \iff \exists i \in \{1, \ldots, n\}. \sigma(v_i) = f_1 \land \cdots \land \sigma(v_n) = f_i \text{ where } formals(m) = (f_1, \ldots, f_n)
\end{align*}
Table 4.1: Summary of the constraints used in this project
### 4.2 Constraint Generation
Our string constraint analysis generates string constraints using an interprocedural dataflow analysis on the control flow graph of the program. These constraints are later translated into the language of the string solver, which finds a satisfying solution for the constraints.
String constraints are primarily generated from the program by doing one pass over the control flow graph. However, multiple passes may be required for mutable strings. In order to handle mutable strings (StringBuilder), we use dataflow analysis to track string variables corresponding to StringBuilder at some point in the program. This is further described below in the section on string builders.
#### 4.2.1 Intraprocedural Analysis
In the intraprocedural analysis, we handle cases for each possible Java bytecode instruction, potentially generating a string constraint.
First, we describe the simpler cases. An assignment from a field to a local variable (or vice versa) generates a COPY constraint. When we encounter a phi node, a PHI constraint is generated.
We describe constraint generation for library methods and string builders below.
#### 4.2.1.1 String Library Methods
When we encounter a method invocation, we first check if it is a method in the String library that is specially supported by the analysis. If so, we ignore the standard interprocedural analysis and generate specific constraints. The following String library methods are supported:
- new String(s) (constructor)
- String.valueOf(s) (string representation)
• `s.toString()` (to string)
• `String.concat(s, t)` (concatenation)
The first three generate a Copy constraint. For example, the bytecode corresponding to the constructor method invocation of the code below:
```java
String s = new String(t);
```
will generate the following constraint:
\[ s = t \quad \text{[COPY]} \]
Similarly, a call to `String.concat(s, t)` will generate a CONCAT constraint.
### 4.2.1.2 String Builders
In Java, string builders are a class for constructing mutable strings. In order to handle string builder manipulations, we create a new string variable each time a string builder is manipulated.
By creating a new string variable, we represent a snapshot of the mutable string builder at a certain program point. The dataflow analysis computes a variable context: a mapping from program variables to string variables. After a string builder program variable is changed, while the program variable may have been mutated, the context tracks the most recent string variable associated with the string builder.
In a node of the control flow graph with multiple incoming nodes, we compute the confluence and merge the incoming contexts by creating PHI constraints for string variables associated with the same program variable.
**Example** Consider the following example below, where two strings, `s1`, `s2`, are appended to the string variable `sb`.
```java
StringBuilder sb = new StringBuilder("");
sb.append(s1); // new string variable created - sb1
sb.append(s2); // new string variable created - sb2
```
Each time that `sb` is manipulated by appending another string, a new string variable is created. The current context computed by the dataflow analysis is updated, associating the most recent string variable `sb2` (generated by `sb.append(s2)`) with the program variable `sb`. After this code executes, if we were to look up the string variable associated with `sb`, then we would find the string variable `sb2`.
String Builder Library Methods The following StringBuilder (and the synchronized equivalent, StringBuffer) library methods are supported:
- new StringBuilder(s) (constructor)
- sb.toString(sb) (to string)
- sb.append(s) (append)
More importantly, note that the Java syntactic convenience of appending strings with + is compiled in bytecode to corresponding calls to StringBuilder.append():
```java
String s = t + v; // t, v are String variables
String fb = "foo" + "bar";
String newS = s + "foo";
```
Our implementation handles this syntax, which is frequently used by programmers to construct strings.
4.2.2 Interprocedural Analysis
We describe how the interprocedural analysis handles method invocations. First, we describe the concept of summary nodes, then we describe how these are used to generate the CALL constraint.
4.2.2.1 Summary Nodes
Summary nodes contain information about the string variables associated with a call graph node. Their purpose is to capture information about method calls, allowing us to generate string constraints in an interprocedural analysis.
Recall that a call graph node consists of two parts: a method and a calling context. There exists a one-to-one correspondence between call graph nodes and summary nodes.
Intuitively, a summary node contains information about the string variables of a single method. Note that new variables are generated for each calling context – two different calling contexts have different formal variables.
Formally, a summary node consists of:
1. A list of formal parameter variables $f_1, \ldots, f_n$ for each string-typed parameter
2. A formal return variable $r_m$ (if the method returns a string type)
4.2.2.2 Handling formals
A method has a set of formal arguments, corresponding to the parameters of the method. When a method is called, a series of actual arguments are supplied to the method. In this section, we describe the process of generating constraints that link the actual arguments to the formal arguments.
Suppose that the two calls below to the method `bar()` have the same calling context—that is, the calls will correspond to the same call graph nodes.
```java
private String foo () {
String firstCall = bar("a", "b");
String secondCall = bar("c", "d");
}
```
The following constraint is generated, supposing there exists some string variables `a`, `b`, `c`, `d` that represent the literals "a", "b", "c", "d":
```
bar(a, b) ∨ bar(c, d)
```
Note that this constraint is only satisfied by a solution `σ` when, for the formal variables `f_1`, `f_2` of `bar()`:
```
σ ⊨ bar(a, b) ∨ bar(c, d) ⇐⇒ (σ(a) = f_1 ∧ σ(b) = f_2) ∨ (σ(c) = f_1 ∧ σ(d) = f_2)
```
This captures the idea that the actual arguments to a method should be “grouped” together for a more precise analysis. The possible two arguments provided to `bar()` include the argument set ("a", "b") and ("c", "d"), but note that our approach to generating constraints disallows the combination ("a", "d"), since `bar()` is never called with this combination of arguments.
In this example, we assume that both calls have the same calling context and consequently the same summary node. Note that this disjunction of argument sets is grouped together by summary node (and thus, call graph node) and not method. The constraints will distinguish argument sets between calls to the same method with different calling contexts.
4.2.2.3 Handling return
The bytecode instruction for return takes a program variable as an argument—the variable to be returned. When we flow over a return statement in bytecode, we add the returned variable to a set of tracked variables.
After analyzing a method, we add a new PHI constraint to link the formal return variable to the possible tracked variables. For a given summary node, we generate the constraint:
\[
m_r = \phi(r_1, \ldots, r_n) \quad \text{[PHI]}
\]
where \( r_1, \ldots, r_n \) are the variables potentially returned by the method at some point in its execution.
### 4.2.2.4 Example
We describe an example of generating constraints in a very basic program. The program calls a method, `addBar()`, that appends the string literal “bar” to its argument. Consider the following program:
```java
public class InterproceduralExample {
static final String s = "foo";
public static void main(String[] args) {
String s1 = s;
String s2 = addBar(s1); // should be "foobar"
}
private static String addBar(String arg) {
String local = "bar";
return arg.concat(local);
}
}
```
We walk through the example line-by-line, using names to denote the locations of string variables (e.g., `main-literal-foo` refers to a string variable in `main()` representing the literal “foo”). Our analysis proceeds by method.
**Analyzing `main()`** When we access a static field:
```java
String s1 = s;
```
it generates the constraint:
```java
main-literal-foo = "foo" \quad \text{[CONSTANT]}
```
When we make a call to `addBar(s1)`:
```java
String s2 = addBar(s1); // should be "foobar"
```
we find the summary node for the call graph node corresponding to the call, and we
link the actual variable (main-literal-foo, which represents s1 in the program) to the
formal variable. We also link the return variable of addBar() to the string variable
corresponding to s2. This generates the constraint:
\[
\begin{align*}
\text{addBar}(\text{main-literal-foo}) & \quad [\text{CALL}] \\
\text{main-local-}s_2 = \text{addBar-return} & \quad [\text{COPY}]
\end{align*}
\]
**Analyzing addBar()** Our interprocedural analysis now delves into the invoked method,
performing an intraprocedural analysis on addBar().
We link the formal variables to the corresponding local arguments. In bytecode, we see
that addBar() is defined with a parameter named arg, which acts as a local variable:
\[
\text{private static String addBar(String arg) \{ ...}
\]
This generates the constraint:
\[
\text{addBar-f}_{0} = \text{addBar-local-arg} \quad [\text{COPY}]
\]
As we analyze the body of addBar(), we encounter a string literal assignment:
\[
\text{String local = "bar";}
\]
generating the constraint:
\[
\text{addBar-literal-bar = "bar"} \quad [\text{CONSTANT}]
\]
Finally, we want to return the result of concatenating the string literal:
\[
\text{return arg.concat(local);}
\]
Note that the bytecode implicitly creates a new local variable \(v_0\) in the bytecode, not
corresponding to any variable in the source code. This first generates the constraint:
\[
\text{addBar-local-}v_0 = \text{addBar-local-arg}++\text{addBar-literal-bar} \quad [\text{CONCAT}]
\]
We link the formal return variable using a \text{Phi} constraint of all of the possible local
variables that can be returned. In this case, there is only one, meaning that the return
statement generates the following constraint (equivalent to a \text{Copy} constraint):
\[
\text{addBar-return} = \text{phi(addBar-local-}v_0) \quad [\text{Phi}]
\]
**Solution** These constraints are translated to the language of the string solver, which solves for a satisfying assignment to all of the variables. Since this program is simple, we have an intuition that our solver should find that the variable `main-local-s_2` will be “foobar”.
Consider the following solution. By inspection, it can be confirmed that this satisfies the constraints.
\[
\sigma = [\text{addBar-f}_0 \mapsto \text{"foo"}]
\]
\[
\sigma = [\text{main-literal-foo} \mapsto \text{"foo"}]
\]
\[
\sigma = [\text{addBar-local-arg} \mapsto \text{"foo"}]
\]
\[
\sigma = [\text{addBar-literal-bar} \mapsto \text{"bar"}]
\]
\[
\sigma = [\text{addBar-local-v}_0 \mapsto \text{"foobar"}]
\]
\[
\sigma = [\text{addBar-return} \mapsto \text{"foobar"}]
\]
\[
\sigma = [\text{main-local-s}_2 \mapsto \text{"foobar"}]
\]
### 4.3 Limitations
When our tool analyzes for security vulnerabilities, we will add more constraints relating to the variable of interest. For example, in the case of SQL injection, this is the string that is sent to the database as a query. This is further elaborated in the section on evaluation.
The analysis is neither sound nor complete. If the string solver does not find a satisfying solution, this does not guarantee that the program is free of vulnerabilities. If the string solver finds a satisfying solution, this does not guarantee that the program contains a vulnerability.
Our analysis is useful as a vulnerability finding tool, which is demonstrated in its evaluation in the next section. If the string solver returns a satisfying solution, it provides a starting point for the programmer to find potential security flaws.
There are three notable limitations to our analysis.
First, the analysis only generates constraints for a few major string operations, such as concatenation and assignment. It excludes many elementary operations that manipulate strings – such as substring replacement, regular expression replacement, and character replacement – due to the complexity of these analyses. These operations are useful in a precise analysis, since many security related functions, such as sanitizers, employ...
such manipulations. For example, our analysis currently cannot analyze a SQL injection sanitizer that escapes single quotations, substituting ‘ for \’.
Second, the analysis does not support full-fledged web applications. Performing static analysis on the frameworks and XML configurations that most Java web frameworks use is complex, illustrated by projects such as Framework 4 Frameworks [15]. Our evaluation is performed on toy Java applications that simulate features of web application frameworks, such as web requests and database connections.
Third, due to the limitations in capabilities of available string solvers, a satisfying solution binds a string variable to exactly one string. In contrast, there are alternative ways of expressing the set of strings that a string variable can take, such as associating each string variable with a context-free grammar approximating a set of strings. This leads to certain limitations in the analysis. For example, in a loop, where a variable takes on different values during through iterations of the loop, our ability to represent such variables is severely limited.
Chapter 5
Implementation
5.1 Constraint Analysis
The analysis was developed using Accrue Bytecode, an existing framework for Java bytecode analysis. Accrue Bytecode leverages the IBM T.J. Watson Libraries for Analysis (WALA) framework for representing Java bytecode.
The analysis and translation were written in Java.
5.2 SMT Solver
The CVC4 SMT solver was used to solve string constraints. CVC4 was selected over other existing string solvers, such as Kaluza [14], HAMPI [7], and Z3-str [16], for its expanded support of string formulas. The constraints were solved using the CVC4 Java API bindings.
5.3 Evaluation
The tool was run on example programs using a 2 GHz Intel Core i7 Macbook Pro with 8 GB of RAM.
Chapter 6
Evaluation
The constraints that we generate provide a foundation for approximating the string values that variables take on at given program points. In this section, we demonstrate how our analysis can be augmented to detect security vulnerabilities in Java programs by adding certain constraints.
To evaluate our end-to-end tool for generating and solving constraints for a given program, we tested it on two example programs. These example programs contain SQL injection or cross-site scripting vulnerabilities.
6.1 Example programs
6.1.1 SQL Injection
We evaluated the tool on a 43 line example Java program, SQLToyApp, that simulates the login of a website. It accepts a username and password as input, sending the pair of strings to the database to validate. The full code is included in the appendix.
Given user inputs $\text{username}$, $\text{password}$, SQLToyApp sends the following query:
\[
\text{SELECT * FROM users WHERE username} = \text{"username"} \\
\text{AND password} = \text{"password"}
\]
Our strategy for determining whether the exists a SQL injection follows. Following the model of evaluation for the HAMPI string solver, we test whether there is a satisfying assignment of strings with the query string containing the substring "1' or '1' = '1". [7] To achieve this, we add the following assertion in the string solver, using the
string variable q for the query string sent to the database.
\[ q \text{ contains } "1' or '1' = '1" \]
We fix the input for $\text{username}$ to be "admin", assuming that the attacker aims to login a username for the administrative account. However, note that an attacker could also input \texttt{username = "'1 OR '1' = '1"", which would return a query set containing all users – the first of which would be authenticated in the login.}
This is motivated by the fact that the most common SQL injection attacks take advantage of unescaped quotation and tautologies (or '1 = '1'). More complex SQL injection vectors, such as those with stored procedures, would require a different approach.
**Results** Our tool ran the pointer analyses, generated 30 string constraints, and discovered a satisfying solution containing a vulnerability in 9.054 seconds. The satisfying solution contained 31 string variables. Of particular interest is the assignment for the query variable q, for which the string solver solution finds that:
\[
q = \text{SELECT * FROM users WHERE username = 'admin' AND password = '1' or '1' = '1'}
\]
This corresponds to the scenario where a malicious user provides the following inputs: $\text{username} = 'admin$ and $\text{password} = 1' or '1' = '1$.
This illustrates that the tool produces a string assignment that highlights a SQL injection vulnerability in SQLToyApp. Given a Java program as input and additional constraints designating the strings of interest, our tool outputs a satisfying solution that indicates a SQL injection vulnerability.
### 6.1.2 Cross-site scripting
We evaluated the tool on a 32 line example Java program, XSSToyApp, that simulates the canonical example of a blog post, rendering an HTML page that takes a user comment as input. The full code is included in the appendix.
Recall that if user comments in a blog are unescaped, then a malicious user can simply provide \texttt{<script>} tags containing arbitrary code that will be executed by any future clients viewing the comments. Our strategy for finding an XSS vulnerability is to add
the following assertion to the string solver, where \texttt{html} is the rendered HTML of the final webpage:
\[
\text{html contains "\texttt{<script>alert(1);</script>}"}
\]
where \texttt{alert(1)} serves as an arbitrary choice of JavaScript code. A malicious user would replace this with something more harmful.
\textbf{Results} Our tool ran the pointer analyses, generated 24 string constraints, and discovered a satisfying solution containing a vulnerability in 8.001 seconds. The satisfying solution for the tool assigns the following value to the string variable for the rendered HTML:
\begin{verbatim}
html = "<!DOCTYPE html>
<html>
<body>
<div><script>alert(1);</script></div>
</body>
</html>
\end{verbatim}
This corresponds to the scenario where a malicious user writes the following comment:
\begin{verbatim}
<script>alert(1);</script>
\end{verbatim}
Similar to the SQL injection example, this applies the tool to a program representative of the canonical persistent XSS vulnerability.
Chapter 7
Conclusion
We designed a tool to detect security vulnerabilities in Java web applications, evaluating the tool on simulated web applications.
First, the tool generated string constraints from a Java program using interprocedural dataflow analysis. Second, it translated the string constraints to the language of the CVC4 string solver. Finally, the string solver generated a satisfying assignment of string variables from the given constraints.
We evaluated the tool by demonstrating that it could find satisfying assignments indicative of security vulnerabilities – SQL injection and cross-site scripting – in example Java programs.
However, the tool was subject to certain limitations. Although the analysis was neither sound nor complete, the tool can be used to guide programmers to potential security vulnerabilities.
This work provides the foundation for an end-to-end tool that generates string constraints and pipes them into an SMT solver. Future work in the area could expand the tool to support the infrastructure of Java web frameworks and further string library operations, which would allow analysis of sanitizing functions commonly used to secure applications.
Finally, the goal of leveraging an existing string solver highlights the limitations of existing string solvers, which often return a satisfying assignment that assigns each string variable to a single string value. String solvers with more expressiveness for solutions, such as associating each string variable with a context-free grammar for the set of possible strings, would allow for a more powerful analysis.
Appendices
Appendix A
Example programs
Below are the example programs, SQLToyApp, XSSToyApp, used in the evaluation.
A.1 SQL Injection
```java
package stringconstraint.tests;
import java.lang.StringBuilder;
/** *
* An application that receives a username and a password from a form field
*/
public class SQLToyApp {
public static void main(String args[]) {
SQLToyApp app = new SQLToyApp();
app.login(args[0], args[1]);
}
public void login(String username, String password) {
String query = constructQuery(username, password);
DatabaseConnection dbc = new DatabaseConnection();
dbc.sendQuery(query);
}
private String constructQuery(String username, String password) {
StringBuilder query = new StringBuilder("SELECT * FROM users WHERE ");
query.append("username = '");
query.append(username);
query.append("'");
return query.toString();
}
}
```
```java
query.append(" AND ");
query.append("password = '");
query.append(password);
query.append("'");
query.append(";");
return query.toString();
}
/**
* Mock database connection.
*/
public class DatabaseConnection {
public void sendQuery(String q) {
// Do nothing.
}
}
Listing A.1: SQLToyApp, a program simulating a query for a user login
A.2 XSS
package stringconstraint.tests;
import java.lang.StringBuilder;
/**
* An example application that renders an HTML page containing
* an unescaped comment from a user.
*/
public class XSSToyApp {
public static void main(String args[]) {
// Suppose the comment, args[0], is retrieved from a database elsewhere
XSSToyApp app = new XSSToyApp();
app.renderPage(args[0]);
}
private String buildPage(String comment) {
StringBuilder sb = new StringBuilder("<!DOCTYPE html>");
sb.append("<html>");
sb.append("<body>");
sb.append("<div>");
sb.append(comment);
```
public void renderPage(String comment) {
String html = buildPage(comment);
// Do something with the built page.
}
Listing A.2: XSSToyApp, a program simulating the rendering of a webpage
References
|
{"Source-Url": "https://dash.harvard.edu/bitstream/handle/1/14398534/LI-SENIORTHESIS-2015.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 11919, "olmocr-version": "0.1.50", "pdf-total-pages": 41, "total-fallback-pages": 0, "total-input-tokens": 73224, "total-output-tokens": 14506, "length": "2e13", "weborganizer": {"__label__adult": 0.0003960132598876953, "__label__art_design": 0.00027823448181152344, "__label__crime_law": 0.000804901123046875, "__label__education_jobs": 0.0007443428039550781, "__label__entertainment": 5.990266799926758e-05, "__label__fashion_beauty": 0.0001493692398071289, "__label__finance_business": 0.00017905235290527344, "__label__food_dining": 0.0002770423889160156, "__label__games": 0.0006308555603027344, "__label__hardware": 0.0007410049438476562, "__label__health": 0.0004405975341796875, "__label__history": 0.00017905235290527344, "__label__home_hobbies": 7.832050323486328e-05, "__label__industrial": 0.00032329559326171875, "__label__literature": 0.0002290010452270508, "__label__politics": 0.0002512931823730469, "__label__religion": 0.0003390312194824219, "__label__science_tech": 0.01727294921875, "__label__social_life": 8.827447891235352e-05, "__label__software": 0.006282806396484375, "__label__software_dev": 0.96923828125, "__label__sports_fitness": 0.00029087066650390625, "__label__transportation": 0.00039267539978027344, "__label__travel": 0.0001499652862548828}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 55926, 0.01961]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 55926, 0.76343]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 55926, 0.8246]], "google_gemma-3-12b-it_contains_pii": [[0, 702, false], [702, 702, null], [702, 3498, null], [3498, 3498, null], [3498, 4326, null], [4326, 6327, null], [6327, 8354, null], [8354, 9246, null], [9246, 10549, null], [10549, 12708, null], [12708, 14086, null], [14086, 16078, null], [16078, 17822, null], [17822, 20197, null], [20197, 21733, null], [21733, 23598, null], [23598, 25252, null], [25252, 25375, null], [25375, 25862, null], [25862, 26984, null], [26984, 28550, null], [28550, 29832, null], [29832, 32140, null], [32140, 34095, null], [34095, 35782, null], [35782, 37729, null], [37729, 39139, null], [39139, 41053, null], [41053, 43212, null], [43212, 44333, null], [44333, 45052, null], [45052, 46427, null], [46427, 48528, null], [48528, 49538, null], [49538, 51146, null], [51146, 51157, null], [51157, 52104, null], [52104, 53088, null], [53088, 53283, null], [53283, 55073, null], [55073, 55926, null]], "google_gemma-3-12b-it_is_public_document": [[0, 702, true], [702, 702, null], [702, 3498, null], [3498, 3498, null], [3498, 4326, null], [4326, 6327, null], [6327, 8354, null], [8354, 9246, null], [9246, 10549, null], [10549, 12708, null], [12708, 14086, null], [14086, 16078, null], [16078, 17822, null], [17822, 20197, null], [20197, 21733, null], [21733, 23598, null], [23598, 25252, null], [25252, 25375, null], [25375, 25862, null], [25862, 26984, null], [26984, 28550, null], [28550, 29832, null], [29832, 32140, null], [32140, 34095, null], [34095, 35782, null], [35782, 37729, null], [37729, 39139, null], [39139, 41053, null], [41053, 43212, null], [43212, 44333, null], [44333, 45052, null], [45052, 46427, null], [46427, 48528, null], [48528, 49538, null], [49538, 51146, null], [51146, 51157, null], [51157, 52104, null], [52104, 53088, null], [53088, 53283, null], [53283, 55073, null], [55073, 55926, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 55926, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 55926, null]], "pdf_page_numbers": [[0, 702, 1], [702, 702, 2], [702, 3498, 3], [3498, 3498, 4], [3498, 4326, 5], [4326, 6327, 6], [6327, 8354, 7], [8354, 9246, 8], [9246, 10549, 9], [10549, 12708, 10], [12708, 14086, 11], [14086, 16078, 12], [16078, 17822, 13], [17822, 20197, 14], [20197, 21733, 15], [21733, 23598, 16], [23598, 25252, 17], [25252, 25375, 18], [25375, 25862, 19], [25862, 26984, 20], [26984, 28550, 21], [28550, 29832, 22], [29832, 32140, 23], [32140, 34095, 24], [34095, 35782, 25], [35782, 37729, 26], [37729, 39139, 27], [39139, 41053, 28], [41053, 43212, 29], [43212, 44333, 30], [44333, 45052, 31], [45052, 46427, 32], [46427, 48528, 33], [48528, 49538, 34], [49538, 51146, 35], [51146, 51157, 36], [51157, 52104, 37], [52104, 53088, 38], [53088, 53283, 39], [53283, 55073, 40], [55073, 55926, 41]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 55926, 0.06919]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
89c8bfa6c6d1a88034eb1382222fa58550b1042f
|
InstallShield 2019
InstallScript Debugger
User Guide
Legal Information
Book Name: InstallShield 2019 InstallScript Debugger User Guide
Part Number: ISP-2400-UG00
Product Release Date: April 2019
Copyright Notice
Copyright © 2019 Flexera. All Rights Reserved.
This publication contains proprietary and confidential information and creative works owned by Flexera and its licensors, if any. Any use, copying, publication, distribution, display, modification, or transmission of such publication in whole or in part in any form or by any means without the prior express written permission of Flexera is strictly prohibited. Except where expressly provided by Flexera in writing, possession of this publication shall not be construed to confer any license or rights under any Flexera intellectual property rights, whether by estoppel, implication, or otherwise.
All copies of the technology and related information, if allowed by Flexera, must display this notice of copyright and ownership in full.
Intellectual Property
For a list of trademarks and patents that are owned by Flexera, see https://www.flexerasoftware.com/producer/company/about/intellectual-property/. All other brand and product names mentioned in Flexera products, product documentation, and marketing materials are the trademarks and registered trademarks of their respective owners.
Restricted Rights Legend
The Software is commercial computer software. If the user or licensee of the Software is an agency, department, or other entity of the United States Government, the use, duplication, reproduction, release, modification, disclosure, or transfer of the Software, or any related documentation of any kind, including technical data and manuals, is restricted by a license agreement or by the terms of this Agreement in accordance with Federal Acquisition Regulation 12.212 for civilian purposes and Defense Federal Acquisition Regulation Supplement 227.7202 for military purposes. The Software was developed fully at private expense. All other use is prohibited.
Contents
Debugging InstallScript-Based Installations .......................................................... 5
InstallScript Debugger ......................................................................................... 6
Script Window ..................................................................................................... 6
Watch Window ..................................................................................................... 6
Button Controls .................................................................................................. 6
User Variables ..................................................................................................... 7
Reproducing the Error ......................................................................................... 7
Locating the Source of the Error ........................................................................ 8
Analyzing the Cause of the Error ....................................................................... 8
Correcting the Error .............................................................................................. 8
The Execution Point ............................................................................................. 8
Step Controls ....................................................................................................... 9
Stepping into a User-Defined Function ............................................................. 9
Stepping over a User-Defined Function ........................................................... 9
InstallScript Breakpoints .................................................................................... 9
Setting a Breakpoint by Clicking the Margin Near a Source Line .................. 10
Setting a Breakpoint at a Function ................................................................... 10
Executing to a Breakpoint ................................................................................ 11
Clearing a Breakpoint ....................................................................................... 11
Inspecting, Watching, and Modifying Script Data ............................................... 11
Inspecting a Variable ....................................................................................... 12
Watching a Variable ......................................................................................... 12
Changing the Value of a Variable ................................................................... 12
Watching Return Values from Built-In Functions ........................................... 12
Deleting a Variable from the Watch Window .................................................. 13
Stopping a Script that Is in an Endless Loop ...................................................... 13
Syntax Errors ....................................................................................................... 13
Logic Errors .......................................................................................................... 13
| Contents |
|------------------|------|
| Debugging an Installation on Any Computer | 13 |
| Debugging a DLL Function Called from the Installation Script | 15 |
| Correcting Identified Errors | 15 |
| Testing the Corrected Installation | 15 |
| Troubleshooting InstallScript Debugger Issues | 16 |
| Displaying Custom Dialogs | 16 |
| Creating Program Folders and Shortcuts | 16 |
| Switching Disks | 17 |
| Before You Call Support | 17 |
| Display Drivers | 18 |
| Antivirus Programs | 18 |
| The Target Drive | 18 |
**Index** 21
Debugging InstallScript-Based Installations
InstallShield 2019 » InstallScript Debugger
Debugging is the process of finding and correcting logic errors in computer software. Those are the errors that can cause a script to operate incorrectly or to halt unexpectedly. Unlike syntax errors, logic errors are not detected by the compiler, which ensures only that statements are expressed correctly. Statements with logic errors look perfectly fine to the compiler. It cannot tell whether or not the instructions expressed by those statements are complete and correct.
Detecting Logic Errors
The best way to detect logic errors in a completed script is to execute that script and observe its operation. Most serious logic errors will turn up while you’re developing and testing a script; however, some logic errors can remain hidden in scripts long after they are put into use, only to surface unexpectedly when the script is run on a particular computer or when a user selects a certain sequence of functions or inputs a particular value.
Logic errors can be fatal, bringing the script to an abrupt halt and displaying a run-time error message to the user. Or they can be subtle; the script executes, but there are problems with its appearance and/or behavior. Perhaps it installed files in a folder other than the one selected or it may not have placed a shortcut on the desktop or in the Windows Start menu, even though that option was selected during the setup.
Resolving Logic Errors
Once you have observed a bug or received a report of a bug, you should follow the steps below.
1. Run the setup and reproduce the error. Be sure you understand the nature of the error before going on.
2. Review your script and identify the probable location of the error.
3. Use the InstallScript Debugger to analyze the error.
4. Use the InstallScript view to correct the error in your script.
5. Recompile your script and verify that the error has been corrected.
InstallScript Debugger
The InstallScript Debugger is a source-level debugger. It displays debugging controls and your installation script in different panes of the same window. In the script pane of the window, the statement to be executed next is indicated with a visual marker, called the execution point.
From the InstallScript Debugger you can execute your script, statement by statement, and trace the flow of control by watching the execution point as it moves in the script pane of the InstallScript Debugger window. You can also monitor the value of any variable in your script at any point during script execution. With these methods, you can more easily identify sources of script error and inefficiency.
Script Window
The script window in the InstallScript Debugger displays your script so that you can view it as you run it. The next statement to be executed is positioned in the window and indicated by a yellow arrow. Lines with breakpoints have a red circle on the left. You cannot set and remove breakpoints by double-clicking a line.
The title bar of the script window shows the full name of the setup file. The script window scrolls automatically if necessary when you use the Step Into or Step Over commands to trace through a set of statements. Likewise, when script execution is halted at a breakpoint, the window is scrolled automatically to display the location of the breakpoint.
Watch Window
The Watch window in the InstallScript Debugger displays the current value of each string and numeric variable that you have selected to watch. The Watch window is displayed in the lower-right corner of the InstallScript Debugger. You can add and delete variables from this window at any time while you are debugging.
Button Controls
The buttons located on the InstallScript Debugger toolbar enable you to control the execution of the script.
<table>
<thead>
<tr>
<th>Button</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Open</td>
<td>Allows you to open a script file.</td>
</tr>
<tr>
<td>Toggle Breakpoint</td>
<td>The toggle breakpoint button allows you to place or remove a breakpoint.</td>
</tr>
<tr>
<td>Go</td>
<td>Begins script execution. Use this button to execute to the next breakpoint or to the end of the script if there are no remaining breakpoints.</td>
</tr>
</tbody>
</table>
User Variables
InstallShield 2019 » InstallScript Debugger
The User variables section of the code window consists of controls that enable you to inspect the current value of local variables and to add local variables to the Watch window.
Reproducing the Error
InstallShield 2019 » InstallScript Debugger
The first goal in the debugging process is to reproduce the bug by running the script and following the steps that you believe will lead to the error. This step is crucial for several reasons:
- If the bug has been reported to you by an end user, the details of the report may be inaccurate or incomplete. If so, you may waste time looking for the wrong problem in the wrong place.
- The bug itself may be one that occurs only in a specific hardware and software environment. If a user reports a bug that you can’t reproduce, you’ll want to determine how the user’s system differs from yours before going any further.
- If you yourself observed the bug, you’ll want to watch it happen again, when you’re expecting it and can document the exact circumstances under which it occurred.
- The process of reproducing the bug will very likely give you insights into where and why the bug is occurring.
- If you don’t know with certainty how to produce the bug, you can’t know later for certain that you’ve actually corrected the problem.
Table 1 • InstallScript Debugger Button Descriptions (cont.)
<table>
<thead>
<tr>
<th>Button</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>Break</td>
<td>Allows you to set and clear breakpoints.</td>
</tr>
<tr>
<td>Step Into</td>
<td>Executes the next statement in the script. If that statement specifies a call to a user-defined function, the debugger displays that function in the code window and positions the execution point at the statement following the keyword begin.</td>
</tr>
<tr>
<td>Step Over</td>
<td>Executes the next statement in the script. If that statement specifies a call to a user-defined function, all of the statements in that function are executed and the execution point is positioned at the next statement to be executed after the function call.</td>
</tr>
<tr>
<td>Step Out</td>
<td>Skips the current routine.</td>
</tr>
<tr>
<td>Show Next Statement</td>
<td>Displays the next statement in your script file.</td>
</tr>
</tbody>
</table>
Locating the Source of the Error
The second step in the debugging process is to locate those parts of the setup that may be involved in the error.
If you have observed the symptoms yourself, you may already have a pretty good idea of where to look for the cause. Still, before you start debugging, it is wise to take a moment to think about the error and to identify obvious design or coding mistakes that could have caused it.
Even the simplest errors can often lead you to several different parts of your setup. For example, suppose the product name is not showing up in Sd dialogs. The error might be found where those dialogs are called. Or it may be that the initialization section fails to establish the product name by calling \texttt{SdProductName}. Or it could be that the call to \texttt{SdProductName} references an undefined string entry.
You probably would not need the debugger to handle that particular bug. But in cases where you would, you will make better use of the debugger if you have planned which parts of the script to trace and analyze for clues.
Analyzing the Cause of the Error
Without a good debugging tool, you would be forced to analyze the code at a potential error location in your script by “running” it in your head. You’d read each line in the suspect area carefully, following the logic and keeping track of the variables that came into play there. You would do that until you found the exact place where your script wandered off the path. Then you would do it again (and again) until you could explain exactly why it was behaving as it was. Because that is the objective of this debugging step: finding the exact cause of the error.
A software debugger is a tool designed specifically for this part of the debugging process. A debugger does not analyze your script for you, but it does make it easier for you to find the reason your setup is misbehaving. With the debugger, you can follow the flow of control by executing your script one statement at a time. And you can determine the value of any variable in your script at any point during script execution.
Correcting the Error
Once you have found the exact source of the error in your script, you are ready to close the debugger and fix the problem. To do that, you will have to make some changes to your installation project in InstallShield. Start by planning your correction, then use the InstallScript view to make the changes. Finally, recompile your script.
The Execution Point
The execution point is the location of the next statement to be executed in the script. That location is displayed in the script window with indicating attributes. When you trace through a script using the Step Into or Step Over buttons, the movement of the execution point reveals the flow of control.
Step Controls
**InstallShield 2019 » InstallScript Debugger**
Step controls include the Step Into and Step Over buttons. These controls allow you to execute all or parts of your script one statement at a time. Use these controls to find help find bugs:
- Step through suspect areas of your script and watch the order in which statements are executed. This process can reveal bugs that are caused by conditional expressions that do not resolve as intended.
- After executing a statement with a step control, check the value of the variables you believe may be causing the bug. The easiest way to track variables is to add them to the Watch window. Verify that the variables you're tracking contain the values you expect them to have at each point in your analysis.
- Use step controls in conjunction with breakpoints. First, set a breakpoint at the statement that starts the section of your script that you want to analyze. Then, click the Go button to execute to that statement. Finally, click the Step Into or Step Over buttons to trace through the statements that follow.
Stepping into a User-Defined Function
**InstallShield 2019 » InstallScript Debugger**
When the execution point is at a statement that calls a user-defined function, click the Step Into button, which is located on the InstallScript Debugger’s toolbar. The script window will scroll automatically to display the first executable statement in the user-defined function. That statement is not executed, but it does become the execution point. The statement will be executed next when you click the Step Into, Step Over, or Go button.
*Note* • When you step into a function that is called from another file, such as a DLL, the title bar displays the name of that file.
Stepping over a User-Defined Function
**InstallShield 2019 » InstallScript Debugger**
When the execution point is at a statement that calls a user-defined function, click the Step Over button, which is located on the InstallScript Debugger’s toolbar. All of the statement in the user-defined function will be executed. The execution point then moves to the next statement in the current block.
InstallScript Breakpoints
**InstallShield 2019 » InstallScript Debugger**
A breakpoint is a location in your script where execution will stop when the script is run under the InstallScript Debugger’s control. You can set breakpoints by clicking in the left margin near the statement at which you want execution to stop. Once a breakpoint has been set, it remains in effect until it is cleared or the InstallScript Debugger is closed.
The role of breakpoints in debugging is to interrupt execution at those places in the script where you want to make a close analysis. Once the script has executed to a breakpoint, you can then step through the statements that follow and watch the variables that are integral to that section of the script. To execute to the next breakpoint, click the Go button on the toolbar.
Statements with breakpoints are displayed with indicating attributes. When the script is executed under debugger control, execution stops immediately before a statement that has been set as a breakpoint.
See Also
Setting a Breakpoint by Clicking the Margin Near a Source Line
Setting a Breakpoint at a Function
Executing to a Breakpoint
Clearing a Breakpoint
Setting a Breakpoint by Clicking the Margin Near a Source Line
InstallShield 2019 » InstallScript Debugger
Task To set a breakpoint by clicking a source line:
1. Scroll through the script window to display the line at which you want to set a breakpoint.
2. Click the left margin near the line.
The InstallScript Debugger marks the line with a breakpoint indicator (red circle).
Note • If you click a breakpoint (red circle) that has already been set, the InstallScript Debugger clears that breakpoint.
See Also
InstallScript Breakpoints
Setting a Breakpoint at a Function
InstallShield 2019 » InstallScript Debugger
Task To set a breakpoint at a function:
1. In the script window, click the left margin next to the first line of the function before which you would like to set a breakpoint.
2. When you run your script in the debugger, the debugger will stop at this breakpoint.
When the breakpoint has been set, the breakpoint itself is set at the first executable line of code in the function.
Note • You cannot set a breakpoint at a built-in InstallScript function.
See Also
InstallScript Breakpoints
Executing to a Breakpoint
To execute to the next breakpoint, click the Go button, which is located on the InstallScript Debugger's toolbar. If you click the Go button when no breakpoints have been set, or when the script has already executed to a statement that follows the last breakpoint, the script will execute to the end.
See Also
InstallScript Breakpoints
Clearing a Breakpoint
Use one of the following methods to clear breakpoints in your script:
- Clear a breakpoint by clicking the red circle in the left margin.
- On the Debug menu, click Clear All Breakpoints.
See Also
InstallScript Breakpoints
Inspecting, Watching, and Modifying Script Data
Some of the most common software bugs occur because a variable does not hold the correct value at a key point in the program. That can happen for a variety of reasons:
- The variable was not initialized.
- The variable was not updated.
- An incorrect value was assigned to the variable.
The repercussions of these kinds of errors can be enormous and varied. For example, if parts of a script are executed only when a variable is set to a specific value, your installation will be incomplete if that controlling variable is set incorrectly. If the variable is used to control a while loop, that loop may never be executed, or it may execute forever, hanging the installation.
To fully analyze a bug, you must be able to investigate the value of script data as you trace through the script. The InstallScript Debugger provides you with three ways to do so:
1. **Inspect a variable** to determine its current value. At any breakpoint or while stepping through the script, you can check the value of any global variable in the script. When the execution point is within a user-defined function, you can also check any variables that are local to that function.
2. **Watch a variable** to observe any changes in its value as you use the Step In and Step Over commands to trace script execution. The control window includes a watch window that lets you insert one or more variables that you want to monitor in your debugging session.
3. **Change the value of a variable** at a key point in the program to test your theories about the role of that variable in the bug that you are analyzing or to override the effects of a logic error that you discovered in your script.
Inspecting a Variable
To inspect a variable, locate the variable that you want to inspect in the variable window. In this window, the name of the variable is detailed, followed by the current local value of the variable.
Restrictions
Structured variables and list variables cannot be inspected.
The local user variable controls are active only when the execution point is within the begin and end statements of a user-defined function. When the execution point moves beyond the end of the function, the value shown in the Watch window for that variable is changed to the message <variable not found.>
Watching a Variable
The Variable window lists all of the local variables in the current user-defined function.
You can type the name of a global variable into the Watch window to see its current value.
Restrictions
- Structured variables cannot be selected for the Watch window. To watch the value of a structure member, return to the script editor and add statements that assign the value of that member to a simple data type at locations in your script where you want to know its value. Then recompile your script and start the debugger. Finally, put that simple variable in the Watch window.
- A List variable can be selected for the Watch window, but the debugger cannot display its elements. Use the method described above for structure members to watch elements of a list.
- The local user variable controls are active only when the execution point is within the begin and end statements of a user-defined function. When the execution point moves beyond the end of the function, the value shown in the Watch window for that variable is changed to the message <variable not found.>
Changing the Value of a Variable
In the InstallScript Debugger, a list of variables is displayed in the Variable window.
Click on the variable in the list that you want to change. Enter the value that you would like to change the variable to.
Watching Return Values from Built-In Functions
In the Watch window, type in LAST_RESULT. This system variable contains the value returned by the most recent call to an InstallScript function.
Deleting a Variable from the Watch Window
**Task**
To delete a variable from the Watch window:
1. In the Watch window, click the variable that you want to delete.
2. Press the **Delete** key.
Stopping a Script that Is in an Endless Loop
To stop a script that is in an endless loop:
1. To change the focus from your installation’s window to the InstallScript Debugger’s windows, press ALT+TAB.
2. In the debugger’s window, click the **Stop** button.
Syntax Errors
Syntax errors are language usage errors, such as misspelled keywords, references to undeclared variables, and missing semicolons at the end of statements. Syntax errors prevent script compilation and are reported by the compiler. The debugger has no role in detecting syntax errors. Your program must be free of syntax errors and compile successfully before it can be run under the control of the debugger.
Logic Errors
Logic errors are found in a script’s algorithm, that is, in the structure of the script. Logic errors produce run-time errors, so called because they become apparent only when the script is executed. Some logic errors produce run-time errors that cause a script to terminate. Others simply cause your script to operate incorrectly or to stop responding to input. These are the kinds of errors the debugger can help you help you analyze.
Debugging an Installation on Any Computer
In order to find bugs that are occurring only with certain hardware or software configurations, you may need to debug your installation on a system other than your development machine. In that case, it is not necessary to install InstallShield on that computer.
To debug the installation on a debug machine, instead of on your installation development machine:
1. Compile and build your installation on the development machine.
2. Move copies of the following files from your development machine to the debug machine.
- InstallShield Program Files Folder\System\ISDbg.exe
This is the executable file for the InstallScript Debugger.
- InstallShield Program Files Folder\System\SciLexer.dll
This file must be present on the debug machine in the same folder as the ISDbg.exe file.
- InstallShield Program Files Folder\Program\0409\ISDbg.chm (for the English version of InstallShield) or InstallShield Program Files Folder\Program\0411\ISDbg.chm (for the Japanese version of InstallShield)
This is the help file that you can optionally copy to the debug machine so that you can access the InstallScript Debugger help from within the debugger.
3. Register the ISDbg.exe file by passing it the /REGSERVER command-line parameter.
4. Copy your project file and your project folder to the debug machine. This should include your built setup disk images (Setup.exe and media and support files from the Disk Images\DiskN folders).
Tip • If the project files on your development machine are accessible to the debug machine over a network, you can skip step 4.
5. If the debug machine does not have Visual Studio 2012 installed, then you must install the redistributable Visual C++ Redistributable for Visual Studio 2012 on the debug machine.
Note • The Visual C++ Redistributable Packages install runtime components of Visual C++ libraries that are required to run applications (such as InstallShield) that were developed using Visual Studio 2012.
6. Launch Setup.exe with the /d command-line parameter to debug the installation and provide the location of the debug symbols (.dbg) file. For example, if Setup.dbg is in C:\Test, type the following statement at the command line:
setup /d"C:\Test"
Note that if your installation, script, and debug files are all in their original location on the development system, you do not need to specify the path to the debug file—use the following:
setup /d
Debugging a DLL Function Called from the Installation Script
<table>
<thead>
<tr>
<th>Task</th>
<th>To debug a DLL function called from your setup script:</th>
</tr>
</thead>
<tbody>
<tr>
<td>1.</td>
<td>Open the Microsoft Visual Studio project that contains your DLL.</td>
</tr>
<tr>
<td>2.</td>
<td>Shut down any setups that may be running. Also, verify that no Setup.exe processes are running by using Windows' Task Manager. If any Setup.exe processes are running, end them.</td>
</tr>
<tr>
<td>3.</td>
<td>In the DLL project's project settings' Debug tab, specify in the "Executable for debug session" field the location of your setup's Setup.exe: <code><project folder>\Media\<media name>\Disk Images\Disk1\Setup.exe</code>.</td>
</tr>
<tr>
<td>4.</td>
<td>Specify the following in the "Program arguments" field: <code>-deleter -d</code></td>
</tr>
<tr>
<td>5.</td>
<td>Press F5 to launch Setup.exe and begin debugging. The debugger will launch Setup.exe. The setup will initialize and run. The debugger should stop at any breakpoints set in your DLL function.</td>
</tr>
</tbody>
</table>
Correcting Identified Errors
The InstallScript Debugger neither identifies errors nor edits code. Only you can find errors that escaped the compiler, and only an editor can actually change the code.
When running the debugger, you may have the Script Editor open, and it may contain the same file (probably Setup.rul) as does the debugger's code window. When you stop the debugger and go to edit your code, you must do so in the IDE. If another file is there, or that window isn't open, you must set it up for editing the offending script.
When you have made the necessary changes, you must:
- Recompile the script (select Compile Setup.rul from the Build menu).
- Rebuild the setup.
- Debug the script.
- Adjust breakpoints and variables, if appropriate, to include the changes just made.
Testing the Corrected Installation
Your job is not done until you have tested your revised script and verified that the reported bug is gone and the setup now operates as intended. To do that, execute the script exactly as you did when you verified the bug. Watch carefully to be sure that your modifications did not introduce a new bug.
Troubleshooting InstallScript Debugger Issues
InstallShield 2019 » InstallScript Debugger
If the debugger does not appear when you select Debug InstallScript from the Build menu, check for the presence of the following files:
Table 2 • Files and Descriptions
<table>
<thead>
<tr>
<th>File</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<tr>
<td>ISDbg.exe</td>
<td>InstallShield Program Files Folder\System</td>
</tr>
<tr>
<td>SciLexer.dll</td>
<td>InstallShield Program Files Folder\System</td>
</tr>
<tr>
<td>Setup.dbg</td>
<td>InstallShield Project Folder\Project Name\Script Files</td>
</tr>
<tr>
<td>Setup.rul</td>
<td>InstallShield Project Folder\Project Name\Script Files</td>
</tr>
<tr>
<td>Setup.inx</td>
<td>InstallShield Project Folder\Project Name\Script Files</td>
</tr>
<tr>
<td>Setup.exe</td>
<td>InstallShield Project Folder\Project Name\Product Configuration\Release Name\DiskImages\Disk1</td>
</tr>
</tbody>
</table>
ISDbg.exe and SciLexer.dll are installed with InstallShield. Setup.rul is the master script that you made for your project. InstallShield creates Setup.exe and Setup.inx as part of the build process.
Displaying Custom Dialogs
InstallShield 2019 » InstallScript Debugger
One common technical support issue is the failure of custom dialogs to be displayed. Building and debugging custom dialogs can be a sophisticated process, but you can often find the bug that prevents a custom dialog from being displayed by confirming that all of the following conditions are true:
- The DLL containing the dialog resides on the disk that you intend to ship.
- Your installation copies the DLL to the path and subfolder where your script expects to find it.
- The dialog that you are loading is in the DLL.
- You are using the correct ID to address the dialog if the dialog is in the DLL.
Creating Program Folders and Shortcuts
InstallShield 2019 » InstallScript Debugger
If you are having difficulty creating program folders and shortcuts, isolate the section of your script in which you create them and run it separately.
Use the `SprintfBox` function to display the parameters of your `AddFolderIcon` function. Make sure that all of the values that are passed to the parameters are valid and in the correct order.
### Switching Disks
**InstallShield 2019 ➤ InstallScript Debugger**
Your script may encounter problems when it attempts to prompt the user to remove one disk and insert the next. For example, you may get a "File not found" error message at the point where the user is supposed to take out Disk 1 and insert Disk 2.
Usually when you encounter such a problem, it occurs because you left a file open on your diskette. DOS will raise this error message when it finds a new disk volume ID or file allocation table and cannot access the open file.
To avoid this problem, do not open files directly on the diskette during your setup. Do not use your information files, bitmap files, or DLLs directly from diskette. Instead, copy the files to the target hard disk and access them from the hard disk.
If you encounter such a problem while debugging, verify that you do not open any files before transferring them to the target disk.
### Before You Call Support
**InstallShield 2019 ➤ InstallScript Debugger**
Try to isolate the problem by determining from your user exactly what is wrong. Are many of your customers reporting the problem, a few, or only this customer? Here are some areas to check in diagnosing your customer’s problem:
- Has the user tried to install your software more than once? If not, ask the user to install it again on the same system. If there is still a problem, ask the user to try installing it on another system or on several, if possible. It is unreasonable to establish conclusions using only one system.
- Is the problem related to the distribution media? If you ship more than one type of media, ask the user to try the different types. This may help identify a disk problem or a drive problem. If the same problem occurs on both sets of disks, you have significantly narrowed down the problem. If you are confident there is nothing wrong with your setup, send the user another set of disks.
- Use brand-name distribution media whenever possible. If you had disk problems before, you know it does not pay to cut corners when you buy disks. A good disk costs only ten or fifteen cents more than a disk of marginal quality, but the difference between a happy customer and an annoyed one is all the difference in the world.
- If you determine that your customer’s problem occurs on only one system, you need to find out how that system differs from others.
- Ask the customer how much memory and system resources are free. If the system resources are extremely low, it is possible some other program is using them. Ask the user to exit Windows to free system resources. If there is ample memory and system resources free after restarting Windows, ask the user to try the setup program again.
- Determine what version of Windows the user is running. Setup.exe typically requires a minimum of 16 MB of RAM on the system. However, it is possible that if you are using an extensive script and large bitmaps, you will require more RAM. If your customer is pushing these limits, they will need more RAM.
- Look at the Config.sys and Autoexec.bat files. Ask your customer to send you a copy of these files. If the Config.sys has many entries, and your customer is loading a lot of programs to specific locations, this could cause problems. Special
memory managers and drivers with a lot of parameters can cause problems. Use only the most basic drivers. Ask the customer to remove as many drivers as possible from their Config.sys. In general, the more lines that you find in the Config.sys, the greater the chance for conflict. Have them temporarily comment out (rem) all unnecessary statements and reboot the system.
Display Drivers
A display driver is a software interface that enables Windows to communicate with the hardware video adapter. Windows provides several standard display drivers that work with any video adapter; however, many Windows users install a custom driver provided by the manufacturer of the display adapter in their computer. These custom drivers offer more colors and higher resolutions than are available with the standard Windows display drivers.
When a customer cannot start a setup properly, it is often due to a problem with a custom display driver. The following symptoms usually indicate that the problem is the display driver:
- The setup starts but does not appear on the screen.
- The system hangs when the setup attempts to display a bitmap (.bmp) file.
- The screen display malfunctions when the setup attempts to fade in a bitmap.
When a customer reports one of these symptoms, determine which video driver is installed in their system. Suggest that they install a standard Microsoft Windows VGA driver and then run the setup again. If necessary, the customer can always return to the non-standard driver after installing your software.
Antivirus Programs
Antivirus programs that have been configured to prevent executable files from being copied to the hard disk will interfere with an installation. When an end user reports that an installation appeared to run normally but did not transfer the application to the hard drive, virus protection may be the problem.
In most cases, the default settings of antivirus programs do not block file transfers; most users will not have trouble installing your software. For those users whose antivirus software is set to block certain file transfers, you may want to include a note in your users guide or Readme file advising them of the potential problem.
The solution to the problem is simple enough: Disable the antivirus software and then run the installation again.
The Target Drive
No matter how well it has been designed or how thoroughly it has been tested, your installation may fail to perform as expected in some cases due to errors on the target drive of an end user’s computer. There are a variety of problems that can occur with magnetic media:
- Flaws and/or damage to the surface of the disk can prevent data from being read from or written to certain disk sectors.
• File allocation table errors, such as lost and cross-linked clusters, can prevent your installation from opening or overwriting files.
• Extreme disk fragmentation, which impairs disk performance, can cause your installation and the installed application to run very slowly.
When you suspect that the target disk may be the cause of an end user’s problems with your installation or the installed application, you can recommend the following tactics:
1. If you suspect that flaws in the disk surface or errors in the file allocation table are the source of the trouble, instruct your end user to run ScanDisk. This utility can lock out bad sectors so that programs no longer attempt to read from or write to them. It will also repair errors in the file allocation table.
2. If you suspect that extreme disk fragmentation is the source of the trouble, recommend that your end user run the Windows Disk Defragmenter.
Tip • You should advise your end users to perform a disk backup before running disk defragmentation software.
Index
A
Antivirus programs 18
B
Breakpoints 11
defined 9
executing to next 11
setting 10
using 9
Buttons
Clear 11
ClearAll 11
Exit 6
Go 11
Step Into 6
Step Over 6
Stop 6
C
Changing 12
variable values 12
Clear button 11
ClearAll button 11
Clearing 11
Custom dialogs 16
debugging 16
D
Debugging
antivirus programs and 18
before contacting Technical Support 17
Break button 6
breakpoints 10
buttons 6
custom dialogs boxes 16
display drivers and 18
DLL function called from setup script 15
editing while debugging 15
Go button 6
on any computer 13
program folder and icon creation 16
script window 6
Step Into button 6
Step Over button 6
Stop button 6
switching disks 17
troubleshooting 16
variables 12
Deleting 13
breakpoints 11
variables from the Watch window 13
Dialogs
debugging custom 16
Display drivers 18
DLL functions 15
debugging 15
E
Editing 15
while debugging 15
Errors 5
types 5
Execution point 8
Exit button 6
Index
G
Go button 11
I
Inspecting variables 11
L
LAST_RESULT 12
Line numbers 10
Logic errors 5
S
Script window 6
Step controls 9
Step Into button 6
Step Over button 6
Stepping 9
into a function 9
over a function 9
Stop button 6
Syntax errors 5
U
User variables 7
V
Variables 12
changing values 12
debugging 12
deleting from Watch window 13
tracking 11
user variable controls 7
Visual Debugger overview 6
W
Watch window 12
Watching 11
return values from built-in functions 12
variables 11
Window 6
script 6
Watch 12
|
{"Source-Url": "https://docs.revenera.com/installshield25helplib/pdf/InstallShield2019_InstallScriptDebuggerUserGuide.pdf", "len_cl100k_base": 8401, "olmocr-version": "0.1.50", "pdf-total-pages": 22, "total-fallback-pages": 0, "total-input-tokens": 45876, "total-output-tokens": 9254, "length": "2e13", "weborganizer": {"__label__adult": 0.0004343986511230469, "__label__art_design": 0.0005092620849609375, "__label__crime_law": 0.00034427642822265625, "__label__education_jobs": 0.0005335807800292969, "__label__entertainment": 0.00015878677368164062, "__label__fashion_beauty": 0.00012302398681640625, "__label__finance_business": 0.0003457069396972656, "__label__food_dining": 0.00015461444854736328, "__label__games": 0.00205230712890625, "__label__hardware": 0.001750946044921875, "__label__health": 0.00011366605758666992, "__label__history": 0.0001131296157836914, "__label__home_hobbies": 9.620189666748048e-05, "__label__industrial": 0.00022029876708984375, "__label__literature": 0.0002371072769165039, "__label__politics": 0.0001035928726196289, "__label__religion": 0.00033020973205566406, "__label__science_tech": 0.0020694732666015625, "__label__social_life": 6.580352783203125e-05, "__label__software": 0.2305908203125, "__label__software_dev": 0.75927734375, "__label__sports_fitness": 0.0001533031463623047, "__label__transportation": 0.00013947486877441406, "__label__travel": 0.00011670589447021484}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 40964, 0.03038]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 40964, 0.29738]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 40964, 0.87678]], "google_gemma-3-12b-it_contains_pii": [[0, 53, false], [53, 2043, null], [2043, 5198, null], [5198, 5731, null], [5731, 7690, null], [7690, 10080, null], [10080, 12528, null], [12528, 15317, null], [15317, 18276, null], [18276, 19756, null], [19756, 22089, null], [22089, 24226, null], [24226, 25862, null], [25862, 28035, null], [28035, 30192, null], [30192, 32192, null], [32192, 35663, null], [35663, 38390, null], [38390, 39421, null], [39421, 39421, null], [39421, 40421, null], [40421, 40964, null]], "google_gemma-3-12b-it_is_public_document": [[0, 53, true], [53, 2043, null], [2043, 5198, null], [5198, 5731, null], [5731, 7690, null], [7690, 10080, null], [10080, 12528, null], [12528, 15317, null], [15317, 18276, null], [18276, 19756, null], [19756, 22089, null], [22089, 24226, null], [24226, 25862, null], [25862, 28035, null], [28035, 30192, null], [30192, 32192, null], [32192, 35663, null], [35663, 38390, null], [38390, 39421, null], [39421, 39421, null], [39421, 40421, null], [40421, 40964, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 40964, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 40964, null]], "pdf_page_numbers": [[0, 53, 1], [53, 2043, 2], [2043, 5198, 3], [5198, 5731, 4], [5731, 7690, 5], [7690, 10080, 6], [10080, 12528, 7], [12528, 15317, 8], [15317, 18276, 9], [18276, 19756, 10], [19756, 22089, 11], [22089, 24226, 12], [24226, 25862, 13], [25862, 28035, 14], [28035, 30192, 15], [30192, 32192, 16], [32192, 35663, 17], [35663, 38390, 18], [38390, 39421, 19], [39421, 39421, 20], [39421, 40421, 21], [40421, 40964, 22]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 40964, 0.10099]]}
|
olmocr_science_pdfs
|
2024-12-03
|
2024-12-03
|
9d18cd9247e9972e0d1d02dab1683f35f433a8ee
|
A Methodology for Operationalizing Enterprise IT Architecture and Evaluating its Modifiability
Robert Lagerström¹, Alan MacCormack², David Dreyfus³, and Carliss Baldwin²
1 Electrical Engineering and Computer Science, KTH Royal Institute of Technology, Stockholm, Sweden
2 Harvard Business School, Boston, USA
3 NorthBay Solutions, Boston, USA
robertl@kth.se, amaccormack@hbs.edu, dddreyfus@gmail.com, cbaldwin@hbs.edu
Abstract. Recent contributions to information systems theory suggest that the primary role of a firm’s information technology (IT) architecture is to facilitate, and therefore ensure the continued alignment of a firm’s IT investments with a constantly changing business environment. Despite the advances we lack robust methods with which to operationalize enterprise IT architecture, in a way that allows us to analyze performance, in terms of the ability to adapt and evolve over time. We develop a methodology for analyzing enterprise IT architecture based on “Design Structure Matrices” (DSMs), which capture the coupling between all components in the architecture. Our method addresses the limitations of prior work, in that it i) captures the architecture “in-use” as opposed to high level plans or conceptual models; ii) identifies discrete layers in the architecture associated with different technologies; iii) reveals the “flow of control” within the architecture; and iv) generates measures that can be used to analyze performance. We apply our methodology to a dataset from a large pharmaceutical firm. We show that measures of coupling derived from an IT architecture DSM predict IT modifiability – defined as the cost to change software applications. Specifically, applications that are tightly coupled cost significantly more to change.
Keywords: Enterprise Architecture, Modularity, Information Systems, Modifiability, Design Structure Matrix.
1 Introduction
As information becomes more pervasive in the economy, information systems within firms have become more complex. Initially, these systems were designed to automate back-office functions...
and provide data to support managerial decision-making. Their role was expanded to coordinate the flow of production in factories and supply chains. The invention of the personal computer led to the creation of client-server systems, which enhanced the productivity of office workers and middle managers. Finally, the arrival of the Internet brought a need to support web-based communication, e-commerce, and online communities. Today, even a moderately sized business maintains information systems comprising hundreds of applications and databases, running on geographically distributed hardware platforms, and serving multiple clients. These systems must be secure, reliable, flexible, and capable of evolving to meet new challenges.
“Enterprise architecture” (EA) is the name given to a set of frameworks, processes and concepts used to manage an enterprise’s information system infrastructure. For instance, TOGAF®, the most-cited framework in this field, was developed by a consortium of firms to provide a standardized approach to the design and management of information systems within and across organizations [1]. It provides a way of visualizing, understanding and planning for the needs of diverse stakeholders in a seamless way. Despite the increasing adoption of EA frameworks by firms, however, the empirical evidence for their impact is mixed at best [2]–[8]. Making changes to systems, adding new functions, and/or integrating different systems (e.g. during a merger) continue to be difficult tasks. Changes made to one component often create unexpected disruptions in distant parts of a system [9]–[12]. In essence, when dealing with complex information systems, changes propagate in unexpected ways, increasing the costs of adaptation. This suggests that we need a better way to operationalize (and analyze) enterprise IT architecture.
Early contributions to the EA literature focused on the need to align IT investment decisions with the business strategy of a firm (e.g. [13]). With this perspective, a firm’s architecture should be optimized to a given strategic position, and was expected to change only slowly, as a firm evolved. Contributions to theory however, focus on the complex and dynamic nature of competition in today’s business markets, and the increasingly pervasive nature of digital platforms [14]–[16]. Given this, viewing the design of a firm’s enterprise architecture as a static optimization problem is no longer possible. Instead, modern information systems theory emphasizes the need for IT architectures to facilitate IT modifiability, through the use of modular, loosely coupled systems [17], [18]. Firms with superior modifiability quickly reconfigure resources to respond to new challenges, ensuring a continuous alignment of IT investments with changing business needs.
How can we operationalize the concept of enterprise IT architecture in a way that is robust, repeatable, and facilitates the analysis of IT modifiability? Prior work has demonstrated the efficacy of using a Design Structure Matrix or DSM – a square matrix that captures dependencies between components – as a tool for visualizing, measuring and characterizing product architecture [19]–[21]. We apply this methodology to analyze a firm’s enterprise IT architecture, which comprises many interdependent elements, including business groups, applications, databases and hardware. We use data from a large pharmaceutical company to i) describe how an enterprise IT architecture DSM is constructed, ii) show that this DSM reveals the layered structure of the architecture, and iii) highlight how this DSM allows components in the architecture to be classified into different groups – Core, Peripheral, Shared and Control – based upon the way that they interact with and are coupled to other components. We then analyze the impact of component coupling on IT modifiability – defined as the cost to change software applications. We show that the cost to change “Core” applications, which are tightly coupled to other components, are significantly higher than the cost to change “Peripheral” applications, which are only loosely connected to other components. The measure of coupling which best predicts IT modifiability is one that captures all direct and indirect connections between components. In sum, it is important to account for all possible paths by which changes may propagate between components in the architecture.
The main contribution of this article lies in developing an operational methodology for analyzing enterprise IT architecture. We show how dependency-matrices, which have previously
been applied to the study of product architecture, can be used to gain insight into enterprise IT architecture. We demonstrate the application of our methodology using a novel dataset from a real firm, encompassing comprehensive information about all system components and the interdependencies between them. We show that this method can be used to predict IT modifiability – the most critical capability in the modern firm. We conclude by relating our findings to the prior literature and discussing the implications of our methods for managerial practice.
The article is organized as follows. Section 2 reviews the literature and motivates our approach. Section 3 introduces our dataset and describes how an enterprise IT architecture DSM is constructed. Section 4 shows how this DSM is used to classify components into groups based upon their levels of coupling. Section 5 shows how measures of coupling derived from the DSM can be used to predict the cost of software changes. Finally, Section 6 describes our conclusions.
2 Literature Review
This section first reviews the enterprise architecture literature, with the aim of understanding the limitations of current approaches, and the criteria by which new methods should be assessed. We then describe work on the visualization and measurement of complex software systems using network-based approaches, with a focus on the use of DSMs.
2.1 Enterprise Architecture
Enterprise Architecture is commonly defined as a tool for achieving alignment between a firm’s business strategy and its IT infrastructure. For instance, MIT’s Center for Information Systems Research defines EA as “the organizing logic for business processes and IT infrastructure reflecting the integration and standardization requirements of the company's operating model” [13]. Prior work tends to emphasize conceptual models, tools and frameworks that attempt to achieve this alignment (e.g. [22]). EA analysis is not limited to IT systems, but encompasses the relationship with and support of business entities.
This overarching perspective is present in the ISO/IEC/IEEE 42010:2011 standard, which defines architecture as “the fundamental organization of a system, embodied in its components, their relationships to each other and the environment, and the principles governing its design and evolution” [23]. Ultimately, EA targets a holistic and unified scope of organization [24], [25]. Hence most research has focused on the “strategic” implications of EA efforts [26]–[29].
If the integration of IT and business concerns is one defining aspect of EA, a model-based methodology is another. As the name hints, architectural descriptions are central in EA. These descriptions include entities that cover a broad range of phenomena, such as organizational structure, business processes, software and data, and IT infrastructure [30]–[33]. A large number of frameworks have been proposed, detailing the entities and relationships between them that should be part of this effort (e.g. [1], [30], [34]). However, considerable diversity exists, in terms of the primary unit of analysis and terminology adopted by each. For instance, various frameworks focus on i) Stakeholders and Aspects to be considered [34]; ii) Viewpoints and Concerns to be analyzed [1]; and iii) Objects and Attributes to be modeled [35]. This lack of consistency is likely one reason for the limited success reported for EA efforts in studies of practice [36].
EA frameworks have been shown to be a useful decision-support tool when focused on the needs of specific decision-makers [18]. For instance, researchers at the KTH Royal Institute of Technology have applied a uniform methodology to model how EA affects the dimensions of security, interoperability, availability, modifiability and data accuracy [35], [37]–[41]. These narrower models help stakeholders understand how EA affects specific performance attributes, generating insight into current and future states. Nevertheless, these approaches often require a larger modeling effort before business value is obtained.
Several EA frameworks propose using matrices to display the relationships among various components of an information system, in an attempt to make EA more operational. For instance, TOGAF recommends preparing nine separate matrices at different points in the development of a firm’s architecture,† which are used to track the linkages and dependencies between various parts of the system. Unfortunately, it is not clear how these matrices should be combined to generate managerial insights. Furthermore, the information used to construct them reflects an idealized view of how a system should function, rather than how it actually functions. Finally, these matrices do not yield quantitative measures of architecture that can be used to analyze performance, they are primarily descriptive in nature.
In sum, operationalizing enterprise architecture in a robust and reliable way, that allows firms to analyze and improve their systems, has proven an elusive goal. A diverse range of frameworks exists, each employing different units of analysis and terminology. Furthermore, these frameworks are conceptual in nature, generating few quantitative measures that can be used to analyze performance. Finally, these frameworks focus on idealized versions of a firm’s architecture, rather than actual data from the architecture “in-use.” While some studies attempt to operationalize EA at a granular level (e.g. [42], [43]), there is yet little consensus on a general methodology for how this should be achieved.
2.1.1 Enterprise Architecture and “Layers”
While there exists a diverse range of enterprise architecture frameworks, one of the themes they have in common is the concept of “layers” [44]–[46]. Simon et al. [44] describe enterprise architecture management as dealing with different layers, including business, information, application, and technology layers. Yoo et al. [45] argue that pervasive digitization has given birth to a “layered-modular” architecture, comprising devices, network technologies, services and content. Finally, Adomavicius et al. [46] discuss the concept of an IT “ecosystem,” highlighting the different roles played by products and applications, component technologies and infrastructure technologies.
While studies differ in the ways they classify layers in a firm’s enterprise architecture, they do share common underlying assumptions. First, layering reflects a division of the functions provided by a system into units, such that these units can be designed, developed, used and updated independently. Second, layering establishes a design “hierarchy” such that each layer tends to interact only with layers immediately above or below it, reducing complexity [47]. Finally, the direction of interdependencies between layers is such that higher layers “use” lower layers, but not the reverse, limiting the potential for changes to propagate [48]. For instance, a software application on a desktop computer “uses” (i.e. depends upon) functions provided by the operating system layer below it. However, the operating system does not (in general) depend upon the applications that use it. This has important implications for the propagation of changes. Changes to the operating system may impact applications, but changes to applications will not, in general, impact the operating system. The importance of layering in the literature suggests that any methodology for operationalizing EA should be able to identify the layered structure of the architecture.
2.1.2 Enterprise Architecture, Firm Performance and IT Modifiability
Much of the literature on EA has focused on frameworks that align business needs with IT capabilities and the processes by which such frameworks are implemented. Surprisingly, there has been little work to explore the performance benefits of EA, using empirical data on the actual outcomes achieved by firms [6]–[8]. Indeed, Tamm et al. [26] found that of the top 50 articles on enterprise architecture (as ranked by citation count) only 5 provided any empirical data that sought to explain the link between EA efforts and improved performance outcomes. Studies that do make claims about the performance benefits of EA tend to cite a range of “enablers” that mediate important firm outcomes. Recurring themes include better organizational
alignment, improved information quality and availability, optimized resource allocation across a business portfolio, and increased complementarities between firm resources [26].
Many authors note it is difficult to directly assess the quality of a firm’s architecture. Hence empirical studies linking enterprise architecture to performance tend to focus on assessing the quality of the outputs from EA planning processes (e.g. the quality of the documentation) or the quality of the planning process itself (e.g. how effectively did the firm set goals, define tasks and govern the effort) [49]–[52]. This approach means that it is difficult to differentiate between firms that follow similar EA planning processes, but which arrive at different system designs. A more robust method for operationalizing EA should be able to discern between such situations.
The most consistent theme that emerges in the literature is the increasingly important role of enterprise IT architecture in facilitating agility. In an influential paper, Samburmathy et al [53] argue that the strategic value of information technology investments in firms is defined by their impact on agility, creating “digital options” and improving “entrepreneurial alertness” (i.e. understanding and exploiting new opportunities). Sambamurthy and Zmud [54] suggest the new organizing logic for IT architecture is the “platform,” which encompasses a “flexible combination of resources, routines and structures” that meets the needs of both current and future IT-enabled functionalities. Duncan [55] and Schmidt and Buxmann [51] explore the factors that contribute to flexibility, and show managers associate this feature with the attributes of compatibility, connectivity, and modularity. Finally, Tiwana and Konsynski [17] use modular systems theory to develop subjective measures of IT architecture, and show that loose coupling and the use of standards are associated with self-reported increases in a firm’s level of IT agility.
The above discussion suggests that any methodology for operationalizing enterprise IT architecture in a more robust way must capture data on the architecture “in-use” by a firm, and not just the processes and documents by which it was developed. Furthermore, the measures output from this methodology should facilitate the analysis of IT agility (flexibility/modifiability), given the importance of this construct in the literature on the role of information systems in the modern firm.
2.2 Network-based Approaches to System Architecture
Many prior studies have characterized the architecture of complex systems using network representations and metrics [56]–[58]. In particular, they focus on identifying the linkages that exist between different elements (nodes) in a system [59], [60]. A key concept that emerges in this literature is that of modularity, which refers to the way that a system’s architecture can be decomposed into different parts. Although there are many definitions of modularity, authors agree on its fundamental features: the interdependence of decisions within modules, the independence of decisions between modules, and the hierarchical dependence of modules on components that embody standards and design rules [61], [62].
Studies that use network methods to measure modularity typically focus on analyzing the level of coupling between different elements in a system [63]. The use of graph theory and network measures to analyze coupling in software systems has a long history [65]. Many authors find measures of direct component coupling predict important parameters such as defects and productivity [66]–[70]. In more recent years, a number of studies have adopted coupling measures derived from social network theory to analyze software systems [43], [71], [72]. However, such measures suffer from limitations that make their application to technical systems difficult to apply and interpret. For instance, social network measures tend to assume that dependencies are symmetric. In technical systems, many important dependencies are asymmetric, meaning the direction of coupling is important.
---
‡ For software systems, this notion is linked with that of cohesion [64]. Well-designed software applications have high levels of cohesion (within modules) and low levels of coupling (across modules).
2.2.1 Design Structure Matrices (DSMs)
An increasingly popular network-based method used for analyzing technical systems is the “Design Structure Matrix” or DSM [19], [20], [73], [74]. A DSM displays the structure of a complex system using a square matrix, in which the rows and columns represent system elements, and the dependencies between elements are captured in off-diagonal cells. Baldwin et al. [75] show that DSMs can be used to visualize the “hidden structure” of software systems, by analyzing the level of coupling for each component, and classifying them into similar categories based upon the results.
Metrics that capture the level of coupling for each component can be calculated from a DSM and used to understand system structure. For instance, MacCormack et al. [20] and LaMantia et al. [76] use DSMs and the metric “propagation cost” to compare software system architectures, and to track the evolution of software systems over time. MacCormack et al. [77] show that the architecture of technical systems tends to “mirror” that of the organizations from which they have evolved. Sturtevant [78] shows that software components with high levels of coupling tend to experience more defects, take more time to adapt and are associated with high employee turnover. Ozkaya [79] shows that metrics derived from DSMs can be used to assess the value released by “re-factoring” designs with poor architectural properties. And Lagerström et al. [80] connects DSM-based complexity measures with known vulnerabilities in Google Chrome.
2.2.2 Design Structure Matrices and Change Propagation
A DSM captures all of the dependencies that exist between components in a system. If component A depends directly upon component B, then any change made to B may affect A. These two components are “coupled.” But using a DSM, we can also analyze the indirect dependencies between components, which reflect the potential for changes to propagate in a system via a “chain” of dependencies. For instance, if component B, in turn, depends upon component C, then a change to C may affect B, which in turn, might affect A. Therefore, A and C are also “coupled,” but indirectly. The level of indirect coupling in a system provides an indication of the degree to which changes can propagate through a system. Prior work has shown that measures of indirect coupling predict both the level of defects and the ease (or difficulty) with which a system can be adapted [78], [81].
A DSM is not the only network analysis technique that can reveal both direct and indirect dependencies between components. In contrast to techniques such as social network analysis, however, a DSM also captures information on the direction of dependencies. This distinction is important, given dependencies in technical systems are typically not symmetric. In the example above, A depends upon B, but that does not imply that B also depends upon A. As such, a change to B may propagate to A, whereas component A could be changed with no impact on B. A DSM captures the direction of dependencies, allowing us to determine the “flow of control” in a system (i.e. the direction in which chains of dependencies are likely to propagate). Hence we can discern between systems that are hierarchical in nature (i.e. there exists a strict ordering of components) versus those that are cyclical in nature (i.e. the components are mutually interdependent). Hierarchy and cyclicity are critical constructs for understanding how changes might propagate in complex systems. DSMs can be used to reveal these characteristics.
3 Constructing an Enterprise Architecture DSM
3.1 The Empirical Context
We illustrate our methodology by using a real-world example of a firm’s enterprise architecture. The aim is to make these methods concrete and to demonstrate that they provide insight into how real world systems operate. Using real-world data also provides validation that our methods of data collection and analysis are able to scale for practical use in the field.
Our study site is the research division of a US biopharmaceutical company “BioPharma”. At this company, “IT Service Owners” are responsible for the divisional information systems, and provide project management, systems analysis, and limited programming services to the organization. Data were collected by examining strategy documents, having IT service owners enter architectural information into a repository, using automated system scanning techniques, and conducting a survey.
Our BioPharma dataset includes information on 407 architectural components and 1,157 dependencies between them. The architectural components are divided into: eight “business groups;” 191 “software applications;” 92 “schemas;” 49 “application servers;” 47 “database instances;” and 20 “database hosts”. These components form a layered architecture, typical of modern information systems, as we will show later. Note that “business groups” are organizational units not technical objects. The dependence of particular business groups on specific software applications and infrastructure is integral to studies of enterprise architecture. We consider business groups part of the enterprise architecture, and include them in our analysis.
We capture data on four types of dependency between components – uses, communicates with, runs on, and instantiates. Business units use applications; Applications communicate with each other, use schemas, and run on application servers. Schemas in turn instantiate database instances that run on database hosts. Importantly, of these four dependency types, “uses”, “instantiates” and “runs on” possess a specific direction (i.e. they are asymmetric dependencies). In contrast, “communicates with” is a bi-directional (i.e. symmetric) dependency.
Dependency data for the BioPharma enterprise architecture was obtained using a combination of manual and automated methods. In particular, interviews were conducted with the IT director and surveys were conducted with IT Service Owners. This information was then supplemented with the use of open-source and custom tools to monitor the server and network traffic in the system. Data on processes and communication links was then manually aggregated to the level of the individual component. Importantly, many links discovered using automatic tools had been overlooked by or were unknown to the IT Service Owners. This indicates that the theoretical (i.e. documented) system architecture can deviate substantially from the actual architecture “in use,” validating the broader motivation for our work.
Finally, for a subset of the software applications in the enterprise architecture, data was collected on the cost of making changes (discussed in Section 5).
3.2 Constructing the DSM
A DSM is a way of representing a network. Rows and columns of the matrix denote nodes in the network; off-diagonal entries indicate linkages between the nodes. In the analysis of complex systems, the rows, columns, and main diagonal elements of a DSM correspond to the components of the system – in this case, business groups and technical resources (e.g. software applications, databases, hosts etc.). Hence the first question we must answer is what kinds of linkages between components should be captured, and how should these be counted?
Influential computer scientist David Parnas argued that the most important form of linkage is a directed relationship that he calls “depends on” or “uses” [82]. If B uses A, then A fulfills a need for B. If the design of A changes, then B’s need may go unfulfilled. B’s own behavior may then need to change to accommodate the change in A. Thus change propagates in the opposite direction to use. Importantly, Parnas stresses that use is not symmetric. If B uses A, but A does not use B, then B’s behavior can change without affecting A. (We ignore the potential for indirect paths between A and B in this example.) As noted earlier, a DSM reveals this asymmetry – the marks in the rows denote one direction of the use relationship and the marks in the columns denote the other. If usage is symmetric (i.e. B uses A and A uses B), the marks will be symmetric around the main diagonal of the DSM.
Whether use proceeds from row to column or column to row is a matter of choice. There is no standard approach among DSM scholars. However, just as cars should drive on the left or the
right to avoid collision, firms should adopt one or the other convention to avoid confusion. In our methodology, *we define use as proceeding from row to column.* That is, our DSMs show how the components in a given row use (i.e. depend upon) the components in a given column. More generally, for the $i$th component in a system one looks at the $i$th element along the main diagonal. To identify the components that it depends upon, one looks along its row. To identify the components that depend upon it, one looks up and down its column.
In a layered architecture, a second convention determines the ordering of layers from top to bottom. One can place the “users” in higher layers and the objects of use in lower layers or vice versa. Most EA layer diagrams display the users at the top. In constructing DSMs, however, we depart from this practice, and place users below the objects that they use. Our reasons for doing this are based upon the concept of “design sequence” as described below.
When used as a planning tool in a design process, a DSM indicates a possible sequence of design tasks, i.e. which components should be designed before which others. In general, it is intuitive and desirable to place the first design tasks at the top of a DSM, with later tasks below. In sum, the first components to be designed should be those that other components depend on. For instance, suppose that B uses A. A’s design should be complete before B’s design is begun. Reversing this ordering runs the risk that B will have to be redesigned to comply with changes in A. Reflecting this sequence in a DSM, we place the “most used” layers on the top and the “users” of these layers towards the bottom. This convention ensures that design rules and requirements, which affect subsequent design choices, always appear at the top of the DSM.
The next question to answer is how should dependencies between elements be counted? Should the matrix cells contain only binary information, indicating a linkage, or ordinal values? Consider when the components of a system are complex entities (e.g. like applications, schemas and servers), there can be multiple ways that each component uses or depends upon the others. For instance, Application B may make different types of requests of Application A. It is possible to count those different requests and assume a linkage is “stronger” when the number of requests (or request types) is higher. Similarly, following Sharman and Yassine [83], [84], one can interpret the off-diagonal entries in a DSM as indicating the probability that a change to one component will cause a change to another. In this scenario, a value of “1” would indicate the certainty of change, while lesser values would indicate merely the possibility of change.
While these are plausible arguments, they are difficult to apply in practice. Establishing the strength of a linkage, or the probability that a change in one component requires a change in the other, has to be based on a deep level of knowledge, which rarely exists in an enterprise setting. Further, allocating different strengths or weights to dependencies can give a false sense of precision in a DSM analysis. The existence of a dependency between two elements, no matter how many ways this dependency is expressed, or how frequently it is observed in operation, merely signifies the *potential* for changes to propagate between these elements. As a consequence, we use a binary DSM as the baseline for analyzing enterprise architecture.
A layered DSM showing the BioPharma enterprise architecture is presented in Figure 1. The matrix is binary with marks in the off-diagonal cells indicating a direct dependency from row to column (and hence a change vulnerability from column to row). White space indicates there is no direct dependency between elements. To set the order of layers we use knowledge of the logical relationships between components. Usage flows from business groups (at the bottom) to applications, from applications to schemas and application servers, from schemas to database instances and from database instances to database hosts (at the top). Within layers, we order components using the component ID, an arbitrary numbering scheme. Note that “communicates with,” the dependency captured between software applications in our data, is bi-directional, hence the marks in the rows and columns of this layer are symmetric around the main diagonal.
---
§ We note further research might examine how the strength of linkages or change probabilities could be used to build Enterprise Architecture DSMs that possess greater predictive power than simple binary versions.
Figure 1. A DSM displaying BioPharma’s layered Enterprise Architecture
Summing the row entries for a given component in the DSM measures the direct outgoing coupling of that component – the number of other components that it uses. We call this measure the direct “fan-out” dependency of the component. Summing the column entries measures the direct incoming coupling of that component – the number of other components that use it. We call this measure the direct “fan-in” dependency of the component. White space to the right of a given layer indicates that components in the layer do not depend on layers below. White space to the left indicates that components in the layer do not depend on layers above.
On the whole, the DSM confirms that this enterprise architecture displays a good separation of concerns: for the most part, schemas act as an interface between applications and the database instances and hosts. Schemas are also efficiently managed: one schema may serve several applications and one application may make use of several schemas. There are two exceptions, however, as indicated by the two circles, where specific applications appear to directly use a database instance or a database host. These exceptions may indicate poor encapsulation or non-standard practices, and hence would be worth investigating further.
It is important to note that this DSM combines several diagrams and matrices that are part of TOGAF’s approach to enterprise architecture [1]. The mapping from business groups to applications (at the bottom of the DSM) corresponds to the “Application/Organization Matrix.” The square submatrix of applications corresponds to the “Application Interaction Matrix” (AIM). The mapping from applications to schemas and servers (to the left of the AIM) corresponds to the “Application Technology Matrix.” Finally, the mapping from schemas to database instances and database instances to database hosts contains the information needed to construct the “Application/Data Matrix,” while also showing how the use of data by applications operates through particular schemas and database instances. For these reasons, we believe that our methodology constitutes an important step towards making this framework more operational.
We note that the Application Interaction Matrix (AIM) is the largest submatrix in this DSM. It shows the dependencies caused by interactions between the software applications in the enterprise’s portfolio. In this dataset, dependencies between software applications are captured by the term “communicates with,” which does not possess directionality (i.e. we do not know which application is requesting a computation and which is performing it). Hence the AIM is symmetric. In general however, capturing information about directionality is always desirable. In particular, one application may always ask for a computation, and another may always supply the result. This distinction would be obscured if all dependencies were merely assumed to be symmetric. However, if applications switch roles, sometimes requesting and sometimes supplying computational services, a symmetric dependency would in fact be warranted.
4 Analyzing an Enterprise Architecture DSM
Figure 1 displays the layered structure of the enterprise architecture, but does not reveal other important architectural characteristics such as indirect coupling, cyclic coupling, hierarchy, or the presence of “core” and “peripheral” components. Matrix operations can be applied to a DSM to analyze these additional features. Specifically, the transitive closure of the matrix reveals indirect dependencies among components in addition to the direct dependencies [20], [83]. That is, if C depends on B and B depends on A, transitive closure reveals that C depends on A.
Applying the procedure of transitive closure to a DSM results in what is called the “Visibility” matrix [20], [75]. The visibility matrix captures all of the direct and indirect dependencies between elements. In a similar fashion to the DSM, row sums of the Visibility matrix, called “visibility fan-out” (VFO) measure the direct and indirect outgoing dependencies for a component. Column sums, called “visibility fan-in” (VFI) measure the direct and indirect incoming dependencies for a component. In a layered enterprise architecture, like the one observed in BioPharma, components at the top of the DSM will have high VFI and components at the bottom of the DSM will have high VFO. Critically, in cases where the systems layers are not known a priori, the Visibility matrix can be sorted using VFI and VFO to reveal the hierarchical relationships among components/layers.**
VFI and VFO can be used to identify “cyclic groups” of components, each of which is directly or indirectly connected to all others in the group. Mathematically, members of the same cyclic group all have the same VFI and VFO measures, given they are all connected directly or indirectly to each other. Thus we can identify cyclic groups in a system by sorting on these measures after performing a transitive closure on the DSM [75]. Large cyclic groups are problematic for system designers, given changes to a component may propagate via a chain of dependencies to many other components. In such a structure, the presence of cyclicity means that there is no guarantee that the design process (or a design change) will converge on a globally acceptable solution that satisfies all components [19], [60].
The density of the Visibility matrix, called Propagation Cost, provides a measure of the level of coupling for the system as a whole. Intuitively, the greater the density of the Visibility matrix, the more ways there are for changes to propagate, and thus the higher the cost of change. Large differences in propagation cost are observed across systems of similar size and function [77]. Yet empirical evidence also suggests that refactoring efforts aimed at making a design more modular can lower propagation cost substantially [20], [85]. These findings suggest that at least for software, architecture is not dictated solely by system function, but varies widely, at the discretion of a system’s architects.
Prior work has shown that the components in a system can be classified into different groups according to the levels of coupling they exhibit, as captured by VFI and VFO. Specifically, Baldwin et al. [75] use DSMs to analyze the structure of 1286 releases from 17 distinct software
** We note that while matrix methods can reveal the hierarchical relationships among components, they will not be able to tease apart discrete groups of components that have equivalent positions in the hierarchy.
applications. They find the majority of systems exhibit a “core-periphery” structure, characterized by a single dominant cyclic group of components (the “Core”) that is large relative to the system as a whole as well as to other cyclic groups. They show that the components in such systems can be divided into four groups – Core, Peripheral, Shared and Control – that share similar properties in terms of coupling. In such systems, dependencies (i.e. “usage”) flow from Control components, through Core components, to Shared components. This represents the main “flow of control” in the system. Peripheral components, by contrast, lie outside the main flow of control, given they are weakly connected to other system components.
We constructed the Visibility Matrix for BioPharma, and applied the classification methodology described in [75] to the resulting data for VFI and VFO (see Table 1). We find that the firm’s enterprise architecture has a core-periphery structure, with 132 “Core” components (i.e. components that are mutually interdependent). Furthermore, all of the Core components in the system are software applications (but note, not all software applications are classified as Core). Each of the layers in the enterprise architecture identified in Figure 1 has some components that are part of the main flow of control, and others in the “Periphery.” In total, 2/3 of the components in the architecture are part of the main flow and 1/3 are peripheral. We believe managers will find this type of classification scheme useful to set priorities, allocate resources, analyze costs, and understand potential differences in resource productivity.
<table>
<thead>
<tr>
<th></th>
<th>Shared</th>
<th>Core</th>
<th>Control</th>
<th>Periphery</th>
</tr>
</thead>
<tbody>
<tr>
<td>Database hosts</td>
<td>8</td>
<td>0</td>
<td>0</td>
<td>12</td>
</tr>
<tr>
<td>Database instances</td>
<td>15</td>
<td>0</td>
<td>0</td>
<td>32</td>
</tr>
<tr>
<td>Application servers</td>
<td>27</td>
<td>0</td>
<td>0</td>
<td>22</td>
</tr>
<tr>
<td>Schemas</td>
<td>83</td>
<td>0</td>
<td>0</td>
<td>9</td>
</tr>
<tr>
<td>Software application</td>
<td>0</td>
<td>132</td>
<td>0</td>
<td>59</td>
</tr>
<tr>
<td>Business groups</td>
<td>0</td>
<td>0</td>
<td>7</td>
<td>1</td>
</tr>
<tr>
<td><strong>TOTAL</strong></td>
<td><strong>272</strong></td>
<td><strong>135</strong></td>
<td></td>
<td></td>
</tr>
<tr>
<td><strong>Percent of Total</strong></td>
<td><strong>66%</strong></td>
<td><strong>34%</strong></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Figure 2 shows a reorganized view of BioPharma’s DSM, organized first, by type of component (i.e. Shared, Core, Periphery, Control) and second, by enterprise architecture layer. We call this the “core-periphery” view of the enterprise architecture DSM. Components in Shared, Core or Control categories are directly or indirectly connected to all Core components (and potentially, other components not in the Core) and hence represent the main flow of control. Thus each main-flow component is connected to at least 132 other components (though the direction of these dependencies will vary by category). In contrast, the highest level of coupling (i.e. visibility fan-in or visibility fan-out) for any peripheral component is only 7. Hence the indirect coupling levels of components in the main flow and the periphery are dramatically different. Assuming the level of component coupling is related to the cost of change, as Parnas [82] suggests, main-flow components will cost significantly more to change than components in the periphery. We investigate this argument empirically in the following section.
5 Using the Enterprise IT Architecture DSM to Predict Performance
In this section, we examine the relationship between measures of component coupling derived from a DSM and IT modifiability – defined as the cost of making a change to the system. Our analysis uses a subset of the data from BioPharma, for which information on the cost of change is available. Specifically, we predict the cost of change only for software applications in the enterprise architecture. We begin by developing several hypotheses about the relationship between component coupling and the cost of change.
In the previous section, we show that BioPharma’s enterprise architecture is comprised of components with very different levels of coupling. In complex systems, heterogeneous levels of component coupling are the rule, not the exception (e.g. [12], [75], [78], [85]). However, little empirical evidence exists about how different measures of coupling relate to the costs of change for a system’s components. These costs determine the agility of a firm with respect to evolving and adapting its IT systems, hereon called modifiability.
Design theory predicts that the more coupled a component is, the more difficult and expensive it will be to change [59]. However, the components of a system can be connected in different ways. Specifically, they can be connected directly or indirectly; and they can be connected hierarchically or cyclically. Furthermore, components that are hierarchically connected may be at the top or the bottom of the hierarchy, whereas components that are cyclically connected may be members of a large or a small cyclic group. Measures of these (and other) types of coupling can be derived from an enterprise architecture DSM.
In this study, we examine the performance impact of three related coupling measures:
(1) The level of Direct Coupling for each component, which is calculated by summing the entries in the rows and columns of the enterprise architecture DSM.
(2) The level of Indirect Coupling for each component, captured here by its classification as being either a Core or Peripheral component [75].
The Closeness Centrality for a component, a metric from social network theory, which can be calculated for Core components (i.e. those in the same network).††
In our dataset, data on the cost of change was available only for software applications, whose dependency relationships are defined to be symmetric. Hence it was not possible to explore the impact of differences between the number of “incoming” and “outgoing” dependencies, nor differences in the hierarchical classification of components (a symmetric DSM contains Core and Peripheral elements, but no Shared or Control elements). In general however, our method allows the exploration of these issues, in cases where dependencies are asymmetric.
Different measures of coupling are likely to be correlated. Specifically, components with high levels of direct coupling are more likely to be members of the Core. Furthermore, closeness centrality is only defined for components in the Core (i.e. those in the same network).‡‡ Finally, Core components with high levels of direct coupling are more likely to have higher closeness centrality. Hence we must be sensitive to issues of multi-collinearity. To address this issue, we conduct our analysis in two stages. First, we explore the impact of Direct and Indirect coupling on the cost of change for all applications. Then, for the subset of Core applications, we test whether the measure of closeness centrality provides additional explanatory power.
**Stage 1: Direct versus Indirect coupling.** Following Chidamber and Kemerer [69], we define direct coupling (DC) as the number of direct dependencies between one software application and all others. Note that because software dependencies are defined as symmetric, the number of incoming and outgoing dependencies is identical. The level of indirect coupling is captured by whether a software application is part of the largest cyclic group (i.e. the Core) in the system. All members of the Core have the same number of direct and indirect dependencies. Core membership is revealed through transitive closure of the DSM.§§
Design theory predicts that higher levels of direct coupling will be associated with higher costs to change. The theory of change propagation predicts that higher levels of indirect coupling (as measured by Core membership) will also lead to higher costs to change. These effects might be additive, or they might be substitutes. We thus state the following hypotheses:
**H1:** Direct Coupling (DC) is positively associated with change cost (CC).
**H2:** Core membership (CORE) is positively associated with change cost (CC).
**H3:** Direct Coupling (DC) and Core membership (CORE), considered together, explain more of the variation in change cost (CC) than either measure considered alone.
We test these hypotheses by performing OLS regressions for the impact of Direct Coupling and Core membership on the cost of change, both individually and together.
**Stage 2: Coupling within the Core.** For Core components, closeness centrality (CENT) is found by calculating the minimum path length from that component to all other components, summing those path lengths and taking the inverse of this sum [86]. The higher this number, the more “central” is the component. Our final hypothesis explores the possibility that closeness centrality explains variations in change cost for all components that are part of the same cyclic group (i.e. they possess the same high level of indirect coupling):
---
†† Closeness centrality captures how “close” a component is to other components in a network. But it can only be calculated for symmetric networks. If A depends upon B, but B does not depend upon A, then the path length from A to B, and from B to A will differ. Centrality cannot capture these subtleties. It assumes dependencies are symmetric, which is not the norm in technical systems, but is true for software applications at BioPharma.
‡‡ In prior work, the closeness centrality for elements that have no connections to others is sometimes assumed to be zero (i.e. denoting an infinite path between these and other elements).
§§ We note there was only one cyclic group in this dataset, thus components not in the Core are not part of any cyclic group. In general, however, there might be other, smaller, cyclic groups in an enterprise IT architecture.
H4: For components that are members of the Core, closeness centrality (CENT) is positively associated with change cost (CC).
We test this hypothesis by performing an OLS regression for the impact of closeness centrality on the cost of change only for Core components.
5.2 Dependent Variable: The Cost of Change for a Component
To demonstrate our methodology, we use data on the cost of change for software applications. Focusing on a single layer of the firm’s enterprise architecture (i.e. as opposed to all layers) allowed us to i) identify a specific respondent for data collection, ii) request quantitative data from these respondents, and iii) ensure the data was comparable across units.
The cost to change of each application was assessed via a survey sent to IT Service Owners. Respondents were asked to estimate the time, in person-years, to perform five IT operations: deploy, upgrade, replace, decommission, and integrate. Operations were defined as follows: “A component is deployed when it is put into production for the first time; a component is upgraded when it is replaced by a new version of the same component; a component is replaced when the existing component is removed from the information system and a new component with similar functionality is added to the information system; a component is decommissioned when it is removed from the information system; and a component is integrated when modifications are made to it that enable it to 'talk' to another component”.
We received survey responses for 99 software applications. The change cost estimates ranged from less than one-person-month to over two-person-years. Respondents could also indicate that the time to perform a given operation was unknown. Applications for which all change costs were unknown were removed from the dataset, resulting in a final sample of 77 applications. For these applications, we combined the change cost estimates for different operations into a single measure, by calculating the mean change cost for operations where a response was provided. The Cronbach’s alpha for this aggregate measure was 0.78.
5.3 Control Variables
Change costs may be affected by a number of factors that are unrelated to architecture, including the source of the component, the users of the component, its internal structure, and whether it was the focus of active development at the time of the survey. In addition, the respondent’s experience with a given component might affect the appraisal of change cost in a systematic way. Hence data on the following variables were collected and included as controls:
(1) VENDOR indicates whether an application is developed by a vendor (1) or in-house (0). One component missing data for this variable was assigned a value of 0.5.
(2) CLIENT indicates whether an application is accessed by end-users (1) or not (0).
(3) COMP indicates whether an application is focused on computation (1) or not (0).
(4) NTIER indicates whether an application has an N-tier architecture (1) or some other type of architecture, such as client-server or monolithic (0).
(5) ACTIVE indicates whether, at the time of the survey, the component was being actively enhanced (1) or was in maintenance mode (0).
*** Specifically, we asked respondents to estimate whether the effort (in person-years) required for each operation fell into the following ranges: <0.10, 0.10-0.249, 0.25-0.49, 0.50-0.99, 1.00-1.99, and > 2.00. The resulting dependent variable was an integer ranging from 1 to 6.
††† Where the estimate of change cost for an operation is missing, we substitute the mean level of change cost for that operation from all respondents to calculate Cronbach’s alpha. Other ways of treating missing values result in a minimum value for alpha of 0.66 (acceptable) to a maximum value of 0.89 (extremely good).
‡‡‡ Omitting the one application with no data provided about vendor did not change the results.
RES_EXP measures the respondent’s experience with the application in question (less than one year = 1; 1–5 years = 2; more than 5 years = 3).
5.4 Empirical Data
Table 2 presents the correlation matrix for our variables. Consistent with our hypotheses, both direct coupling (DC) and CORE are positively correlated with change cost. They are also correlated with each other (0.52). In this table, we include data on closeness centrality (CENT) for the entire sample of 77 applications, substituting a value of 0 for the 19 components not in the Core. Hence we observe an extremely high correlation (0.96) between CORE and CENT.
Among the control variables, Active components tend to have higher change costs. Vendor provided components tend to have lower change costs, have lower centrality, are more likely to perform computations, are less likely to have N-tier architectures, and are more likely to be Active. Components with N-tier architectures tend to be more highly coupled by all measures.
Table 2. Descriptive Statistics and Correlation Matrix
<table>
<thead>
<tr>
<th></th>
<th>Mean</th>
<th>St.Dev</th>
<th>#</th>
<th>CC</th>
<th>DC</th>
<th>CORE</th>
<th>CENT</th>
<th>VENDOR</th>
<th>CLIENT</th>
<th>COMP</th>
<th>NTIER</th>
<th>ACTIVE</th>
<th>RES_EXP</th>
</tr>
</thead>
<tbody>
<tr>
<td>CC</td>
<td>2.46</td>
<td>1.22</td>
<td>77</td>
<td>1</td>
<td>0.33*</td>
<td>0.33*</td>
<td>0.35**</td>
<td>-0.23*</td>
<td>-0.06</td>
<td>-0.11</td>
<td>0.17</td>
<td>0.31**</td>
<td>0.08</td>
</tr>
<tr>
<td>DC</td>
<td>3.58</td>
<td>2.83</td>
<td>77</td>
<td>0.33**</td>
<td>1</td>
<td>0.52***</td>
<td>0.68***</td>
<td>-0.19</td>
<td>0.1</td>
<td>0.01</td>
<td>0.39***</td>
<td>0.21</td>
<td>-0.08</td>
</tr>
<tr>
<td>CORE</td>
<td>0.75</td>
<td>0.43</td>
<td>77</td>
<td>0.33**</td>
<td>0.52***</td>
<td>1</td>
<td>0.96***</td>
<td>-0.17</td>
<td>0.11</td>
<td>-0.04</td>
<td>0.37***</td>
<td>0.06</td>
<td>-0.19</td>
</tr>
<tr>
<td>CENT</td>
<td>1.73</td>
<td>1.03</td>
<td>77</td>
<td>0.35**</td>
<td>0.68***</td>
<td>0.96***</td>
<td>1</td>
<td>-0.26*</td>
<td>0.14</td>
<td>-0.04</td>
<td>0.46***</td>
<td>0.12</td>
<td>-0.15</td>
</tr>
<tr>
<td>VENDOR</td>
<td>0.41</td>
<td>0.49</td>
<td>77</td>
<td>-0.23*</td>
<td>-0.19</td>
<td>-0.17</td>
<td>-0.26*</td>
<td>1</td>
<td>-0.06</td>
<td>0.39***</td>
<td>-0.52***</td>
<td>0.35**</td>
<td>0.1</td>
</tr>
<tr>
<td>CLIENT</td>
<td>0.71</td>
<td>0.45</td>
<td>77</td>
<td>-0.06</td>
<td>0.1</td>
<td>0.11</td>
<td>0.14</td>
<td>-0.06</td>
<td>1</td>
<td>0.15</td>
<td>0.27*</td>
<td>0.05</td>
<td>-0.11</td>
</tr>
<tr>
<td>COMP</td>
<td>0.39</td>
<td>0.49</td>
<td>77</td>
<td>-0.11</td>
<td>0.01</td>
<td>-0.04</td>
<td>-0.04</td>
<td>0.39***</td>
<td>0.15</td>
<td>1</td>
<td>-0.21</td>
<td>-0.05</td>
<td>0.12</td>
</tr>
<tr>
<td>NTIER</td>
<td>0.53</td>
<td>0.5</td>
<td>77</td>
<td>0.17</td>
<td>0.39***</td>
<td>0.37***</td>
<td>0.46***</td>
<td>-0.52***</td>
<td>0.27*</td>
<td>-0.21</td>
<td>1</td>
<td>0.08</td>
<td>-0.14</td>
</tr>
<tr>
<td>ACTIVE</td>
<td>0.26</td>
<td>0.44</td>
<td>77</td>
<td>0.31**</td>
<td>0.21</td>
<td>0.06</td>
<td>0.12</td>
<td>0.35**</td>
<td>0.05</td>
<td>-0.05</td>
<td>0.08</td>
<td>1</td>
<td>0.18</td>
</tr>
<tr>
<td>RES_EXP</td>
<td>2.04</td>
<td>0.84</td>
<td>77</td>
<td>0.08</td>
<td>-0.08</td>
<td>-0.19</td>
<td>-0.15</td>
<td>0.1</td>
<td>-0.11</td>
<td>0.12</td>
<td>-0.14</td>
<td>0.18</td>
<td>1</td>
</tr>
</tbody>
</table>
* p<0.05, ** p<0.01, and ***p<0.001
5.5 Empirical Results
The results of our regression tests are presented in Table 3. Model 1 contains only controls, showing that two of them are significant: Vendor provided applications tend to have lower change costs and Active applications tend to have higher change costs. The control variables alone explain 18% of the variation in change cost across applications.
Our first hypothesis, H1 predicts that direct coupling is associated with change cost, a relationship suggested by the correlations reported above. In Model 2 however, which includes control variables, we find direct coupling is only a relatively weak predictor of change cost (p-value = 0.06). This model explains 21% of the variation in change cost across applications. In Model 3, we find CORE is a highly significant predictor of change cost (p-value = 0.005). This model explains 26% of the variation in change cost across components, supporting H2.
In Model 4, we include both direct coupling and CORE in the regression, but only CORE is significant. This model explains 25% of the variation in change cost across applications, a reduction from Model 3. In sum, H1 and H2 are supported by our results, but H3 is rejected. Specifically, adding direct coupling to a model that already includes CORE makes the model worse. CORE is the strongest predictor; the power that direct coupling has as an explanatory variable in Model 1 is accounted for by its correlation with CORE.
Table 3. Regression Models
<table>
<thead>
<tr>
<th>Sample:</th>
<th>Full</th>
<th>Core only</th>
</tr>
</thead>
<tbody>
<tr>
<td>Test #</td>
<td>(1)</td>
<td>(2)</td>
</tr>
<tr>
<td>Hypothesis</td>
<td>H1</td>
<td>H2</td>
</tr>
<tr>
<td>DC</td>
<td>0.10†</td>
<td>0.04</td>
</tr>
<tr>
<td>CORE</td>
<td>0.89**</td>
<td>0.77*</td>
</tr>
<tr>
<td>CENT</td>
<td>-0.76</td>
<td></td>
</tr>
<tr>
<td>VENDOR</td>
<td>-1.21**</td>
<td>-1.10**</td>
</tr>
<tr>
<td>CLIENT</td>
<td>-0.29</td>
<td>-0.26</td>
</tr>
<tr>
<td>COMP</td>
<td>0.28</td>
<td>0.17</td>
</tr>
<tr>
<td>NTIER</td>
<td>-0.17</td>
<td>-0.33</td>
</tr>
<tr>
<td>ACTIVE</td>
<td>1.37***</td>
<td>1.19**</td>
</tr>
<tr>
<td>RES_EXP</td>
<td>0.01</td>
<td>0.04</td>
</tr>
<tr>
<td>Constant</td>
<td>2.77***</td>
<td>2.47***</td>
</tr>
<tr>
<td>Adj. Rsquare</td>
<td>0.18</td>
<td>0.21</td>
</tr>
<tr>
<td>f</td>
<td>3.75**</td>
<td>3.87**</td>
</tr>
<tr>
<td>Observations</td>
<td>77</td>
<td>77</td>
</tr>
</tbody>
</table>
† p<0.1, * p<0.05, ** p<0.01, and ***p<0.001
In models 5 and 6, we analyze only the 59 components in the Core (the largest cyclic group of components). Model 5 contains only control variables, and produces results consistent with Model 1. Model 6 includes the measure of closeness centrality, which is not significant. Hence closeness centrality provides no additional explanatory power in predicting change cost, over and above that provided by Core. We therefore reject hypothesis H4.
5.6 Robustness Checks
We performed a number of checks to assess whether our results were sensitive to other assumptions or specifications of variables. First, we note that our basic specification did not control for the size of components, a variable that could plausibly affect the cost of changes. Data on component size (measured by the number of lines of code and files in each) was available for a subsample of 60 applications. We ran our models on this smaller sample, including these as controls. The controls were insignificant, while the results for our explanatory variables were consistent with those reported above. §§§
We conducted a test to explore the possibility that transformations of direct coupling might better predict change cost, given this variable has a skewed distribution and is truncated at zero. Specifically, we included the natural log of direct coupling in models, instead of the raw value. We found the transformed variable had more explanatory power than the raw variable (i.e. its use improved the results in Model 2). However, it still explained less of the variation in change cost than CORE, hence was insignificant when included in a model with CORE.
Finally, we explored whether direct coupling, or its natural log, contribute to explaining the variation in change cost among only Core components (as we did for centrality). Appendix reports the results of three models predicting change cost, the first being a model with controls, the second adding direct coupling, and the third adding the natural log of direct coupling. Direct
§§§ Note, some of the significance levels declined as a result of the decrease in sample size and hence power.
coupling is not statistically significant in any model. This suggests that in this dataset, CORE is the most parsimonious and powerful measure of coupling that explains the cost of change. Neither direct coupling, nor centrality, contributes additional explanatory power in our models.
6 Discussion and Conclusions
The main contribution of this article is in developing a robust and repeatable network-based methodology by which to operationalize a firm’s enterprise IT architecture. The methodology is consistent with prior work in this area, and addresses several limitations of this work. Specifically, it i) integrates the consideration of business and IT related attributes; ii) identifies distinct layers in the architecture associated with different entities (e.g. applications, databases, etc.); iii) reveals the “flow of control” within the architecture across its associated layers and; iv) generates measures of the architecture that can be used to predict performance. We demonstrate the application of this methodology to predict IT modifiability using a real-world dataset, and show that it generates insights that could not have been gained merely from the inspection of documents or processes traditionally associated with EA frameworks.
A second contribution of this article lies in the specific results we report using our methodology to analyze enterprise architecture. Specifically, we explore the relationship between measures of coupling derived from a DSM, and IT modifiability – defined as the cost of change for software applications. The measure of coupling that best predicts change cost is not the number of direct dependencies for a component, but all of the direct and indirect dependencies it has with other components. Once the variation in change cost explained by this measure is accounted for, other measures of coupling add no further explanatory power. This suggests a firm’s agility to adapt its IT infrastructure (modifiability) is driven mainly by the potential for changes to propagate from one component to others via chains of dependencies. Such data is not visible from inspection of a component’s “nearest neighbors.” Rather, our findings lend support to the methods we employ, which reveal all of the indirect paths that exist between system components.
For managers, our methodology provides a clear picture of the actual instantiated architecture that they possess, as opposed to high level conceptual representations often found in documents depicting a firm’s IT architecture. The insights thereby generated will prove useful in several ways, including i) helping to plan the allocation of resources to different components, based upon predictions of the relative ease/difficulty of change; ii) monitoring the evolution of an architecture over time, as new components and/or dependencies are introduced (e.g. when a new firm is acquired) and; iii) identifying opportunities to improve the architecture, for instance, by reducing coupling, and hence reducing the cost to change specific components.
Ironically, in this era of “big data,” the lack of appropriately granular data may be the largest barrier to the systematic investigation of an enterprise architecture using our methodology. At a minimum, firms need to capture data on the dependencies between different components in the enterprise architecture, and the way that these dependencies evolve over time. To fully use this data, they must also systematically capture performance data on the cost of change for components over time. In most organizations we have worked with, this type of data does not exist. In some, efforts have been made to collect this data manually. However, there are many challenges associated with this approach, including a lack of incentives to provide accurate and timely information. In this study, we found substantial omissions in the data collected via survey, in comparison to the automated tools we used to uncover system dependencies. In essence, many firms do not know the “real” enterprise IT architecture that they possess. As Eppinger and Browning [87] state: “for most product DSM models, the data collection requires at least some amount of direct discussion with subject matter experts in order to draw out the tacit and system-level knowledge that may not be captured in the documentation.” However, manual methods of dependency extraction are labor-intensive, and limit the scale, precision and accuracy of analyses. The ideal solution would be to develop more automated ways to detect and capture
important dependencies between components in a firm’s enterprise architecture. This implies the need for some investment by firms who wish to adopt these methods. We believe the benefits associated with these investments would more than offset the costs, given the increase in understanding of the firm’s IT architecture that would result.
For the academy, this study contributes to the field of enterprise IT architecture in several ways. First, it makes what has been a rather conceptual area more grounded, providing a method to analyze a firm’s architecture in-use, rather than the processes and documents through which it is created and managed. Second, it provides a way to operationalize frameworks like TOGAF [1], defining how the matrices they include can be quantified and analyzed. Finally, our methodology generates metrics that capture the level of coupling between different components in a firm’s IT architecture, reveals the main “flow of control” across the system, and allows us to examine how IT modifiability might vary for different system components.
Our work opens up the potential for further empirical research that could explore the relationship between enterprise architecture and performance. Within organizations, work might focus on the relationship between measures of coupling, and a variety of performance measures relevant to individual components in the architecture (e.g. reliability, security, productivity). In contrast, studies across different organizations might reveal how measures of enterprise architecture affect firm-level performance. The latter area is particularly promising, given prior literature argues there is a strong linkage between certain types of architecture and firm-level attributes, such as agility. One might ask, for instance, whether loosely coupled architectures, in general, facilitate a rapid response to unpredictable business challenges? Or are there subtle nuances to account for, with respect to different layers in the architecture (e.g. is the use of shared databases – with the pattern of coupling this entails – a best practice)? This methodology allows us to answer such questions, with an approach that can be replicated across studies.
Our study is subject to a number of limitations that must be considered when assessing the generalizability of results. In particular, the data to demonstrate our methods comes from a single firm. Hence more work is needed to provide validation of these methods across different contexts. Furthermore, questions remain as to the different layers/components that should be included in the analysis of enterprise IT architecture, and the types of dependency that exist between them. For instance, we may find that different types of dependency (e.g. “uses” versus “communicates with”) predict different dimensions of performance (e.g. modifiability versus reliability). Similarly, we may find that different measures of coupling (e.g. direct versus indirect coupling) may predict performance differently across different contexts. Ultimately, our methods provide a platform to enable researchers to answer a variety of questions that until now have proved elusive. As such, we hope that future scholars will improve upon and evolve these methods, in order that we benefit from the cumulative nature of enterprise IT knowledge.
References
**** E.g. in software, automatic dependency extractors supplied by commercial vendors can be used to create DSMs with no manual effort needed (e.g. [20], [77], [88], [89]).
Appendix: Models Predicting Change Cost only for Core Components
<table>
<thead>
<tr>
<th>MODEL</th>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>DC</td>
<td></td>
<td>0.03</td>
<td></td>
</tr>
<tr>
<td>DC(In)</td>
<td></td>
<td></td>
<td>0.09</td>
</tr>
<tr>
<td>VENDOR</td>
<td>-1.40***</td>
<td>-1.37**</td>
<td>-1.37**</td>
</tr>
<tr>
<td>CLIENT</td>
<td>-0.69†</td>
<td>-0.68†</td>
<td>-0.68†</td>
</tr>
<tr>
<td>COMP</td>
<td>0.22</td>
<td>0.20</td>
<td>0.21</td>
</tr>
<tr>
<td>NTIER</td>
<td>-0.44</td>
<td>-0.47</td>
<td>-0.46</td>
</tr>
<tr>
<td>ACTIVE</td>
<td>1.69***</td>
<td>1.64***</td>
<td>1.65***</td>
</tr>
<tr>
<td>RES_EXP</td>
<td>-0.01</td>
<td>0.00</td>
<td>-0.00</td>
</tr>
<tr>
<td>Constant</td>
<td>3.45***</td>
<td>3.35***</td>
<td>3.34***</td>
</tr>
<tr>
<td>Adj. Rsquare</td>
<td>0.25</td>
<td>0.24</td>
<td>0.24</td>
</tr>
<tr>
<td>f</td>
<td>4.17**</td>
<td>3.55</td>
<td>3.52</td>
</tr>
<tr>
<td>Observations</td>
<td>58</td>
<td>58</td>
<td>58</td>
</tr>
</tbody>
</table>
† p<0.1, * p<0.05, ** p<0.01, and ***p<0.001
|
{"Source-Url": "https://csimq-journals.rtu.lv/article/download/csimq.2019-19.05/1621", "len_cl100k_base": 15201, "olmocr-version": "0.1.53", "pdf-total-pages": 24, "total-fallback-pages": 0, "total-input-tokens": 80558, "total-output-tokens": 21674, "length": "2e13", "weborganizer": {"__label__adult": 0.0006113052368164062, "__label__art_design": 0.004169464111328125, "__label__crime_law": 0.0006384849548339844, "__label__education_jobs": 0.016082763671875, "__label__entertainment": 0.0003299713134765625, "__label__fashion_beauty": 0.0003581047058105469, "__label__finance_business": 0.0164031982421875, "__label__food_dining": 0.0006804466247558594, "__label__games": 0.0014448165893554688, "__label__hardware": 0.0025119781494140625, "__label__health": 0.0010528564453125, "__label__history": 0.0012693405151367188, "__label__home_hobbies": 0.00026702880859375, "__label__industrial": 0.001800537109375, "__label__literature": 0.0011606216430664062, "__label__politics": 0.00045180320739746094, "__label__religion": 0.0007419586181640625, "__label__science_tech": 0.377685546875, "__label__social_life": 0.00014472007751464844, "__label__software": 0.037628173828125, "__label__software_dev": 0.53271484375, "__label__sports_fitness": 0.0002853870391845703, "__label__transportation": 0.0010890960693359375, "__label__travel": 0.00040793418884277344}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 84932, 0.07272]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 84932, 0.53877]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 84932, 0.89835]], "google_gemma-3-12b-it_contains_pii": [[0, 2088, false], [2088, 6709, null], [6709, 10792, null], [10792, 15184, null], [15184, 19515, null], [19515, 23535, null], [23535, 27909, null], [27909, 32576, null], [32576, 34829, null], [34829, 39252, null], [39252, 43212, null], [43212, 44752, null], [44752, 49100, null], [49100, 53028, null], [53028, 56986, null], [56986, 60281, null], [60281, 64838, null], [64838, 69260, null], [69260, 73786, null], [73786, 78495, null], [78495, 78495, null], [78495, 83169, null], [83169, 84365, null], [84365, 84932, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2088, true], [2088, 6709, null], [6709, 10792, null], [10792, 15184, null], [15184, 19515, null], [19515, 23535, null], [23535, 27909, null], [27909, 32576, null], [32576, 34829, null], [34829, 39252, null], [39252, 43212, null], [43212, 44752, null], [44752, 49100, null], [49100, 53028, null], [53028, 56986, null], [56986, 60281, null], [60281, 64838, null], [64838, 69260, null], [69260, 73786, null], [73786, 78495, null], [78495, 78495, null], [78495, 83169, null], [83169, 84365, null], [84365, 84932, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 84932, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 84932, null]], "pdf_page_numbers": [[0, 2088, 1], [2088, 6709, 2], [6709, 10792, 3], [10792, 15184, 4], [15184, 19515, 5], [19515, 23535, 6], [23535, 27909, 7], [27909, 32576, 8], [32576, 34829, 9], [34829, 39252, 10], [39252, 43212, 11], [43212, 44752, 12], [44752, 49100, 13], [49100, 53028, 14], [53028, 56986, 15], [56986, 60281, 16], [60281, 64838, 17], [64838, 69260, 18], [69260, 73786, 19], [73786, 78495, 20], [78495, 78495, 21], [78495, 83169, 22], [83169, 84365, 23], [84365, 84932, 24]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 84932, 0.19485]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
003e0972df7bacf7a86e2dd4020a24c4a820f9b7
|
[REMOVED]
|
{"Source-Url": "http://www-wjp.cs.uni-saarland.de/leute/private_homepages/starostin/context-vstte08-preprint.pdf", "len_cl100k_base": 9420, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 49232, "total-output-tokens": 11259, "length": "2e13", "weborganizer": {"__label__adult": 0.00040531158447265625, "__label__art_design": 0.00035190582275390625, "__label__crime_law": 0.0003979206085205078, "__label__education_jobs": 0.0006542205810546875, "__label__entertainment": 6.884336471557617e-05, "__label__fashion_beauty": 0.0001780986785888672, "__label__finance_business": 0.0002989768981933594, "__label__food_dining": 0.0004172325134277344, "__label__games": 0.0007109642028808594, "__label__hardware": 0.0027751922607421875, "__label__health": 0.0006918907165527344, "__label__history": 0.00030875205993652344, "__label__home_hobbies": 0.00013148784637451172, "__label__industrial": 0.0006666183471679688, "__label__literature": 0.0002739429473876953, "__label__politics": 0.0003070831298828125, "__label__religion": 0.0005660057067871094, "__label__science_tech": 0.08538818359375, "__label__social_life": 7.969141006469727e-05, "__label__software": 0.007190704345703125, "__label__software_dev": 0.896484375, "__label__sports_fitness": 0.00032401084899902344, "__label__transportation": 0.0009098052978515624, "__label__travel": 0.0002218484878540039}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 44927, 0.0205]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 44927, 0.29723]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 44927, 0.85527]], "google_gemma-3-12b-it_contains_pii": [[0, 2472, false], [2472, 5921, null], [5921, 8857, null], [8857, 11259, null], [11259, 14304, null], [14304, 17616, null], [17616, 20602, null], [20602, 24296, null], [24296, 26555, null], [26555, 28791, null], [28791, 32054, null], [32054, 35174, null], [35174, 38591, null], [38591, 41482, null], [41482, 44927, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2472, true], [2472, 5921, null], [5921, 8857, null], [8857, 11259, null], [11259, 14304, null], [14304, 17616, null], [17616, 20602, null], [20602, 24296, null], [24296, 26555, null], [26555, 28791, null], [28791, 32054, null], [32054, 35174, null], [35174, 38591, null], [38591, 41482, null], [41482, 44927, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 44927, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 44927, null]], "pdf_page_numbers": [[0, 2472, 1], [2472, 5921, 2], [5921, 8857, 3], [8857, 11259, 4], [11259, 14304, 5], [14304, 17616, 6], [17616, 20602, 7], [20602, 24296, 8], [24296, 26555, 9], [26555, 28791, 10], [28791, 32054, 11], [32054, 35174, 12], [35174, 38591, 13], [38591, 41482, 14], [41482, 44927, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 44927, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-06
|
2024-12-06
|
9608441fae48b499409de6eb987349032561faaf
|
[REMOVED]
|
{"Source-Url": "https://rd.springer.com/content/pdf/10.1007/3-540-45559-0_9.pdf", "len_cl100k_base": 10075, "olmocr-version": "0.1.50", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 45053, "total-output-tokens": 13403, "length": "2e13", "weborganizer": {"__label__adult": 0.0002758502960205078, "__label__art_design": 0.0005016326904296875, "__label__crime_law": 0.0002498626708984375, "__label__education_jobs": 0.0005435943603515625, "__label__entertainment": 6.0439109802246094e-05, "__label__fashion_beauty": 0.0001220107078552246, "__label__finance_business": 0.0001531839370727539, "__label__food_dining": 0.00023937225341796875, "__label__games": 0.0004377365112304687, "__label__hardware": 0.0005373954772949219, "__label__health": 0.0003056526184082031, "__label__history": 0.00020122528076171875, "__label__home_hobbies": 5.59687614440918e-05, "__label__industrial": 0.000247955322265625, "__label__literature": 0.00023949146270751953, "__label__politics": 0.00019860267639160156, "__label__religion": 0.0003714561462402344, "__label__science_tech": 0.01215362548828125, "__label__social_life": 6.496906280517578e-05, "__label__software": 0.007228851318359375, "__label__software_dev": 0.97509765625, "__label__sports_fitness": 0.0002086162567138672, "__label__transportation": 0.0003261566162109375, "__label__travel": 0.00016415119171142578}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 62862, 0.02094]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 62862, 0.39554]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 62862, 0.89893]], "google_gemma-3-12b-it_contains_pii": [[0, 2732, false], [2732, 5978, null], [5978, 9451, null], [9451, 12844, null], [12844, 14542, null], [14542, 17352, null], [17352, 20767, null], [20767, 22519, null], [22519, 25670, null], [25670, 28863, null], [28863, 31213, null], [31213, 34422, null], [34422, 37726, null], [37726, 41076, null], [41076, 44359, null], [44359, 47474, null], [47474, 50918, null], [50918, 53812, null], [53812, 57039, null], [57039, 60738, null], [60738, 62862, null]], "google_gemma-3-12b-it_is_public_document": [[0, 2732, true], [2732, 5978, null], [5978, 9451, null], [9451, 12844, null], [12844, 14542, null], [14542, 17352, null], [17352, 20767, null], [20767, 22519, null], [22519, 25670, null], [25670, 28863, null], [28863, 31213, null], [31213, 34422, null], [34422, 37726, null], [37726, 41076, null], [41076, 44359, null], [44359, 47474, null], [47474, 50918, null], [50918, 53812, null], [53812, 57039, null], [57039, 60738, null], [60738, 62862, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 62862, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 62862, null]], "pdf_page_numbers": [[0, 2732, 1], [2732, 5978, 2], [5978, 9451, 3], [9451, 12844, 4], [12844, 14542, 5], [14542, 17352, 6], [17352, 20767, 7], [20767, 22519, 8], [22519, 25670, 9], [25670, 28863, 10], [28863, 31213, 11], [31213, 34422, 12], [34422, 37726, 13], [37726, 41076, 14], [41076, 44359, 15], [44359, 47474, 16], [47474, 50918, 17], [50918, 53812, 18], [53812, 57039, 19], [57039, 60738, 20], [60738, 62862, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 62862, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-02
|
2024-12-02
|
1049a71d69d39792b39fce1f3e1539778346054a
|
1.0. Introduction
For several generations, the most widely sold toys have been those that allow you to take small simple objects and combine them to create a replica of some real-world object. Initially starting out as a large pile of plastic blocks with varying shapes and colors, they can transform into a multistage ignition rocket ship or an elegant mansion without a roof.
Toys aren’t the only place we see this sort of design. Almost everywhere you look, this piecewise refinement is evident in many facets of everyday life. Cars aren’t built using a myriad of non-connecting objects but rather are assembled from smaller pieces to form the engine, for instance, which is then used as a component in the final automobile. Using another example, a company contains employees who form a team. These teams combine to form a section or business unit, and these units group together to form the corporation. In fact, this type of organization doesn’t just make sense in the physical realm but is prevalent in many natural things as well.
Based on this concept, it comes as no surprise that software is logically divided into smaller pieces that contribute to a solution when assembled. At the lower levels of the programming language construct hierarchy are the operator, the expression, and the control structure. An expression is any group of operators and operands that are combined to perform some type of computation, such as setting a variable, calling a function, or performing a system-related task.
In this chapter, we look at all the various C# language elements that are available to construct an application. From the basic layout of a small console application to using overloaded operators to change the semantic meaning of objects, this chapter points out the various options you have at your disposal to efficiently design your next Visual C# .NET application.
1.1. Understanding Visual C# .NET Program Layout
You want to create a simple Visual C# .NET console application and inspect the generated code.
Technique
In the Visual Studio .NET IDE, click on File, New, Project (Ctrl+Shift+N) and select Visual C# Projects from the list of project types. In the list of templates, select the Console Application template and type in a name for the project.
Comments
For most of this chapter and in several projects throughout this book, you’ll find yourself working with console-based applications. Their minimalist nature allows you to concentrate on the topic being discussed without having to traverse through extraneous, potentially distracting code.
Even though it is just a simple console-based application that currently provides no functionality, it does serve as a good illustration for some of the various pieces that make a C# application. Once you create your project, the Visual Studio .NET IDE opens the application’s main program file, which should look similar to Listing 1.1.
Listing 1.1 A Simple Visual C# .NET Console Application
```csharp
using System;
namespace _1_ProgramLayout
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class DateTimePrinter
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Console.WriteLine( "Today is {0}", DateTime.Now );
}
}
}
```
The first couple of lines relate to an organizational construct known as the namespace. Namespaces convey a sense of relationships between like objects. For instance, if you have some objects with such names as Frame, Engine, Wheel, Light, and Seat, you immediately see the relationship these objects possess in that they all belong on an automobile. In this example, the namespace could be Automobile.
On the first line, the program is letting the compiler know that it wants to use some of the objects within the System namespace. Therefore, anytime you want to use one of these objects, you do not need to preface the object name with the namespace name. For instance, the WriteLine statement prints out a small message in the console. The Console object is a class within the System namespace. Without the using directive, you have to qualify each type you want to use with the namespace it is declared in. In this instance, the line in Listing 1.1 would be
```csharp
System.Console.WriteLine( "Today is {0}", DateTime.Now );
```
In the listing, you can see a namespace declaration, which is simply the name you gave the project when you initially created it. Although the wizard placed an initial type in a namespace for you to use, the namespace declaration itself is purely optional. However, we recommend that you do get into the habit of using namespaces to enhance code organization and readability.
Within the automatically generated namespace is a class called Class1, which was renamed to DateTimePrinter to more accurately describe the type’s functionality (albeit somewhat limited). A class is best described as a data type that can contain various associated methods to interact with it. Whenever an instance of that class is created or instantiated, it becomes a usable object to which you can get or set various properties, receive notification of certain events, and tell it to perform some action using one of its member functions. Chapter 2, “Objects and Components,” delves deeper into the many ways classes are used within C# and the .NET Framework.
The last important component of our simple console application is the application’s entry point, denoted by the static member function Main. Each application must contain an entry point so that the Common Language Runtime (CLR) can effectively start the application by handing control over to you. Once the Main function exits, the application ends. Just before the Main method declaration is the STAThread attribute. This attribute denotes the threading model your application uses. However, it is only applicable if you plan to use COM Interop, discussed in Chapter 24, “COM Interop,” and is ignored if you do not.
1.2. Parsing Command-Line Arguments
You want your application to support command-line argument parsing.
**Technique**
Use a string array as a parameter in your application’s entry point, the static `Main` function.
```csharp
using System;
class CommandLineArgs
{
static void Main(string[] args)
{
foreach (string arg in args)
Console.WriteLine(arg + "\n");
}
}
```
**Comments**
The `Main` function in an application has the option of accepting a string array as a parameter. This array contains the command-line arguments passed to it by the system where each element in the array corresponds to a string on the command line delineated by quotation marks or whitespace.
1.3. Creating Multiple Application Entry Points
You want your application to contain several entry points.
**Technique**
For each entry point you want to add, create a separate class containing a static `Main` member function. To change which entry point is run by the CLR, go to the project properties (Alt+P,P) and select Common Properties, General. Select the function you want to use as the application entry point in the Startup Object field. You must then recompile your project any time you change the application entry point because you can only change the entry point at compile time, not at runtime.
Comments
There are several reasons why creating several application entry points is advantageous. One key advantage is that it allows you to control the flow of your application to test different avenues of functionality. For instance, you can create an entry point that serves to display a tremendous amount of debugging information at runtime. When you are confident that the unit tests you created are working correctly, you can create a final application entry point that removes most of the debugging information. However, in the past, you might have had to comment out or remove the critical debugging information. By creating a separate entry point, you gain the advantage of preserving your unit tests that you can run simply by changing a property within your project. With a little clever command-line compiling, you can even create an automated test harness that compiles your application, specifying one of your unit-test application entry points; verify that the results are satisfied; and repeat that process for each entry point.
To compile a C# program from the command line and specify which startup object to use as the application entry point, use the /main command-line argument for the compiler. Listing 1.2 contains a project source file that contains three different application entry points. To compile this file on the command line and specify an application entry point, you invoke the C# compiler using the following:
csc.exe Class1.cs /main:_3_MultEntryPoints.EntryPointTest.Main3Entry
Listing 1.2 A C# Application Containing Multiple Application Entry Points
```csharp
using System;
namespace _3_MultEntryPoints
{
class EntryPointTest
{
class Main1Entry
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine( "Running in Main" );
}
}
class Main2Entry
{
[STAThread]
static void Main(string[] args)
{
Console.WriteLine( "Running in Main2" );
}
}
}
}
```
1.4. Referencing Assemblies and Namespaces
You want to use a class, but the compiler says that the class cannot be found.
**Technique**
Add a reference to the assembly that defines the class by clicking on the Project, Add Reference from the main menu. Select the .NET tab, locate the assembly that contains the type you want to use, and double-click it.
**Comments**
The .NET Framework uses information in an assembly to resolve type information when you want to use a class. An assembly is simply the file that is created when you compile a project such as an .exe or dynamic link library (.dll) file. When you perform the steps of referencing an assembly, the compiler knows to look in each referenced assembly during compilation to resolve any types that are encountered within the source file.
1.5. Creating Valid Identifier Names
You want to ensure that the identifier follows the rules of valid identifier naming.
**Technique**
Your identifier cannot be the same as that of a C# keyword. You are free to use any combination of letters, numbers, and underscore characters as long as the identifier does not start with a number. Furthermore, you can use the @ symbol as the first character in your identifier. Listing 1.3 shows several valid and invalid identifier names.
Listing 1.3 **Demonstrating Valid and Invalid Identifier Names**
```csharp
namespace _5_Identifiers
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
int i; // valid
int @int; // valid but confusing
int INT; // valid since C# is case sensitive
int 4_Score; // Not valid. Cannot begin with a digit
int in@t; // not valid. @ symbol not at beginning
int int; // not valid. Cannot use keywords
}
}
}
```
**Comments**
Identifiers name certain programming elements within a program. They include such items as namespace names, classes, and variables. It is good programming practice to create identifiers that convey important information about the element it is defined as. In the days before .NET, Hungarian notation was used as the de facto standard for identifier naming, at least for those using the C++ language within a Windows program. Although some people argue for or against its suitability as a standard, the fact remains that it was a standard which could alleviate some of the issues that go along with reading someone else's source code. With the release of .NET, Microsoft dropped the Hungarian-notation guideline due to the cross-language support within the .NET Framework. Some of these identifier guidelines include using a combination of Pascal and Camel case for character capitalization within an identifier as well as using semantics in the identifier name. If you want to learn more about the guidelines Microsoft uses for the .NET Framework, search MSDN using the phrase “naming guidelines.”
### 1.6. Working with Numeric Types
**You need to store data in a variable as an integral type.**
**Technique**
Choosing the correct data type can almost be considered an art. Keep in mind the range of possible values for the data you need to store in memory and whether you need a signed or unsigned data type.
Comments
There are eight types designed to work with numerical data. Each of the types is designated based on its size and whether it is signed. The smallest integral types available to C# are the 8-bit `byte` with a range of 0 to 255 and the 8-bit `sbyte`, a signed data type with a range of –128 to 127. At the far end of the spectrum are the 64-bit `ulong` and the signed version, the `long`. Table 1.1 shows the possible numerical data types as well as their sizes in bits and range.
<table>
<thead>
<tr>
<th>Data Type</th>
<th>Size (Bits)</th>
<th>Range</th>
</tr>
</thead>
<tbody>
<tr>
<td>sbyte</td>
<td>8</td>
<td>-128 to 127</td>
</tr>
<tr>
<td>byte</td>
<td>8</td>
<td>0 to 255</td>
</tr>
<tr>
<td>short</td>
<td>16</td>
<td>-32,768 to 32,767</td>
</tr>
<tr>
<td>ushort</td>
<td>16</td>
<td>0 to 65,535</td>
</tr>
<tr>
<td>char</td>
<td>16</td>
<td>0 to 65,535</td>
</tr>
<tr>
<td>int</td>
<td>32</td>
<td>-2,147,483,648 to 2,147,483,647</td>
</tr>
<tr>
<td>uint</td>
<td>32</td>
<td>0 to 4,294,967,295</td>
</tr>
<tr>
<td>long</td>
<td>64</td>
<td>-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807</td>
</tr>
<tr>
<td>ulong</td>
<td>64</td>
<td>0 to 18,446,744,073,709,551,615</td>
</tr>
</tbody>
</table>
When working with integral data types, you have to weigh two options. First of all, even though we live in an age where memory is in abundance, you should still attempt to keep memory usage to a minimum. Sometimes, your application might need to run in a low-memory environment, and by choosing a design that optimizes memory usage, you can benefit from this strategy. Secondly, you must ensure that the data type you choose is large enough to hold any value you assign to it. If you inadvertently assign a number outside of a data type’s range, your application will encounter a situation that it is not prepared to deal with. Based on your project properties and whether you are using exception handling, which is explained later in this book, the CLR will do one of two things. First, your application will throw an `OverflowException`. It is then your responsibility to handle this exception or face the consequences of an application crash.
By default, your project is created with overflow checking turned off. This default means that the CLR does not check whether a value being assigned to a data type causes an overflow. Rather, it takes a safer approach, which is either to flip the bits of the data type, thereby causing it to change sign, or to simply roll the value back to 0 in the case of unsigned data. As you might guess, this process can have undesirable side effects in your application and can lead to subtle defects that might be hard to find.
To turn on overflow checking in your project, open the property pages of your project by choosing Project, Properties (Alt+P). Select Configuration Properties, Build. Set the property labeled Check for Arithmetic Overflow to `True` so that data types are...
checked for overflow, as shown in Figure 1.1. If you believe that once you thoroughly test your code with all possible inputs your data types will not overflow, you can consider setting this property to False. The safest and most advantageous route is to enable this property when you build in debug mode and turn it off, as an optimization technique, during release builds.
![Image of project properties for checking arithmetic overflows.]
**Figure 1.1** Changing project properties to check for arithmetic overflows.
### 1.7. Working with Floating-Point Numbers
Your application needs to work with floating-point values and you need to determine the correct type to use.
**Technique**
If memory is your primary concern and the range of possible values isn’t too large, use the `float` data type. If you need very large values knowing that you need to sacrifice precision, use the `double` data type. If you need accurate and precise data, use the `decimal` data type.
**Comments**
Just as with integral types, choosing the proper floating-point number is essential to creating a robust application. There are two main points to consider when deciding which floating-point data type to choose: size and precision.
The .NET floating-point data types allow you to use exponential notation. For instance, the float data type has a range of \( \pm 1.5 \times 10^{-45} \) to \( \pm 3.4 \times 10^{38} \). Although this range is certainly large, the precision of the float only allows for a maximum of seven digits. Any digits after the seventh digit are simply changed to a 0. For financial applications, this change could result in the improper calculation of money, which could have harsh repercussions from the clients who use your software. If, however, you are programming a video game, you might not need precision greater than seven digits. You might have small side effects but nothing like the side effects a loss of precision on a financial calculation would yield.
The double data type has the largest range of all the floating types. It can contain values in the range of \( 5.0 \times 10^{-324} \) to \( 1.7 \times 10^{308} \). Its precision is limited to just 15 to 16 digits. Although the precision is larger than that of a float, it still might not be suited for financial calculations.
The decimal data type is the only floating type not based on an IEEE specification; it is an exclusive .NET Framework type. This 128-bit number contains a precision of 28 to -29 digits, which makes it the most precise floating-point type. However, its range isn’t as widespread as the double data type. It can contain values in the range from \( 1.0 \times 10^{-28} \) to \( 7.9 \times 10^{28} \).
To resolve ambiguities when working with floating-point numbers, C# contains a suffix for each type. For instance, if you want to assign a number to a double type, use the suffix d as in 3.14d. To designate a float data type, supercede the number with a f. Finally, to use a decimal number, use the m suffix.
### 1.8. Creating Value Types with struct
You want to create a new data type that behaves more like a value than a class.
**Technique**
Define a structure using the `struct` keyword. A struct behaves similar to a class in that it can contain any number of member variables, methods, properties, and indexers, but memory for it is allocated on the stack rather than the heap, which also implies that it is passed by value rather than by reference. The following code demonstrates a temperature value type that performs a conversion if the Fahrenheit property is accessed:
```csharp
struct TemperatureStruct
{
public double Celsius;
public double Fahrenheit
{
get
{
```
Chapter 1 Operators, Expressions, and Control Structures
```
return ((9d/5d)*Celsius)+32;
```
```
set
{
Celsius = (5d/9d)*(value-32);
}
```
Comments
Sometimes, a language’s built-in data types just aren’t sufficient to use as a data-storing mechanism. Although using them would most certainly work, you generally need several related variables to describe all the pieces of pertinent information about a single object or abstract value type. Structures, or structs, were designed to organize and group built-in data types to create user-defined types that could emulate values.
One of the most prominent distinguishing differences between structs and classes is that you do not have to instantiate a struct using the `new` operator. You don’t have to declare a default constructor because the compiler will ensure that all members are initialized by using a process known as static flow analysis. Sometimes, however, the analysis is unable to determine whether a member can be initialized. You can make the determination by declaring a private member variable within your struct. In this case, you have to create a custom parameterized constructor, and clients using your struct must create it using the `new` operator. Based on this information, you might make the assumption that using `new` on the struct would then allocate it on the heap. We can in fact verify that it does not by looking at the intermediate language (IL) code generated by the compiler using a tool, ILDasm, which is perfect when you want to investigate a certain behavior.
To run the ILDasm tool, you need to navigate to the `bin` directory of the .NET Framework SDK. You can double-click on the file to run it, but there are some advanced options available if you run the executable and specify the command-line argument `/ADV`. For this exercise, you can simply run it without the advanced options. Listing 1.4 shows an application that contains a class called `TemperatureClass` and a struct named `TemperatureStruct`. When you build this application, open the assembly in ILDasm. Expand the tree item of the namespace that contains the class and struct definition, which in this case is `_8_ValueTypes`. You should see three data types defined in the assembly: the main entry point, the temperature class, and the temperature struct. Expand the tree item that denotes the class where the entry point is located. Finally, double-click on the `Main` function to display the disassembled IL code shown in Figure 1.2.
Listing 1.4 Comparing Differences Between a Class and a Struct
```csharp
using System;
namespace _8_ValueTypes
{
class EntryPoint
{
[STAThread]
static void Main(string[] args)
{
TemperatureStruct ts = new TemperatureStruct();
TemperatureClass tc = new TemperatureClass();
Console.Write( "Enter degrees in Celsius: " );
string celsius = Console.ReadLine();
ts.Celsius = Convert.ToDouble(celsius);
Console.WriteLine( "Temperature in Fahrenheit = {0}", ts.Fahrenheit );
}
}
class TemperatureClass
{
public double Fahrenheit { get; set; }
public double Celsius { get; set; }
}
class TemperatureStruct
{
public double Celsius { get; set; }
public double Fahrenheit { get; set; }
}
}
```
Figure 1.2 ILDasm is a good tool to understand the inner workings of your application and how it interacts with the CLR.
Listing 1.4 Continued
{
private double degreesCelsius;
public double Fahrenheit {
get {
return ((9d/5d)*degreesCelsius)+32;
}
set {
degreesCelsius = (5d/9d)*(value-32);
}
}
public double Celsius {
get {
return degreesCelsius;
}
set {
degreesCelsius = value;
}
}
}
struct TemperatureStruct {
public double Celsius;
public double Fahrenheit {
get {
return ((9d/5d)*Celsius)+32;
}
set {
Celsius = (5d/9d)*(value-32);
}
}
}
Chapter 1 Operators, Expressions, and Control Structures
One particular portion of the IL for the Main function in Listing 1.4 is the four lines following the declaration of the locals that are used within the function:
```
IL_0000: ldloca.s ts
IL_0002: initobj _8_ValueTypes.TemperatureStruct
IL_0008: newobj instance void_8_ValueTypes.TemperatureClass::.ctor()
IL_000d: stloc.1
```
The first two lines initialize the struct. The important piece of information here is the instructions `ldloca` and `initobj`. Compare these two instructions with the two that are used for initialization of the temperature class, `newobj` and `stloc`. When you use the `new` operator on the class, it generates the `newobj` instruction using the class constructor as the operand. However, when you use `new` on the struct, it performs a `ldloca.s`, which is an instruction used to fetch an object from the stack. Based on this information, even though you use the `new` keyword on a struct, it still follows the rules in that it is a stack-allocated rather than a heap-allocated object.
**Note**
Most of the built-in C# data types are structs themselves. For instance, the `int` is simply an alias for the `System.Int32` structure.
## 1.9. Converting Data Types
You need to convert a value of one type to an equivalent value of another type.
**Technique**
```csharp
long l = 0;
int i = 0;
l = i;
```
If however you need to convert a data type from a larger to a smaller size, you need to explicitly convert the value using the `System.Convert` class or through a technique known as *casting*:
```csharp
long l = 0;
int i = 0;
i = Convert.ToInt32(l);
i = (int)l;
```
For any objects you want to convert to a string, simply use the `ToString` method, which is defined for all .NET value types:
```csharp
int i = 0;
string s = i.ToString();
```
Every value type defined in the .NET Framework contains a static method named `Parse`. It allows you to convert a string value to that value type. The string itself must be formatted correctly or a `FormatException` will occur.
```csharp
string sNum = "3.1415936535";
double dNum = Double.Parse(sNum);
```
**Comments**
Data conversion is a process that tends to occur frequently. The most frequent case is when you need to call a function whose parameters are different types than what you have been using in your application. Regardless of how different those two types are, an implicit or an explicit conversion will take place.
*Implicit* conversion occurs when the data type you want to convert to is a larger size than the data type you are converting from. For example, if a method needs a `long` data type (64 bits in C#) and your variable is an `int`, then the compiler will perform the necessary implicit conversion for you. In other words, you can simply pass the `int` variable into the method that is expecting a `long` parameter, and it will work without any conversion necessary on your part. The high 32 bits of the `long` will simply be all zeros.
If you need to convert a larger value to a smaller value, you have to perform an *explicit* conversion. The easiest way to determine whether you need to do so, other than memorizing all the conversion rules, is receiving an error from the compiler indicating that it could not perform an implicit conversion. To explicitly convert one data type to another, you can use the `System.Convert` class. This class contains several methods and several overloads of those methods to effectively perform explicit conversions. For example, to convert a `long` variable to an `int`, use the `System.Convert.ToInt32` method, passing the `long` variable as the parameter. Looking at this class, you'll see most of the data conversions you need.
A shorthand way of performing an explicit conversion is through a technique known as *casting*. You perform casting by prefacing the variable you want to convert with the data type to convert to within parenthesis. To cast a `long` to an `int`, you use the following:
```csharp
long l;
int i = (int) l;
```
### 1.10. Performing Relational Operations
You need to perform a relational comparison on two values or objects.
**Technique**
C# relational operators compare the actual values of value types but compare references to objects rather than what those objects contain. The format of a relational operation in C# is `expr1 operator expr2` as in `x == y`. Listing 1.5 demonstrates different relational operations by comparing both value types and objects.
using System;
namespace _10_Relations
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class ComparingRelations
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main(string[] args)
{
// compare 2 values for equality
int a = 12;
int b = 12;
Console.WriteLine( a == b );
Console.WriteLine( (object)a == (object)b );
// compare 2 objects which contains overloaded == operator
string c = "hello";
string d = "hello";
Console.WriteLine( (object) c==(object) d );
// compare 2 objects for equality
ClassCompare x = new ClassCompare();
ClassCompare y;
x.val = 1;
y = x;
Console.WriteLine( x == y );
// changing 1 object also changes the other
x.val = 2;
Console.WriteLine( y.val.ToString() );
}
}
class ClassCompare
{
public int val = 0;
}
}
Comments
Testing relationships between values or objects is an important concept in programming. It provides the foundation for program flow and is used extensively in human/computer interaction. You use relational operations for determining how two values or objects relate to one another to decide what the next step in your program flow will be. Some of these include testing to see whether two values are equal, testing whether one value is greater than another, or testing whether one object is the same as another object, a process known as type-testing.
One key thing you need to keep in mind when creating relational operations is the difference between testing two value types and testing two objects. When you test value types, such as two `int` values, you are testing the value that those two types contain. Compare it to testing two different objects, shown later in the code, in which testing them means you are testing to see whether they are the same objects. In other words, when you are comparing two objects, you are comparing their locations in memory. If they both point to the same location, then they are considered equal. To test this equality, the last test in the code changes the value in one object and the next line prints a member variable in the second object. When you run this code, you’ll notice that even though the variable was changed in one object, the other changed as well because you modified the same memory location that the second one pointed to. Additionally, when creating classes, you might want to overload the `Equals` method so that any comparisons done on your object will compare its internal values rather than the object references.
One particular thing to watch for is a reference type overloading a relational operator. Overloading an operator, discussed later in this chapter, is a technique to change the behavior of a built-in operator so that it makes better sense given the context of the objects you are working with. As an example, code in Listing 1.5 evaluates to `true` even though the two objects being compared are different. The `string` class within the .NET Framework has overloaded the relational operators so that the comparison happens on the internal string rather than the objects themselves. Comparing the strings of two `string` objects makes more sense than comparing two actual `string` objects themselves.
1.11. Using Logical Expressions
You want to evaluate an expression to see whether it is true.
Technique
Use a combination of logical operators on each relational expression you want to test. Logical operations consist of the logical and operator (`&&`), the logical or operator (`||`), and the logical exclusive-or operator (`^`). The following example demonstrates the logical operators as applied to Boolean values:
Chapter 1 Operators, Expressions, and Control Structures
```csharp
static void Main(string[] args)
{
Console.WriteLine("true==true: {0}", (true==true).ToString() );
Console.WriteLine("true==false: {0}", (true==false).ToString() );
Console.WriteLine("false==false: {0}", (false==false).ToString() );
Console.WriteLine("true||true: {0}", (true||true).ToString() );
Console.WriteLine("true||false: {0}", (true||false).ToString() );
Console.WriteLine("false||false: {0}", (false||false).ToString() );
Console.WriteLine("true^true: {0}", (true^true).ToString() );
Console.WriteLine("true^false: {0}", (true^false).ToString() );
Console.WriteLine("false^false: {0}", (false^false).ToString() );
}
```
**Comments**
Logical operations test the results of two or more relational expressions. In the last recipe, you used relational operators to test the relationship of two values or objects with each other. This evaluation results in a Boolean value, `true` or `false`, which you can then act upon in some manner. One action is to compare the results from two or more of these relational expressions by using logical operations.
Logical operations belong to a larger family of operators known as bitwise operators. The term *bitwise* applies because these operators use the actual bits of a value to determine the result. For instance, a Boolean value of `true` is a single bit (at least in theory), which is “turned on” or equals 1. The Boolean value `false` is “turned off” or set to 0. By using this information, you can generate a table to see the result based on the logical or bitwise operator used on these two values, as shown in Table 1.2.
<table>
<thead>
<tr>
<th>Operand 1</th>
<th>Operand 2</th>
<th>Operator</th>
<th>Result</th>
<th>Rule</th>
</tr>
</thead>
<tbody>
<tr>
<td>True</td>
<td>True</td>
<td>&&</td>
<td>True</td>
<td>Both operands must be true.</td>
</tr>
<tr>
<td>True</td>
<td>False</td>
<td>&&</td>
<td>False</td>
<td></td>
</tr>
<tr>
<td>False</td>
<td>True</td>
<td>&&</td>
<td>False</td>
<td></td>
</tr>
<tr>
<td>False</td>
<td>False</td>
<td>&&</td>
<td>false</td>
<td></td>
</tr>
<tr>
<td>True</td>
<td>True</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>True</td>
<td>False</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>False</td>
<td>True</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>False</td>
<td>False</td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td>True</td>
<td>True</td>
<td>^</td>
<td>False</td>
<td>At least one operand is true, but not both.</td>
</tr>
<tr>
<td>True</td>
<td>False</td>
<td>^</td>
<td>True</td>
<td></td>
</tr>
<tr>
<td>False</td>
<td>True</td>
<td>^</td>
<td>True</td>
<td></td>
</tr>
<tr>
<td>False</td>
<td>False</td>
<td>^</td>
<td>False</td>
<td></td>
</tr>
</tbody>
</table>
The logical and, and the logical or operators are also known as short-circuit bitwise operators. If you are using a \texttt{&&} operator, it makes sense that if the first operand is false, there is no need to test the second operand because you know that the logical statement will still evaluate to false. Furthermore, when using the \texttt{||} operator, it makes no sense to test the second operand if the first is already true because that would automatically make the statement true. The exclusive-or operator cannot use any type of short-circuit evaluation because you must test both operands regardless of the value of the first. This difference is why you see two characters for \texttt{&&} and \texttt{||} but only one character for \texttt{^}.
Furthermore, if you want to evaluate both operands and not short-circuit, each operator has a single bitwise operator implementation. However, you generally use these operators for bitwise manipulations of data.
### 1.12. Determining Operator Precedence and Associativity
You want to change the order in which your expression is evaluated by modifying operator precedence.
**Technique**
Our rule of thumb is to parenthesize the expression being evaluated to prevent any possible operator-precedence defects. Determining whether one operator has precedence over another requires understanding all precedence rules for the language you are using.
**Comments**
Operator-precedence rules are one of those things you just have to keep in the back of your head no matter how boring it is. As we said earlier, the rule of thumb is to just use parentheses around certain parts of the expression so that we know the order of evaluation. Parentheses are at the top of the food chain, so to speak, for operator precedence.
Operator precedence isn’t entirely a programming concept. Back in grade-school arithmetic, you learned that multiplication and division is performed from left to right through the expression, followed by addition and subtraction using the result of the multiplication and division expressions as new operands. For instance, the expression $2 + 4 \times 6$ equals 26 because you perform the multiplication first, with a result of 24, followed by the addition of 2. If you want to change the order of this evaluation, use parentheses around the parts of the expression you want to perform first. So if we want to perform the addition followed by the multiplication, we use the expression $(2 + 4) \times 6$ to get a result of 36. Table 1.3 shows the available C# operators and the corresponding precedence and associativity. An operator has precedence over another if it appears higher in the table (closer to the top) than the other. For instance, the $\texttt{==}$ operator has a higher precedence than the $\&$ operator. If both operators appear on the same level, then you must refer to the associativity of those operators. If the associativity is left, then the expression with the operator that appears leftmost in the table is evaluated first.
Table 1.3 C# Operator Precedence and Associativity
<table>
<thead>
<tr>
<th>Operators</th>
<th>Associativity</th>
</tr>
</thead>
<tbody>
<tr>
<td>(x), x, y, f(x), a[x], x++, x--, new, typeof, sizeof, checked, unchecked</td>
<td>Left</td>
</tr>
<tr>
<td>unary +, unary --, ++x, --x, (type)x</td>
<td>Left</td>
</tr>
<tr>
<td>*, /, %</td>
<td>Left</td>
</tr>
<tr>
<td>+, -</td>
<td>Left</td>
</tr>
<tr>
<td><<, >></td>
<td>Left</td>
</tr>
<tr>
<td><, <=, >, >=, is, as</td>
<td>Left</td>
</tr>
<tr>
<td>==, !=</td>
<td>Left</td>
</tr>
<tr>
<td>&</td>
<td>Left</td>
</tr>
<tr>
<td>^</td>
<td>Left</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>&&</td>
<td>Left</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>?: (ternary)</td>
<td>Right</td>
</tr>
<tr>
<td>=, *=, /=, %=, +=, -=, <<=, >>=, &=,</td>
<td>=, ^=</td>
</tr>
</tbody>
</table>
1.13. Using if Statements
You want your application to perform a certain action based on the result of evaluating an expression.
Technique
Using a combination of relational operations on variables, you can execute a body of code if the expression evaluates to true or evaluate a different body of code if not. Use the if/else statement to control program flow.
Comments
One of the most widely used conditional statements is the if/else statement. The format of an if/else statement follows:
```csharp
if( expr )
{
}
else
{
}
```
You read this code as “If expr is true, then perform these actions; else, perform these actions.” In the previous recipe, you used relational operators to compare values and objects with one another. You can then combine the result of these relational expressions using logical expressions. You use the results of these comparisons within the if statement, which is known collectively as a conditional statement.
A shorthand way of creating an if statement is to use a ternary operator. The format of a ternary operator is
```
(conditional)? true_expression : false_expression
```
As an example, if you want to test whether a variable is equal to a certain number, you write the following:
```
Console.Write(( i==42 )? "Meaning of life" : "I don't know");
```
A common technique is to create multiple if statements to further refine the conditional comparisons of variables. For example, the following is perfectly legal and you'll notice that it can perform one of several different actions based on the conditions that are present. Listing 1.6 demonstrates how to create multiple if statements.
Listing 1.6 Creating Multiple if Statements to Control Several Actions
```csharp
namespace _13_IfStatement
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
/// <summary>
/// The main entry point for the application.
/// </summary>
/// <STAThread>
static void Main(string[] args)
{
string input;
Console.Write( "Enter your name: " );
input = Console.ReadLine();
if( input.ToLower() == "jordan" )
{
Console.WriteLine( "{0}, have you cleaned " + "your room yet?", input );
}
else if( (input.ToLower() == "jake") ||
(input.ToLower() == "jonah") )
{
}
```
Chapter 1 Operators, Expressions, and Control Structures
Listing 1.6 Continued
Console.WriteLine( "{0}, clean your room!", input );
}
else if( input.ToLower() == "mallorie" )
{
Console.WriteLine( "{0}, you may do anything you " +
"want.", input );
}
else
{
Console.WriteLine( "Sorry {0}, I don't know you",
input );
}
}
1.14. Using Looping Control Structures
You need to continuously perform a set of actions a certain number of times or
until a certain condition becomes false.
Technique
C# contains several different looping control structures to handle different cases. You use
a for statement if you need to run a loop a set number of times. If you need to execute
a block of statements while an expression remains true, use a while loop. Choose a
do/while statement if you need to execute a block of statements at least once regardless
of any pre-existing conditions and then continuously while an expression remains true.
Comments
In the last recipe, you saw how you can use if statements to execute blocks of code
based on certain conditions. However, you could only execute that block of code one
time. Looping control structures allow you to execute blocks of code several times and
stop either when an expression finally evaluates to false or when you explicitly break out
of the loop somewhere within the body of the loop using the C# keyword break.
Using loops requires care because the conditional statement to test whether the loop
should continue might never become false, which means the program gets stuck in an
endless loop. All three of the looping statements covered here have the possibility of con-
tinuing forever.
You generally use the `for` loop when you want to execute a block of code a certain amount of times. An index variable associated with the loop keeps count of the iterations that have occurred and if you tested it to see whether the loop should finish executing. The `for` statement contains three sections as shown in Listing 1.7. The first part is for initialization. In most cases, you initialize the variable used to control the `for` loop. However, you are free to initialize other variables or even call methods as long as they are separated by commas. The second component of the `for` statement is the conditional expression you want to evaluate. If the expression remains true, the `for` loop body executes. Finally, the last field of the `for` loop is for changing the variables associated with the conditional statement by either incrementing or decrementing the loop counter, for example.
Listing 1.7 Using a `for` Statement to Loop and Calculate the Factorial of a Number
```csharp
static void ComputeFactorial()
{
ulong loopCount = 0;
ulong factorial = 1;
Console.Write( "Enter an integer between 1 and 50: " );
loopCount = UInt64.Parse( Console.ReadLine() );
for( ulong i = loopCount; i > 0; i-- )
{
factorial *= i;
}
Console.WriteLine( "{0}! = {1}", loopCount, factorial );
}
```
The `while` and `do/while` statements are quite similar in that both loop while a certain condition holds true. Once that condition evaluates to false, the loop is exited and the next statement following the loop block is executed. The major difference between the two loop structures is that the `do/while` statement's code block is guaranteed to execute at least once. The `while` statement appears at the end of the code block, as shown in Listing 1.8, instead of at the beginning as with the `while` statement.
Listing 1.8 Using the `do/while` Statement to Control Program Flow
```csharp
static void NumberGuessGame()
{
int guess, number, guesses = 0;
number = new Random((int)DateTime.Now.Ticks).Next( 0, 10 );
do
{
++guesses;
Console.Write( "Enter a number between 1 and 10: " );
guess = Int32.Parse( Console.ReadLine() );
} while( guess != number );
Console.WriteLine( "You took {0} tries to guess the number: {1}" , guesses, number );
}
```
Chapter 1 Operators, Expressions, and Control Structures
Listing 1.8 Continued
if( guess < number )
Console.WriteLine( "Too low. Pick a higher number" );
else if ( guess > number )
Console.WriteLine( "Too high. Pick a lower number" );
} while (guess != number );
Console.WriteLine( "You are correct and it only took you \{0\} guesses!", guesses );
A while statement might never run if the condition is always false during the execution of a program because the condition is evaluated before the code block is entered. If the initial condition is false, then the block is skipped and the program continues after that point. Listing 1.9 shows a while loop being used to create a countdown timer.
Listing 1.9 The while Statement
using System;
namespace _14_Looping
{
class Game
{
[STAThread]
static void Main(string[] args)
{
WaitForNewMinute();
NumberGuessGame();
}
static void WaitForNewMinute()
{
int sec = -1;
Console.Write( "The game will start in " );
while( DateTime.Now.Second != 0 )
{
if( sec != DateTime.Now.Second )
{
sec = DateTime.Now.Second;
Console.Write( "...{0}", 60-DateTime.Now.Second );
}
}
}
}
}
1.15. Breaking Out of a Loop Control Body
You need to repeatedly execute statements in a block but break out of the loop based on a certain event.
**Technique**
There are two ways to break out of a loop statement in the middle of a loop body. The first is by using the `break` keyword. Using it will break out of the loop entirely, and execution will begin at the statement following your loop block. The second way is to use the `continue` keyword, which will cause your application to skip the rest of the loop body but then reevaluate the loop conditional and possibly enter the loop again.
**Comment**
Although the `break` and `continue` keywords are rarely used, sometimes they might prove to be the only alternative. As mentioned earlier, use a `break` statement when you are within the loop body and need to exit the loop entirely. You simply exit the loop, and the program continues execution at the statement following the loop body. An example is a modification of the game in Listing 1.9 in which the loop will exit if the user enters a number that is one less than the randomly generated number.
Listing 1.10 Using the break Keyword to Make the Number-Guessing Game a Little Easier
```csharp
static void NumberGuessGame()
{
int guess, number, guesses = 0;
number = new Random((int)DateTime.Now.Ticks).Next(0, 10);
do
{
++guesses;
Console.Write( "Enter a number between 1 and 10: " );
guess = Int32.Parse( Console.ReadLine() );
if (guess == number) {
Console.WriteLine("You guessed the right number!");
break;
} else if (guess < number) {
Console.WriteLine("The number is higher.");
} else if (guess > number) {
Console.WriteLine("The number is lower.");
}
} while (guesses < 10);
}
```
Listing 1.9 Continued
```csharp
Console.WriteLine();
} } }
```
if( guess-1 == number )
break; // close enough
if( guess < number )
Console.WriteLine( "Too low. Pick a higher number" );
else if ( guess > number )
Console.WriteLine( "Too high. Pick a lower number" );
} while (guess != number );
Console.WriteLine( "You are correct and it only took you "+
"{0} tries!", guesses );
If you want to instead make the game a little harder, you could set a difficulty value and
use the continue keyword to bypass the statements that tell the user whether her guess is
too high or too low. Yes, using an if statement for these cases seems like a more logical
choice, which is a reason why we said the break and continue statements are rarely used.
|
{"Source-Url": "http://ptgmedia.pearsoncmg.com/imprint_downloads/informit/sams/0672325802_CH01.PDF", "len_cl100k_base": 11150, "olmocr-version": "0.1.53", "pdf-total-pages": 26, "total-fallback-pages": 0, "total-input-tokens": 53563, "total-output-tokens": 12256, "length": "2e13", "weborganizer": {"__label__adult": 0.0003437995910644531, "__label__art_design": 0.0002493858337402344, "__label__crime_law": 0.00016498565673828125, "__label__education_jobs": 0.00044655799865722656, "__label__entertainment": 5.328655242919922e-05, "__label__fashion_beauty": 0.00011754035949707033, "__label__finance_business": 9.369850158691406e-05, "__label__food_dining": 0.00029349327087402344, "__label__games": 0.0008330345153808594, "__label__hardware": 0.000736236572265625, "__label__health": 0.00018918514251708984, "__label__history": 0.0001329183578491211, "__label__home_hobbies": 7.861852645874023e-05, "__label__industrial": 0.00021767616271972656, "__label__literature": 0.00016415119171142578, "__label__politics": 0.00013589859008789062, "__label__religion": 0.0003638267517089844, "__label__science_tech": 0.0014009475708007812, "__label__social_life": 5.4717063903808594e-05, "__label__software": 0.0037841796875, "__label__software_dev": 0.9892578125, "__label__sports_fitness": 0.0002675056457519531, "__label__transportation": 0.0003528594970703125, "__label__travel": 0.00018787384033203125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 48556, 0.01483]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 48556, 0.67757]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 48556, 0.87397]], "google_gemma-3-12b-it_contains_pii": [[0, 1882, false], [1882, 3391, null], [3391, 6086, null], [6086, 7409, null], [7409, 9496, null], [9496, 10779, null], [10779, 12777, null], [12777, 15659, null], [15659, 16882, null], [16882, 19378, null], [19378, 21881, null], [21881, 22865, null], [22865, 23487, null], [23487, 25339, null], [25339, 28004, null], [28004, 29110, null], [29110, 31921, null], [31921, 34546, null], [34546, 37570, null], [37570, 38601, null], [38601, 40502, null], [40502, 42243, null], [42243, 44583, null], [44583, 45956, null], [45956, 47864, null], [47864, 48556, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1882, true], [1882, 3391, null], [3391, 6086, null], [6086, 7409, null], [7409, 9496, null], [9496, 10779, null], [10779, 12777, null], [12777, 15659, null], [15659, 16882, null], [16882, 19378, null], [19378, 21881, null], [21881, 22865, null], [22865, 23487, null], [23487, 25339, null], [25339, 28004, null], [28004, 29110, null], [29110, 31921, null], [31921, 34546, null], [34546, 37570, null], [37570, 38601, null], [38601, 40502, null], [40502, 42243, null], [42243, 44583, null], [44583, 45956, null], [45956, 47864, null], [47864, 48556, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 48556, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 48556, null]], "pdf_page_numbers": [[0, 1882, 1], [1882, 3391, 2], [3391, 6086, 3], [6086, 7409, 4], [7409, 9496, 5], [9496, 10779, 6], [10779, 12777, 7], [12777, 15659, 8], [15659, 16882, 9], [16882, 19378, 10], [19378, 21881, 11], [21881, 22865, 12], [22865, 23487, 13], [23487, 25339, 14], [25339, 28004, 15], [28004, 29110, 16], [29110, 31921, 17], [31921, 34546, 18], [34546, 37570, 19], [37570, 38601, 20], [38601, 40502, 21], [40502, 42243, 22], [42243, 44583, 23], [44583, 45956, 24], [45956, 47864, 25], [47864, 48556, 26]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 48556, 0.06868]]}
|
olmocr_science_pdfs
|
2024-12-11
|
2024-12-11
|
526c933aa15f17fd1ed8c37967b6f14937ce45cc
|
A Concept Map based Teaching of Compiler Design for Undergraduate Students
Venkatesan Subramanian 1,*, Kalaivany Karthikeyan2, Pallapa Venkataram3
1Department of Information Technology, Indian Institute of Information Technology, Allahabad, India.
2Independent Researcher, Australia.
3Department of Electrical Communication Engineering, Indian Institute of Science, Bangalore, India.
Abstract
In undergraduate engineering, most of the subjects do not have the open visibility of the Industry and Research requirements. Students are interested mostly on subjects which are useful for Industry placement. They do not show interest in non-open visibility subjects if an instructor teaches by simply following the textbook. Considering this, we presented a concept map based teaching methodology with Research and Industry assignments and problems. The proposed methodology focus on improving the teaching quality and students understanding level. In this paper, we have taken the Compiler Design subject and presented the concept map. To understand the effectiveness of the proposed methodology, the students feedback was collected and evaluated using the sign-test and the students’ submitted problems and assignments were evaluated to understand their level. The analysis results show that most of students studied Compiler Design with interest as a result of proposed teaching methodology.
Received on 21 September 2022; accepted on 24 July 2022; published on 17 August 2022
Keywords: Compiler Design, Concept Map, Computer Science education, Teaching
Copyright © 2022 Venkatesan et al., licensed to EAI. This is an open access article distributed under the terms of the Creative Commons Attribution license (http://creativecommons.org/licenses/by/3.0/), which permits unlimited use, distribution and reproduction in any medium so long as the original work is properly cited.
doi:10.4108/eetel.v8i1.2550
1. Introduction
The Industry professionals and the Academicians claim that most of undergraduate engineering students are not having required potential for hiring. The major reason behind such criticism is that while studying the course, students do not show interest in the subjects, thus affect their understanding of the subject in depth and they were not motivated to show interest in the subjects. Also, M. J. De Vries and J. H. M. Stroeken [1] found that engineering students are lacking in research skills (the abilities to define the research problem, comment upon research methodology, and reflect upon research outcomes). This varies from one subject to another subject. To understand the students’ thoughts about different subjects, a survey was conducted with the three questions.
- What are the subjects you are interested in?
- What are the subjects you feel are required for Industry placement?
- What are the subjects you feel are required for Research?
The third-year undergraduate engineering students (number of students participated in the survey is 92) participated in the survey and given their opinion. The survey results in percentage are shown in Table 1 for few subjects of undergraduate computer science and engineering. The same survey was repeated with the next batch of third year engineering undergraduate students (number of student participated in the survey: 99) with a following additional question.
- If the listed subjects are not given in a core list but offered as elective, then what are the subjects will you prefer to study.
The survey result in percentage is shown in Table 2. It is very clear from the survey results that students are not having enough interest on some subjects as well as not aware of its need in Industry and Research. Hence,
it is necessary to encourage and motivate students toward these subjects also by changing the teaching methodology, which should be in a high degree of quality. The concept map [2] [3] based teaching would be more appropriate for the purpose as C. Chiou et al. [4] presented its effectiveness.
In this paper, Compiler Design subject is concentrated since students feel this is a complex and very less productive. The students’ opinion in Table 1 and 2 clearly shows that the students have a negative notion about the Compiler Design subject. Hence, Instructor need to beat this notion by re-designing the teaching methodology of Compiler Design and motivating students towards the subject.
1.1. Research Questions
While teaching, an instructor plays a significant role in motivating and making students to understand the subject. This can be achieved if an instructor have solutions to the following questions.
• Question 1: What innovative technique should be introduced to beat the students’ negative notions of various subjects? - Most of the students in the class are not interested in the subjects that are not directly visible as a requirement for industry and research demand. This can be witnessed from the Table 1 and 2. The Instructor needs to follow an innovative strategy to beat the notion.
• Question 2: How do instructor make students self-design the problem and assignments for a concept of a subject? - The students in a subject understand the concept when the Instructor teaches it or later in a few cases. Also they can solve the problem given in the textbook. In case the problem is tricky, then they are unable to solve it. The instructor can overcome this issue by asking the students to design problems and assignments independently. For example, Ana et al. [5] proposed a module using concept map to support self-regulated learning by undergraduate engineering students. Each student are linked to the concept map to record all topics that are covered and the ones that are pending. The Instructor examines the concept maps of all students for further improvement. However, the issue is what will encourage the students to do it?
• Question 3: What factor is required to make the students in the classroom to be attentive? - In most of cases, the students are not attentive in the classroom due to various factors such as teaching methodology, complex topics, smart gadgets, next guy nuisance, etc. In a classroom of more than 50 students, the instructors may not be in a position to monitor all students. Even if the instructor forces or threatens the students to listen to the teaching, it will be a physical presence but mental absence which is non productive. Hence a novel teaching technique is required to make the students be attentive in the classroom.
The significance of the above questions are to achieve the long-lasting remembrance of the subjects, properly utilize the learned concepts in real time on demand, and most importantly, make the full-fledged graduate. Considering the significance of the questions, benefits of concept map and students opinion, the novel teaching methodology is introduced with an evaluation technique to provide solutions to the research questions. The methodology has been
experienced while teaching the Compiler Design subject for Undergraduate engineering students.
1.2. Contribution
The contributions of the paper to improve the teaching quality and understanding level of students are
1. A novel teaching methodology based on the concept map, directed concept graph, and concept relation weight.
2. Linked each concept with the present and future Industry and Research related problems and assignments.
3. Developed the broad and extended concept map of Compiler Design.
The rest of the paper is structured as follows: Section 2 discusses the existing works, Section 3 discusses the proposed teaching research methodology, section 4 discusses the broad and extended concept map of the Compiler Design subject. Section 5 presents the evaluation of the proposed methodology and section 6 proves the significance of the proposed teaching methodology and discusses the limitation. Finally, Section 7 concludes the paper with the directions of future work.
2. Related works
In literature, different approaches were proposed to encourage and motivate the students to concentrate on Compiler Design subject and its concepts. Here, we discuss the existing works in two categories: The Teaching style of the compiler design course and its concepts.
J. Velásquez [18] developed a tool called bcc: mini-language to cover the complete syllabus in a semester. The bcc supports to execute different phases of the compiler. K. Abe [19] developed an integrated laboratory that deals with processor organization, compiler design, and computer networking. The students are encouraged to integrate these components to construct a complete small computer system. J. Velásquez [20] also described exposing students to the practical application of compiler construction techniques and encouraging the development of programming and problem-solving skills. In addition, the author discussed the implementation of a scheme for the automatic assessment using the Virtual Programming Lab. S. B. Nolen and M. D. Koretsky [21] discussed the physical projects to actively engage students in a subject. M. Frank et al. [22] analysed and recommended teaching technology and engineering by means of Project Based learning can train students better for their future profession. J. Óñel Velázquez-Iturride et al. [23] analyzed and identified that the student motivation increase through software visualization. I. Estévez-Ayres et al. [24] proposed a methodology for improving active learning through regular feedback and iterative refinement.
F. Ortin et al. [25] shows how object-oriented design patterns represented in unified modeling language (UML) can be used to teach type checking and develop the semantic analysis phase of a compiler. S. Sangal et al. [26] proposed a Parsing Algorithms Visualization Tool (PAVT) to teach the process of parsing algorithms. Learners can visualise the intermediate steps of the parsing algorithm through the tool. R. D. Resler and D. M. Deaver [27] introduced the Visible Compiler Compiler (VCOCO) to make the students visualize a compiler’s internal working. The VCOCO is flexible and effective tool for generating user-specific LL(1) visible compilers. A. Karkare and N. Agrawal [28] developed ParseIT tool for teaching parsing.
The game based, experiment based, project based like teaching computer architecture by D. Cenk Erdil [29], case based, feedback based and tool based teaching makes learning easy and interesting. However, concepts and its relationship along with assignments and problems related to Research and Industry requirement
should be discussed for motivation and long-lasting remembrance thus provides solutions to the research questions. Hence this paper propose a novel teaching methodology based on concept map which will simplify the teaching, make students to understand the subject and get motivated.
3. Research Methodology
This section discusses the proposed novel teaching research methodology and its evaluation technique to answer the teaching research questions to improve the quality of teaching and understanding.
3.1. Methodology
The concept map based teaching and relating the concepts with Research and Industry demand is the right method to address the above research questions since students are interested in Industry which was witnessed through the survey outcome. Considering this, a systematic teaching methodology is introduced to teach a subject.
Basics for Quality Teaching. For efficient and qualitative teaching, a teacher/instructor shall follow the research questions and plan the subject’s teaching material, assignments and problems. This paper improves the quality of teaching by the teacher by constructing the concept map and directed graph of the subject, which gives a teacher to systematically follow the relation of concepts and order to teach with examples. Also, to evaluate the students’ understanding and improve their understanding level, students needs to self-design the problems and assignments. Accordingly, the following two teaching experiments are designed.
Teaching quality improvement The systematic approach of teaching is to identify, order and deliver the concepts. While teaching, each concepts should be discussed along with practical Industry and Research usage. Also, the relevant assignments and problems of a concept to be discussed before taking up the next concept in the order or queue. It is necessary to make the queue and follow it so that students will not miss the significance of any concepts and their relational concepts. The Directed Concept Graph ($G = (N, E)$, the set of $N$ nodes and $E$ edges) is one of the best techniques to order the concepts of a subject. The nodes $N$ are the concepts, and edges $E$ are the concepts’ relations. The Figure 1 shows the Directed Concept Graph (DCG) with five concepts notation $C_a$, $C_b$, $C_c$, $C_d$ and $C_e$, which can be mapped with compiler concepts.
The Lemma 1 proves the need for DCG to order the concepts of a subject and discuss them in the class, thus improving the teaching quality.

**Figure 1. Directed Concept Graph**
Postulate 1. A concept’s pre-requisite concept will have the significant influence on understanding it.
Postulate 2. A source node (concept) $C_a$, is the prerequisite for the destination node (concept) $C_b$, if the directed relationship is from $C_a \rightarrow C_b$
Postulate 3. A concept should be discussed only after its pre-requisite concepts are discussed with relevant problems and assignments.
Lemma 1. The concept queue get ordered concepts if the DCG followed.
*Proof.* Given postulate 1, 2 and 3, the precedence of concept $C_a$ is more than concept $C_b$ ($C_a > C_b$), if the $C_b$ has directed edge from the $C_a$. Therefore, the $C_a$ comes before $C_b$ in the concept’s queue. Hence the queue will have ordered concepts.
The directed edge is insufficient to order the concepts when a concept has more than one outdegree. For example, $C_a$ has directed edge (two outdegrees) to $C_b$ and $C_c$. The next concept to $C_a$ in the order is non-deterministic. To overcome the non-determinism, the relation weight among concepts is introduced. An each concept of a subject will be given weight based on the importance in three categories; teaching (use in other subjects), industry and research. The qualitative weight under each category is classified into low, medium and high with a quantity of 1, 2 and 3 respectively. A concept’s overall or total weight is the summation of weights of all three categories. The weights for some concepts of the Compiler Design is given in Table 3. The weights are assigned based on the Instructors’ experience in teaching, preparation and evaluation of the Industry and Research problems and assignments.
Using the concept weights, the relation weight can be assigned. For example, the relation weight of $C_a \rightarrow C_b$ is sum of weight of $C_a$ and $C_b$. The relation weight can be used to decide the next concept to be placed in the order.
**What will be the loss if the instructor miss a concept?** A concept missed while teaching a subject will greatly impact on understanding the related concepts. For
Table 3. Concept Weight
<table>
<thead>
<tr>
<th>Concept</th>
<th>Teaching</th>
<th>Industry</th>
<th>Research</th>
<th>Sum</th>
</tr>
</thead>
<tbody>
<tr>
<td>Regular Expression</td>
<td>3</td>
<td>3</td>
<td>3</td>
<td>9</td>
</tr>
<tr>
<td>Optimization</td>
<td>3</td>
<td>3</td>
<td>3</td>
<td>9</td>
</tr>
<tr>
<td>Attribute Grammar</td>
<td>2</td>
<td>1</td>
<td>2</td>
<td>5</td>
</tr>
<tr>
<td>Finite State Machine</td>
<td>3</td>
<td>3</td>
<td>3</td>
<td>9</td>
</tr>
<tr>
<td>Left Factoring</td>
<td>1</td>
<td>1</td>
<td>1</td>
<td>3</td>
</tr>
<tr>
<td>Three Address Code</td>
<td>2</td>
<td>2</td>
<td>2</td>
<td>6</td>
</tr>
</tbody>
</table>
example, an instructor teaching LR parsing to the students should teach the item set construction, parsing table construction and parsing in order. Lets assume the Instructor miss the item set and parsing table construction but teaches parsing to the students. In this case, students will keep on thinking about how the table was constructed and what are its input. This forces students on the dark side, thus, loose interest in the concept and eventually loose interest in the subject.
What will be the loss if the Instructor does not follow the order?: A concept will significantly influence understanding the other concepts. In case, the concept $C_a$, which should be discussed before concept $C_b$ is missed or discussed later, then the student will not be able to understand $C_b$. For example, lets map the DCG of Figure 1 with the lexical analyser phase concepts of Compiler Design. The $C_a$ is the Tokenization, $C_b$ is the Finite State Machine, $C_c$ is the Regular Expression, and $C_e$ is the Table Driven LA. Assume, the instructor teaches $C_a$, $C_b$, $C_c$ in order but the $C_e$ later. In this case, students will not be in position to understand the source of $C_e$ while it is discussed thus degrade the teaching quality. This supports the need to order concepts using DCG and relation weight to improve the teaching quality.
Improving understanding level of students: In addition to the concept map and order-based teaching, the pyramid structure, as shown in Figure 2 can be followed while teaching each concept. An idea is to give the definition, practical working model, how it was and is used and what would be its future. The structure shows the contents of a concept to be discussed and the time frame for each content. The time frame is proportional to spread of the pyramid. The discussion of lexical analyzer concept based on the pyramid shown in Figure 2 is as follows.
Firstly, the concept was defined then its working model along with text book based examples were discussed. Later, use of the concept in an other concepts or subjects was discussed. At the end, the research and industry oriented examples of the concept were discussed by the Instructors. Finally, students were invited for the discussion to describe the future need of the concept in Industry as well as in the research domain. The student must take up the concept only when its pre-requisite concepts are clear.
Need of pre-requisite concept understanding: If a student does not have 100% understanding of $C_c$ of Figure 1 then cannot solve the problem of $C_d$. For example, a student not having clear understanding of first and follow construction cannot solve the example problem or prepare the sample assignment or problem for the item set/parsing table construction. Hence, understanding the pre-requisite concepts by the students is very essential and instructor needs to guide them.
To understand the concept very clearly, the students should be asked to self-design Industry, and Research problems for each concepts based on the Instructor discussed Industry and Research examples. A student with sufficient knowledge on the concept can prepare the relevant industry and research assignments and problems. The instructors can understand students’ level of understanding while evaluating their assignments and problems accordingly, which can guide them to understand the concept in depth. This will make the students think innovative and attentive in the classroom. Also,
this method will encourage the students towards the subject since they visualize and realize the use of a concept in Industry and Research domain. Hence, this method improves the understanding level of students.
**Building Concept Map.** The subject overview can be presented using a concept map to encourage students toward a subject. In the experiment, the Compiler Design concept map was built and discussed in the class. The process of making the broad concept map is presented in the Algorithm 1. As a part of building the concept map, each concept must be linked with other concepts if there is an association/relation, as discussed in the Directed Concept Graph. The associations/relationships are has, includes, creates, etc. The extended concept map was built for each phase of compiler based on the concepts of broad concept map and added supplementary such as what it is?, How does it works?, Objective, Implementation, Approaches and added supplementary such as what it is?, How does it works?, Objective, Implementation, Approaches etc. To differentiate the concepts and supplementary, separate representation was used. The red color border rectangle is used for supplementary in the extended concept map of Compiler Design discussed in section 4.2.
**Algorithm 1 Building Broad Concept Map**
```plaintext
Require: List of Concepts $C \subset \{c_1, c_2, c_3..c_n\}$
Ensure: Concept Map $CM$
1: for $c_i$ in $C$ do
2: Design a simple example for $c_i$ based on text book
3: if $c_i$ is the major concept with weight $\geq 1$ in Industry and Research then
4: Identify the Research and Industry related assignments
5: end if
6: for $c_i \{c_1, c_2, c_3..c_n\}$ in $C$ do
7: if $c_i$ has relationship with $c_j$ then
8: Identify the concept map relationship $R \subset \{has, includes, creates, can be,\ldots\}$
9: Build the relationship $R : c_j \rightarrow c_i$
10: end if
11: end for
12: end for
13: return $CM$
```
3.2. Evaluation Technique
The proposed methodology can be evaluated in two ways: the first is the evaluation of the proposed teaching methodology and second is the evaluation of students’ self-designed assignments and problems.
**Methodology Evaluation.** The proposed teaching methodology can be evaluated using the students’ feedback survey. The survey can be conducted at beginning and at the end of the course with the same set of students and questions. The course should be taught using the proposed teaching methodology. The survey questions to be prepared to understand the students’ mind set about a subject and the response to be dichotomous, that is yes or no. In section 1, the necessary survey questions are presented to understand the students, mindset about a subject. The outcome of the survey results can be evaluated using the non-parametric sign test [30] to prove the significance of the proposed methodology. The *sign test* uses the binomial distribution with the cumulative distribution function given in equation 1.
$$F(k, n, p) = Pr(X \leq k) = \sum_{i=0}^{k} \binom{n}{i} p^i (1-p)^{n-i}$$ \hspace{1cm} (1)
The *sign test* is most useful if comparisons can be expressed as $x > y$, $x = y$ and $x < y$ [31], where $x$ and $y$ are the survey outcome before and after the event respectively. This fits the proposed methodology evaluation. Here, the event refers to the proposed teaching methodology. The possible outcome from the survey results $x$ and $y$ that can be used for *sign test* are as follows
- If the survey outcome $y$ of a student has more answers as yes then record a ‘+’ (positive for the proposed teaching methodology), where $x < y$.
- If the survey outcome $x$ of a student has more answers as yes then record a ‘−’ (negative for the proposed teaching methodology), where $x > y$.
- If a student’s number of yes answers has not changed then record a ‘0’ (neutral), where $x = y$.
- If a student’s number of no answers has not changed, then record a ‘−’ (negative for the proposed teaching methodology), where $−x = −y$.
To compute the binomial probability ($bp$) for *sign test*, $n$, total count that is number of ‘+’ and ‘−’ excluding ‘0’, $k$, number of ‘−’ that is against the proposed methodology and $p$, initial non biased probability value 0.5 are required. The two-tailed *sign test* is required since not sure whether yes answers would increase or decrease after the event. The hypotheses for the test are as follows.
- The null hypothesis $H_0$: The proposed teaching methodology does not have any effect or a negative effect on the students.
- The alternate hypothesis $H_1$: The proposed methodology has the positive effect on the students, and they are motivated.
Student Assignment Evaluation. The students submitted self-designed assignments and problems can be evaluated by Instructors according to the concept in the concept map and categorize into relative/non-relative or strong/weak. This helps the Instructors understand student’s understanding level and their involvement. The non-relative or weak assignment submitted students could be asked to prepare the new set of assignments. Instructors can provide support in preparing the assignments by giving more examples.
Syntax Analysis. Syntax Analysis takes the input as tokens from the lexical phase and produces the syntax tree, which the semantic phase will use. The major task of the syntax analyzer is to check whether the syntax presents in the program is part of the programming language or not. To do this check, Syntax Analyzer uses parser with Finite State Machine, Push down Automata, Context Free and Sensitive Grammar. Parser can be top down or bottom up approach and it will be chosen based on the developer’s requirement. The LL (Left-to-right, Leftmost derivation) and LR (Left-to-right, Rightmost derivation) parsers work well only when a grammar is unambiguous and parse in linear time. For LL parser, an unambiguous, deterministic and non-left recursive grammar will be given as input and compute the first and follow. Using the first and follow, the parsing table will be constructed to do parsing. In the case of the LR parser, the finite state machine based item set and parsing table for the unambiguous grammar will be constructed to do parsing. Instructor also needs to briefly discuss about the universal parsers like Earley’s and CYK, which can take any type of grammar and parse however the complexity will not be linear. The tool Yacc can be briefly introduced. In Compiler Design course teaching, at least 25% to 35% of time in the semester will be spent on the syntax analysis phase.
Semantic Analysis. It takes the parse tree as input from the syntax analyzer and checks the semantics of the program such as type checking, parameter matching, label check, etc. This phase uses the attribute grammar or direct method to verify the semantics. The concepts in the semantic analyser are the Symbol Table, Attribute Grammars, Semantic check, Syntax Directed Translation and Definition. Attribute grammars can be represented using the Syntax Directed Translation (SDT) or Syntax Directed Definition (SDD) with Left to Right L- or Synthesized S-Attributed and use Dependency Graph at the time of evaluation to maintain the order. The semantic analyzer utilizes the symbol table to check the semantics of the program. There are high level programming languages do not have the attribute grammars for semantic check and it uses the symbol table.
Intermediate Code Generation (ICG). It takes the input as syntax tree from the semantic phase and provides the Intermediate Representation (IR). The IR can be structural, linear and hybrid. In most of the programming languages, linear representation is used further three address code is mostly preferred with storage representations such as quadruple, triple and indirect triple. It also uses the Single Static Assignment (SSA) for better register allocation. This phase also uses the SDT in some languages to convert the syntax tree representation into three address code.
4. COMPILER DESIGN CONCEPT MAP
The students studied or studying Compiler Design course should know the overview and understand how the compiler is designed, and the high-level program is getting translated for execution. The compiler design concept map [32] in Figure 3 provides the complete overview and relationship among the concepts to encourage the students to focus on the subject. The concept map includes the pre-processor and pre-requisites for this subject. The prerequisites are instruction set, Context Free Grammar (CFG) and Context Sensitive Grammar (CSG), Regular Expression (RE), Finite State Machine (FSM) and Push Down Automata (PDA). This makes students understand the importance of Theory of Computation (ToC) subject since they studied RE, FSM, PDA and CFG/CSG there. Hence, the proposed concept map motivates the students toward Compiler Design and Theory of Computation subject. However, no advantage concerning ToC since students already studied the subject, but this can impact junior students because senior students will convey the importance of ToC/Automata to juniors.
4.1. Phases of Compiler
In this paper, machine independent optimization is included in the code optimization phase and machine dependent optimization in the code generation and optimization phase.
Lexical Analysis. The important concepts to be discussed in lexical analysis phase are Tokenization, Finite State Machine, Regular Expression. In addition, buffering and Symbol Table and obviously how these concepts are interlinked to generate the tokens. Even though, students studied regular expression and finite state machine in the pre-requisite subject ToC, the concepts need to be revised with programming language patterns example. In the classroom, instructor may take the hello world C language program as input and recognize the tokens using single and double buffering to better understand lexical analyser. The tools Flex, and lolo need to be briefly introduced and practiced in the laboratory.
Code Optimization. This phase helps in optimizing the time and space complexity of the program while execution however semantics of the program should be preserved. The Code optimization can be done locally, globally or inter-procedural level and can also be machine dependent or independent. In the classroom, Instructor has to show one example for each optimization concept to make the concepts clear to students.
Code Generation. Code Generation is the final phase of the compiler that takes optimized code and generates target code. Target code may be another High level language code or Assembly level language code. To generate the assembly level, it is important to consider the Instruction Set, Register Allocation and Instruction Scheduling. Instruction set will be based on Reduced Instruction Set Computer (RISC) or Complex Instruction Set Computer (CISC) or Micro-op (mix of CISC and RISC). Since CISC architecture is used in popular Intel processors, CISC instruction set can be taken for solving the example in classroom. However, students may be asked to generate the target code for different architectures.
4.2. Extended Concept Map
The Instructor introduced the broad concept map at the first level then for each concept, the concept map is extended further till it makes the students to understand easily and solve the problems and assignments. The extended concept map also encourages the enthusiastic student to design their problems and assignment regarding Industry application and Research. This section, presents the extended concept map of Compiler Design phases.
Lexical Analysis. The Figure 4 shows the extended concept map of lexical analyser [33][34]. The Industry and Research example for the core concepts in the extended concept map are as follows.
- **1I**: Use the regular expression for medical industry to identify the external analytic vendor that is different from the approved list.
- **1R**: Use text manipulation (update, delete, search) in the text file database using the regular expression [35]. In this case, flat files may play a useful role as a database. The extensive facilities provided by the databases such as MySQL, Oracle, SQL server, etc. are not required and free the users from the additional work of database software installation, knowing a query language etc.
- **2I**: Finite State Machine (FSM) can be used to execute sequence of tests for flow measurement testing. This solution can be applied to automate other serial, and batch processes [36].
Figure 4. Concepts of Lexical Analyzer
• 2R: Design a process flow for managing enterprise documents and identify all possible states that a document can be in; and identify the corresponding actions that allow the documents transition between states. Software usually allows auto-deleting documents once they have been in a final state for a given number of days, months or years. This is useful for compliance scenarios in which some documents must be kept, archived and later deleted following strict rules following legal requirements [37].
• 3I & 6I: An object-oriented lexical analyzer for the compiler construction can simplify the design effort, and it permits code re-use [38].
• 3R & 6R: An industry that handles big data and needs analysis can use the object-based scanner to recognize.
• 4I: The state oriented lexical analyzer can be designed to detect the SQL injection attack in a database [39].
• 4R: Use the state oriented lexical analyzer for sentimental analysis of entertainment industry for prediction of movies. Identify the states and transition for the prediction of the movie [40].
• 5I: Design the table-driven lexical analyzer tool to identify the patterns of a Go language.
• 5R: Design the table-driven Lexical analyzer to analyse the log file of an online product selling Industry.
• 7I: Design the handwritten scanner using the state oriented/table driven/object-oriented lexical analyser to extract the useful information from an email message to categorize the emails.
• 7R: Design the handwritten tokenizer using the state-oriented, table-driven or object-oriented lexical analyser to analyse natural language data.
• 8I: Design the automated tokenization tool for an online product selling Industry that can be reused for the cyber security industry that needs to scan the packets datagram to identify the attack if any.
• 8R: Design the automated lexical analysis tool for sentiment, social cognition, and social-order analysis [41].
Other phases of compiler. The Figure 5 to 9 respectively shows the extended concept map of Syntax Analyzer, Semantic Analyzer, Intermediate Code Generation, Code Optimization and Code Generation phase. The Industry and Research example for the core concepts need to be discussed in the class when the respective concept is taught to the students. This will motivate students to study Compiler Design subjects with interest.
5. Evaluation
The proposed concept map, directed concept graph and concept relation weight based teaching methodology was implemented/experimented with while teaching Compiler Design course and evaluated its significance through students’ self-designed problems, assignments and feedback.
5.1. Students Feedback
To validate the proposed teaching methodology, the students’ opinion about the Compiler design subject was collected at the end of the course through anonymous survey using the same three questions discussed in section 1. The number of students from the Batch - I (2019) who participated in the survey is 60. The outcome is shown in Figure 10, which also includes the survey outcome of the Batch - I (2019) students at the beginning of the course. The difference in the survey outcome indicates that the students’ mindset about the Compiler Design subject is changed positively, and that the proposed teaching methodology influenced students. It is very clear from the post-event outcome that students are largely interested in the subject, and they realized that the subject’s requirement in research is more, however, they found the subject’s requirement in the Industry is less. To overcome this issue, instructors needs to discuss more assignments and problems from the industry domain.
Students feedback reliability justification. In general, students always feel that the course is about to be completed and the grade will be generated so accordingly let us answer the survey questions to gain higher grades. This way of answering will give a better results for the proposed teaching methodology but it will not be fact (authentic) and the whole experiment is useless. But in the survey, the results seems authentic since students’ view of placement are reduced at the same time, it is massively increased in interest and research. Hence, the students’ feedback is not biased considering grades.
Sign Test. To test the significance of the proposed teaching methodology, the survey outcome is applied to the sign test. The survey taken was anonymous so mapping the pre and post-event outcome with a participant is impossible. Hence, random mapping was used to perform the test. Also, the participants in the beginning (pre-event) are 92 and at the end (post-event) are 60 so randomly, 32 participants’ feedback are removed from the pre-event survey list. The survey at the beginning (x) and the end (y) had same three
A Concept Map based Teaching of Compiler Design for Undergraduate Students
Figure 5. Concepts of Syntax Analyzer
- **Syntax Analyzer**
- What it is? Parser
- Objectives – a) Check input is part of the language, b) Build parse tree or similar representation and c) Report errors
- How does it work?
- Parsing
- Top Down
- Recursive Descent Parsing
- Predictive Parsing
- LL Parsing
- Left Recursion
- Left Factoring
- Predictive Parsing Table
- Universal Parsing - Earley
- First & Follow
- Bottom Up
- Shift Reduce Parsing
- LR Parsing
- LR Automaton
- Parsing Table
- Universal Parsing - CYK
- Industry Example: 2I
- Research Example: 2R
- Industry Example: 1I
- Research Example: 1R
- It uses
- Context Free Grammar
- Finite State Automata
- Industry Example: 3I
- Research Example: 3R
- Push Down Automata
- Industry Example: 4I
- Research Example: 4R
- Parse Tree
- Industry Example: 5I
- Research Example: 5R
- Error Recovery
- Industry Example: 6I
- Research Example: 6R
questions and equivalent students' answers. The sign test attribute discussed in section 3.2 and its values along with computed cumulative binomial probability \( bp \) and two-tailed test value are given in Table 4.
It can be concluded from the results in Table 4 that the proposed teaching methodology had a positive effect on the students since the two-tailed binomial probability value \( bp \) is less than significance level 0.05. Hence the null hypothesis \( H_0 \) is rejected, and the alternate hypothesis \( H_a \) is accepted. The proposed teaching methodology changed the students' negative notion about the subject towards the positive side. That is, students understand the need of the subject concerning to Industry and Research requirements, shown interest and get motivated.
5.2. Students Assignment
As a part of an evaluation and experiment, students were asked to form a five member team and prepare assignments on each core concept of the compiler with respect to both Industry and Research. Marks were awarded while grading to motivate the students to actively participate in the assignment preparation. The instructors evaluated students’ submitted assignments according to relevance with the concept. Table 5 shows the Batch - I (2019) assignment evaluation results in percentage with respect to the relevancy of assignments with the concept. The results shows that for few concepts students’ team prepared the relevant assignments, and for other concepts, they are weak. For example, only 45% and 50% of students teams are able to self design the Industry and Research assignments, respectively for the Lexical Analyzer phase concepts. Hence, the Instructor have to identify few more example assignments on these concepts and discuss in the class to improve the students understanding level. These results helps Instructor to identify the level of students and their understanding of concepts accordingly guide them to understand the concept clearly and self design the relevant industry and research assignments.
6. Proof and Limitation
The Lemmas are proposed to prove the impact of the proposed teaching methodology among students. The

A Concept Map based Teaching of Compiler Design for Undergraduate Students
Figure 7. Concepts of Intermediate Code Generation
Table 4. Sign Test Results
<table>
<thead>
<tr>
<th>Attributes</th>
<th>+</th>
<th>-</th>
<th>0</th>
<th>n</th>
<th>k</th>
<th>bp</th>
<th>Two-tailed</th>
</tr>
</thead>
<tbody>
<tr>
<td>Values</td>
<td>36</td>
<td>16</td>
<td>8</td>
<td>52</td>
<td>16</td>
<td>0.00389</td>
<td>0.00779</td>
</tr>
</tbody>
</table>
Table 5. Compiler Design Assignment Evaluation Results
<table>
<thead>
<tr>
<th>Concept-Phase</th>
<th>Industry</th>
<th>Research</th>
</tr>
</thead>
<tbody>
<tr>
<td>Lexical Analyser</td>
<td>45%</td>
<td>50%</td>
</tr>
<tr>
<td>Syntax Analyser</td>
<td>65%</td>
<td>55%</td>
</tr>
<tr>
<td>Semantic Analyser</td>
<td>80%</td>
<td>80%</td>
</tr>
<tr>
<td>Intermediate Code Gen.</td>
<td>65%</td>
<td>50%</td>
</tr>
<tr>
<td>Code Optimization</td>
<td>70%</td>
<td>65%</td>
</tr>
<tr>
<td>Code Generation</td>
<td>65%</td>
<td>65%</td>
</tr>
</tbody>
</table>
notations considered to prove the Lemma are given in Table 6.
In any subject, a class can have $N$ number of students with different categories. The first category of students studies the subject just to pass and get a degree. The second category of students concentrates only on the subjects which help in industry placement, and consider other subjects are just to complete the degree. The third category of students interested in doing research will concentrate on subjects they feel are required for Research. The fourth category of students focuses on all subjects and studies thoroughly. The fourth category of students are the outliers ($P$), who do not need any motivation, but the other three categories need motivation and different teaching methodology. Hence, only two categories (one needs motivation and another does not need motivation) of students considered for the proof. The set of students $S$ in equation 2 is the two categories of students i.e $M$ and $P = N - M$ but for further proof $S$ is considered with one category of students i.e $M$. In undergraduate engineering program, there are four years of students.
and the junior batch students are influenced by senior batch students as in equation 3.
\[ S \subset \{s_1, s_2, s_3, \ldots s_M, s_{M+1}, \ldots s_N\} \text{ where } N - M << M \quad (2) \]
**Postulate 4.** A student is influenced by the senior students and placement record. \((s \leftarrow SS)\)
**Postulate 5.** A student believes in seniors as well as Instructor but has more belief in senior student than
Instructor. That is \( S_1 >> S_2 \) and \( S_1 >> I \) but \( (S_1 >> S_2) > (S_1 >> I) \).
**Postulate 6.** In most of the cases, student mindset about a subject is fixed before the beginning of the class.
**Postulate 7.** Linking each concept with present Industry and research requirements can make students know a subject’s need.
**Lemma 2.** If Instructor follows only textbook-based teaching, encouraging a student towards a subject is challenging.
**Proof.** Given Postulate 4, 5 and 6, encouraging a student with the textbook teaching is a challenging task for the Instructor if a subject is not directly visible as a requirement for placement and research.
**Lemma 3.** If Instructor follow the proposed teaching methodology, the student mindset about the subject will be positive and motivated.
**Proof.** Given postulate 7, students’ mindset about a subject will be positive and motivated towards the subject.
**Lemma 4.** If the Instructor changes the notion about a subject once, it will have consequences for the junior students.
<table>
<thead>
<tr>
<th>Notation</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>$S$</td>
<td>Students study a subject</td>
</tr>
<tr>
<td>$SS$</td>
<td>Students already studied a subject</td>
</tr>
<tr>
<td>$S_b$</td>
<td>Year wise batch students</td>
</tr>
<tr>
<td>$I$</td>
<td>Instructor of a subject</td>
</tr>
<tr>
<td>$N$</td>
<td>Total number of students</td>
</tr>
<tr>
<td>$M$</td>
<td>Number of generic students who needs motivation</td>
</tr>
<tr>
<td>$O$</td>
<td>Outliers $N-M$, concentrate on subject irrespective of the teaching methodology and seniors comments</td>
</tr>
</tbody>
</table>
\[ a \leftarrow b \] \quad \text{b influences a} \\
\[ a >> b \] \quad \text{a believe b} \\
\[ x << y \] \quad \text{x is very lower than y}
Figure 10. Batch - I (2019) Students opinion (feedback) survey results comparison – Compiler Design
**Proof.** Given postulate 4 and 5, the junior student notion about a subject can be changed if the senior student is motivated toward the respective subject.
The survey results in Figure 10 supports the Lemma 2 and 3. The survey results in Table 2 is not supporting the Lemma 4 however, after two or three batches, Instructor can realize the impact of Lemma 4.
### 6.1. Limitation
Deciding on the number of teaching hours including lectures, tutorials and practicals hours is more important for a subject since all topics need to be taught to the students within a semester. The academic committee of an Institute decide credit hours according to the content weight of the subject while creating the curriculum, thus making it possible to complete all topics in a semester. The credit hours vary from a subject to subject and nature of the subjects such as core, elective, add-on, practical oriented, etc. The proposed teaching methodology covers various aspects, including the student assignment and problem evaluation, retraining the students and re-evaluation, and discussing each concept of a subject by following the proposed pyramid model. This teaching methodology needs more time due to multiple learning level (Below Average, Average and Above Average) of students in the class. In some cases the time or total duration of the semester may not be sufficient to complete all the subject topics following the proposed methodology. Hence, the proposed methodology needs to be optimized further to make it effective in the allotted time without affecting the semester’s regular exercises such as exams, result declaration, etc. There is a possibility that the proposed teaching methodology can be applied entirely to the subjects that are not having the open visibility of Industry and Research need for others with a reduction. For example, Machine Learning course has open visibility because a lot many research paper like [42] [43] can be found easily and more work available on it thus we can optimize the proposed teaching methodology. However, the effectiveness should not be affected.
### 7. Conclusion
This paper analysed various teaching methodologies and identified the three research questions that need to be addressed to improve the quality of teaching and understanding level of students. The proposed teaching methodology using the concept map, concept
order queue, pyramid structure, Industry and Research assignments and problems addresses the questions. The methodology advances the teaching practice compared to the existing techniques. The Compiler Design subject is chosen for the experiment of the proposed teaching methodology since many students pre-decided that this subject is of less scope in the research and development. Teaching Compiler Design through the proposed teaching methodology made students understand the importance of Compiler Design subject in the Industry and research domain, thus motivated them to self-design the problems and assignments and be attentive in the classroom. The sign test performed on the students’ feedback collected through a survey at the beginning and the end proves the significance and impact of the proposed teaching methodology. This methodology can also be used for other subjects; however this discussed limitation needs to be addressed. The future work of this paper is to optimize the proposed teaching methodology, possibly by doing parallel activities to make it effective in the available time. Also to experiment with other batches and subjects that are considered by the students’ as not or less required for their Research or Industry placement or both.
Acknowledgement
Authors would like to thank the students those who are participated in the survey.
References
[31] Worm, G. The sign test .
[34] Part i: Lexical analysis slides .
[38] Schreiner, A. and Kühl, B. Object-oriented compiler construction .
|
{"Source-Url": "https://eudl.eu/pdf/10.4108/eetel.v8i1.2550", "len_cl100k_base": 10224, "olmocr-version": "0.1.50", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 51086, "total-output-tokens": 13250, "length": "2e13", "weborganizer": {"__label__adult": 0.00095367431640625, "__label__art_design": 0.002208709716796875, "__label__crime_law": 0.0007920265197753906, "__label__education_jobs": 0.192138671875, "__label__entertainment": 0.0002739429473876953, "__label__fashion_beauty": 0.0006546974182128906, "__label__finance_business": 0.0008440017700195312, "__label__food_dining": 0.0012216567993164062, "__label__games": 0.0021419525146484375, "__label__hardware": 0.002777099609375, "__label__health": 0.0014858245849609375, "__label__history": 0.0012884140014648438, "__label__home_hobbies": 0.0004911422729492188, "__label__industrial": 0.0016632080078125, "__label__literature": 0.0011386871337890625, "__label__politics": 0.0010805130004882812, "__label__religion": 0.0017995834350585938, "__label__science_tech": 0.0645751953125, "__label__social_life": 0.0005164146423339844, "__label__software": 0.007205963134765625, "__label__software_dev": 0.7109375, "__label__sports_fitness": 0.0012149810791015625, "__label__transportation": 0.0020465850830078125, "__label__travel": 0.0006194114685058594}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56057, 0.03369]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56057, 0.78952]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56057, 0.91571]], "google_gemma-3-12b-it_contains_pii": [[0, 3706, false], [3706, 6955, null], [6955, 12129, null], [12129, 16806, null], [16806, 20816, null], [20816, 25509, null], [25509, 30858, null], [30858, 33373, null], [33373, 33412, null], [33412, 38219, null], [38219, 39468, null], [39468, 41691, null], [41691, 43580, null], [43580, 43994, null], [43994, 45046, null], [45046, 48138, null], [48138, 53682, null], [53682, 56057, null]], "google_gemma-3-12b-it_is_public_document": [[0, 3706, true], [3706, 6955, null], [6955, 12129, null], [12129, 16806, null], [16806, 20816, null], [20816, 25509, null], [25509, 30858, null], [30858, 33373, null], [33373, 33412, null], [33412, 38219, null], [38219, 39468, null], [39468, 41691, null], [41691, 43580, null], [43580, 43994, null], [43994, 45046, null], [45046, 48138, null], [48138, 53682, null], [53682, 56057, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56057, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56057, null]], "pdf_page_numbers": [[0, 3706, 1], [3706, 6955, 2], [6955, 12129, 3], [12129, 16806, 4], [16806, 20816, 5], [20816, 25509, 6], [25509, 30858, 7], [30858, 33373, 8], [33373, 33412, 9], [33412, 38219, 10], [38219, 39468, 11], [39468, 41691, 12], [41691, 43580, 13], [43580, 43994, 14], [43994, 45046, 15], [45046, 48138, 16], [48138, 53682, 17], [53682, 56057, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56057, 0.09894]]}
|
olmocr_science_pdfs
|
2024-11-28
|
2024-11-28
|
88ee789b761a473185b109dbecc90ef5516e3383
|
8.7. How can I add my own tag library to the JBoss Tools Palette? .......................... 99
8.8. How to get Code Assist for Seam specific resources in an externally generated
project? ......................................................................................................................... 100
8.9. How to import an example Seam project from jboss-eap directory? ............... 100
8.10. Is a cross-platform project import possible for JBoss Developer Studio? ......... 100
9. Further Reading ........................................................................................................ 101
Chapter 1.
Installation Instructions
1.1. Installing JBoss Tools Plugins
The JBoss Tools plugins can be installed in Eclipse from the JBoss.org update site. JBoss Tools 3.2 requires Eclipse 3.6, which can be downloaded from the Eclipse web site [http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/helios/].
To install the JBoss Tools plugins start Eclipse and select Help → Install New Software...

**Figure 1.1. Install New Software**
Click the Add... button.
Available Software
Select a site or enter the location of a site.
Work with: type or select a site
Find more software by working
Type filter text
Name
There is no site selected.
Select All Deselect All
Details
Show only the latest versions of available software
Group items by category
Contact all update sites during install to find required software
Figure 1.2. Install Dialog
Installing JBoss Tools Plugins
This will display the Add Repository dialog. Enter JBoss.org Tools in the Name field, and http://download.jboss.org/jbosstools/updates/JBossTools-3.2.0.GA/ in the Location field. Click the OK button to save the changes and close the dialog.
Figure 1.3. Add Repository
The JBoss.org Tools site will be selected in the Work with drop down list, and after a moment the list of plugins that are included in the JBoss Tools package will be listed. From this list you can individually select the desired plugin, or select the All JBoss Tools 3.2.0 option to install all the plugins.
Chapter 1. Installation Instructions
Figure 1.4. Available Software
Available Software
Check the items that you wish to install.
Find more software
type filter text
Name
- [x] All JBoss Tools 3.2.0
- [ ] Application Development
- [ ] Business Intelligence, Reporting and Charting
- [ ] Cloud
- [ ] Data Services
- [ ] Maven Support
- [ ] SOA Development
- [ ] Test and Performance
- [ ] Web and Java EE Development
Select All Deselect All 26 items selected
Details
Contains ALL the plugins that are available from JBoss Tools except those related to integration with 3rd party plugins. Selecting this category will give you all tools needed
Figure 1.4. Available Software
- [x] Show only the latest versions of available software
- [x] Have items by category
- [x] Contact all update sites during install to find required software
Click the **Next** button to calculate the system requirements and dependencies (this may take a little while). You will then be given an opportunity to review the plugins that will be installed.
Chapter 1. Installation Instruction
Figure 1.5. Installation review
<table>
<thead>
<tr>
<th>Name</th>
<th>Version</th>
</tr>
</thead>
<tbody>
<tr>
<td>Common tools for jBPM 3 and jBPM 4</td>
<td>4.4.0.v201</td>
</tr>
<tr>
<td>Context and Dependency Injection Tools</td>
<td>1.1.0.v201</td>
</tr>
<tr>
<td>FreeMarker IDE</td>
<td>1.1.0.v201</td>
</tr>
<tr>
<td>Hibernate Tools</td>
<td>3.4.0.v201</td>
</tr>
<tr>
<td>JBoss Archives Tools</td>
<td>3.2.0.v201</td>
</tr>
<tr>
<td>JBoss Drools Core</td>
<td>5.2.0.v201</td>
</tr>
<tr>
<td>JBoss Drools Guvnor</td>
<td>5.2.0.v201</td>
</tr>
<tr>
<td>JBoss Drools Task</td>
<td>5.2.0.v201</td>
</tr>
<tr>
<td>JBoss ESB Tools</td>
<td>1.3.0.v201</td>
</tr>
<tr>
<td>JBoss Portlet</td>
<td>1.1.0.v201</td>
</tr>
<tr>
<td>JBoss Runtime Detection Core</td>
<td>1.0.0.v201</td>
</tr>
<tr>
<td>JBoss Tools Community Project Examples</td>
<td>1.1.0.v201</td>
</tr>
<tr>
<td>JBoss Tools RichFaces</td>
<td>3.2.0.v201</td>
</tr>
<tr>
<td>JBoss Tools Usage Reporting</td>
<td>1.0.0.v201</td>
</tr>
<tr>
<td>JBoss WebServices Tools</td>
<td>1.1.0.v201</td>
</tr>
</tbody>
</table>
Click the **Next** button to install the selected plugins. You will be prompted to accept the various license agreements that cover the plugins that are to be installed. Review the licenses, select the **I accept the terms of the license agreements** option, and click the **Finish** button to install the plugins.
Review Licenses
Licenses must be reviewed and accepted before the software can be installed.
Licenses:
- Eclipse Foundation Software User Agreement
- Licensed under the Apache License, Version 2.0 (the "License");
- Red Hat, Inc. licenses these features and plugins to you under certain options.
Figure 1.6. License review
Installing JBoss Tools Plugins
Wait while the plugins are downloaded and installed.

**Figure 1.7. Installing Software**
You may be prompted with a warning informing you that you are attempting to install unsigned content. Click the **OK** button to continue.

**Figure 1.8. Unsigned Software Warning**
You will then have to restart Eclipse to apply the new plugins. Click the **Restart Now** button to restart Eclipse.
Figure 1.9. Restart Eclipse
The plugin is now installed and ready to use.
1.2. Usage Reporting
JBoss Tools now includes a usage plug-in that anonymously reports information back to JBoss. The plug-in is not enabled by default. To enable, click the Yes button.
Figure 1.10. Usage plug-in pop-up
Once enabled, the plug-in will remain active until turned off. To turn the active plug-in off, navigate to Window → Preferences → JBoss Tools → Usage Reporting.
The gathered data allows JBoss to see how the tools are being used and where they are being used geographically. Currently we are looking into the operating systems being used, screen resolution and how often the tooling environment is started. In the future geographic information will assist in focusing translation resources to areas where the developer environment is most used.
The plug-in uses Google Analytics to track and report data by acting as if you were visiting the site http://jboss.org/tools/usage/. To view the type of information being collected, refer to Section 1.2.1, “Collected usage information guide”.
To view the source code of the usage plug-in visit http://anonsvn.jboss.org/repos/jbosstools/trunk/usage/.
1.2.1. Collected usage information guide
Below you will find an outline of the information that is reported and the Google Analytics fields that are used to gather this information.
Version
The Content field has been modified to report the installed JBoss Developer Studio version. Sample returned values include: jbdevstudio-linux-gtk-x86_64-4.0.0.v201009301221R-H20-Beta1.jar and jbdevstudio-linux-gtk-3.0.2.v201009161622R-H138-GA.jar.
Installed components
The Keyword field has been modified to report the installed JBoss Developer Studio components. Sample returned values include: JBoss AS, Drools, Teiid and ModeShape.
Visitor type
The Visitor type field reports if the current user is new or returning.
Language
The Language field reports the localized language the product is being used in. Sample returned values include: en-US, de-DE and fr-FR.
Location fields
The location fields report the geographical location where the product is being used based on the continent, country and city. Sample returned values include: Europe (continent), Germany (country) and Munich (city).
Eclipse interface and version
The Browser field has been modified to report the Eclipse interface and version being used. Sample returned values include: JBoss Developer Studio: 5.0.0 and JBoss Developer Studio: 5.0.1.
Operating System
The Operating System field reports the Operating System and its version that the product is running on (with Linux distribution version reporting conducted through the User Defined Value field). Sample returned values include: Linux, Macintosh 10.6, Macintosh 10.7 and Windows 7.
Linux distribution version
The User Defined Value field reports the distribution and version of Linux, if one is being used as the Operating System. Sample returned values include: Red Hat Enterprise Linux 6 and Fedora 16.
Chapter 1. Installation Instr...
Screen colors
The **Screen colors** field reports the color depth being used. Sample returned values include: 32-bit and 24-bit.
Screen resolution
The **Screen resolution** field reports the resolution being used. Sample returned values include: 2048x1536 and 1920x1080.
Java version
The **Flash version** field has been modified to report the Java version used. Sample returned values include: 1.6.0_20.
Connection speed
The **Connection speed** field reports the type of internet connection being used. Sample returned values include: T1, Cable and DSL.
JBoss Central Enabled
The **JBoss Central Enabled** field reports whether JBoss Central is set to be seen upon startup or not. Returned value is either true or false.
JBoss Central
When viewing the workbench for the first time you will be greeted with *JBoss Central*. JBoss Central assists you in getting started and keeps you up to date with JBoss technologies.

**Figure 2.1. JBoss Central**
### 2.1. Getting Started with JBoss Central
The *Getting Started* tab of JBoss Central is the first tab you will see, and is setup as a functional starting point for developers.
At the top of the tab is a search box. By clicking the down arrow to the left you can select to perform a search on either the Red Hat Customer Portal or the JBoss Community.
Figure 2.2. Search Options
Performing a search will launch a web browser as a new tab, displaying the results page. You can interact with the browser as you would any other web browser.
Getting Started with JBoss Central
Figure 2.3. Search Results
From the Create Projects section you can create a Dynamic Web Project, OpenShift Express Application, Java EE Web Project, Java EE Project, HTML5 Project, Spring MVC Project, RichFaces Project, GWT Web Project, or any one of many Project Examples. To access a complete list of projects you can create, click on the window icon at the top-right of the Create Projects section.
Note
All wizards generate Maven based projects, except for the Dynamic Web Project wizard.
Figure 2.4. Creating a Project
GWT (Google Web Toolkit) Web Project creation. To create a GWT web project, the latest m2e-wtp and Google plug-ins have to be installed. If these plug-ins have not been previously installed, the first page of the GWT web project wizard will provide you with the ability to install the plug-ins.
Under the **Project Examples** section you can expand and view **JBoss Quickstarts**. Each quickstart is an example to assist first time users.
Figure 2.6. Project Examples
For an in-depth look into the installation of project examples go to Section 2.3, “Project Example Installation”.
You can also download other examples and install and set runtime preferences through the Project Examples section by using the five buttons at the top-right. The first button launches a New Project Examples wizard. Here you can search and download project examples to assist you with getting started.
By clicking on the second button you will be taken directly to the JBoss Tools Runtime Detection dialog within Preferences.
Figure 2.7. New Project Examples wizard
Figure 2.8. JBoss Tools Runtime Detection
The third button takes you directly to the Server Runtime Environments preferences dialog.
Figure 2.9. Server Runtime Environments preferences
The final button refreshes the Project Examples list.
The Documentation section of JBoss Central contains links to help materials such as reference guides, user forums and documentation concerning new features.
Chapter 2. JBoss Central
Figure 2.10. Documentation links
If you do not wish to see JBoss Central at every startup, you can deselect the checkbox **Show on Startup** in the **Settings** section.
Figure 2.11. Settings section
The **News** and **Blogs** sections are updated automatically, bringing you the latest information concerning JBoss technologies.
2.2. Software installation and updates from within JBoss Central
The Software/Update tab at the bottom of JBoss Central switches to a screen where you can install and update your software.
Note
After using JBoss Central once, the current content will be available offline. This includes project example archives and descriptors, maven artifacts, and news and blog feeds.
Figure 2.12. News and Blogs sections
Chapter 2. JBoss Central
Figure 2.13. Software/Update tab
To install or update software, select the checkbox beside one or more components.
Source Control Management
Plugins for source control systems
- Subclipse + SVNKit by tigris.org, Free, Subclipse License
Eclipse Team Provider for the Subversion version control system, including SVNKit
Testing
Plugins for testing + code quality
- FindBugs by FindBugs Project, Free, LGPL
Tool support for FindBugs
- JRebel by zeroturnaround.org, Commercial
Tool support for JRebel
- PMD by PMD Developers, Free, PMD License
Tool support for PMD
Figure 2.14. Software/Update tab
Once you have selected all the components to update or install, click the
Install button.
button at the bottom left of the tab window. A screen will then appear offering you the option of
deselecting a part of the component if you wish.
### Install
Check the items that you wish to install.
<table>
<thead>
<tr>
<th>Name</th>
<th>Version</th>
<th>Id</th>
</tr>
</thead>
<tbody>
<tr>
<td><img src="image" alt="Subclipse (Required)" /></td>
<td>1.6.18</td>
<td>org.tigris.subversion.subclipse</td>
</tr>
<tr>
<td>![SVNKit Client Adapter (Not required)]</td>
<td>1.6.15</td>
<td>org.tigris.subversion.clientadapter</td>
</tr>
</tbody>
</table>
You will then be asked to confirm the selection of components to install. To accept the selection
press the **Next** button. You can change the components by pressing the **Back** button.
**Figure 2.15. Component selection**
Figure 2.16. Component verification
After pressing the Next button you will need to accept the terms of the license agreement for the associated software being installed. To do this select the corresponding radio button.
Click Finish to begin installation.
Software installation and updates from within JBoss Central
Review Licenses
Licenses must be reviewed and accepted before the software can be installed.
<table>
<thead>
<tr>
<th>Licenses:</th>
<th>License text:</th>
</tr>
</thead>
<tbody>
<tr>
<td>Subclipse Software User Agreement</td>
<td>Subclipse Software User Agreement 11th April, 2006</td>
</tr>
<tr>
<td></td>
<td>Subclipse is licensed under the terms of the Eclipse Public License v1.0. <a href="http://www.eclipse.org/legal/epl-v10.html">http://www.eclipse.org/legal/epl-v10.html</a></td>
</tr>
<tr>
<td></td>
<td>Applicable Licenses</td>
</tr>
<tr>
<td></td>
<td>Subclipse is built upon a number of other open source licenses.</td>
</tr>
<tr>
<td></td>
<td>☐ I accept the terms of the license agreement</td>
</tr>
<tr>
<td></td>
<td>☐ I do not accept the terms of the license agreement</td>
</tr>
</tbody>
</table>
Figure 2.17. Licenses review
As the installation process takes place you can choose to have further details displayed or run the installation in the background.
Figure 2.18. Licenses review
After the software has been downloaded, you will be asked to verify the installation of the components if the contents are unsigned. Install unsigned third-party components with discretion.
Figure 2.19. Installing unsigned content
Once installation is complete, restart JBoss Developer Studio by pressing the **Restart Now** button that appears.
Figure 2.20.
2.3. Project Example Installation
To install an example from within JBoss Central, navigate to the Project Examples section and select an example from the list.
Figure 2.21. Project Examples
This section will guide you through the installation of the Helloworld example.
Click on the Helloworld item in the Quickstarts list.
An installation wizard for the example will open and automatically search for required components on your system. If a particular component is not found (a plug-in or a required version of the JBoss server), the component will be automatically downloaded for you during example installation.
Chapter 2. JBoss Central
Figure 2.22. Project Examples
Click the **Next** button.
You will be asked to define the install location for the example. Your current workspace will be selected by default.
Figure 2.23. Project Examples
Click the Finish button to begin installation of the example.
Once the example has been installed it will appear in the list of projects within your Project Explorer.
Chapter 3.
**JBoss Perspective**
The JBoss perspective is designed to incorporate the views most often used by developers using JBoss, while also changing standard menu items to reflect what a JBoss developer would want and need.

Chapter 3. JBoss Perspective
The JBoss perspective views include: **Project Explorer**, **JBoss Central**, **Outline**, **Palette**, **Properties** and **Servers**.
Certain menus also see a change in available items. These menus include **File → New**, **Window → Show View** and the context menu for a project.
A selection of the menu items for **File → New** can be seen in *Figure 3.2, “JBoss Perspective: File→New”*.
**Figure 3.2. JBoss Perspective: File → New**
A selection of the menu items for **Window → Show View** can be seen in *Figure 3.3, “JBoss Perspective: WindowShow View”*.
**Figure 3.3. JBoss Perspective: Window → Show View**
A selection of the menu items for the context menu of a project can be seen in Figure 3.4, “JBoss Perspective: Context Menu → New”.
**Figure 3.4. JBoss Perspective: Context Menu → New**
Setting up a JBoss runtime and managing the server
Although JBoss Developer Studio works closely with JBoss Enterprise Application Platform 6 we do not ultimately tie you to any particular server for deployment. There are some servers that Studio supports directly (via the bundled Eclipse WTP plug-ins). In this chapter we discuss how to manage a JBoss server.
Note
This chapter assumes you have a JBoss application server installed on your system. If you do not, consult the installation instructions that accompanied your server.
4.1. Adding and configuring a JBoss server runtime
- Select the Servers view by navigating to Window → Show View → Other → Server → Servers.
- Click the new server wizard text in the Servers view or if this is not your first server, right-click anywhere in the view and select New → Server.
- Select the server option that matches your installed server.
### Define a New Server
Choose the type of server to create
#### Select the server type:
- OpenShift Server
- JBoss Enterprise Middleware
- JBoss Enterprise Application Platform 4.3
- JBoss Enterprise Application Platform 5.x
- JBoss Enterprise Application Platform 6.x
- ObjectWeb
#### JBoss Enterprise Application Platform (EAP) 6.x
<table>
<thead>
<tr>
<th>Field</th>
<th>Value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Server’s host name</td>
<td>localhost</td>
</tr>
<tr>
<td>Server name</td>
<td>JBoss EAP 6.0 Runtime Server</td>
</tr>
<tr>
<td>Server runtime environment</td>
<td>JBoss EAP 6.0 Runtime</td>
</tr>
</tbody>
</table>
**Figure 4.1. Selecting Server Name and Server Type**
- To setup the new runtime, click the **Next** button.
- In the next dialog verify the specified information and set local or remote server information.
Adding and configuring a JBoss server runtime
Create a new JBoss Server
JBoss Enterprise Application Platform 6.0
A JBoss Server manages starting and stopping instances of JBoss. It manages command line arguments and keeps track of which modules have been deployed.
Runtime Information
If the runtime information below is incorrect, please press back, Installed Runtimes..., and then Add to create a new runtime from a different location.
Execution Environment Java Platform, Standard Edition 6.0
JRE Default JRE for JavaSE-1.6
Server Behaviour
- Server is externally managed. Assume server is started.
- Listen on all interfaces to allow remote web connections
- Expose your management port as the server’s hostname
Local
Figure 4.2. JBoss Runtime Summary
• Lastly, a screen will appear that will allow you to modify projects that are to be configured for the server. Click the Finish button.
Chapter 4. Setting up a JBoss...
Add and Remove
Modify the resources that are configured on the server
Move resources to the right to configure them on the server
Available:
Configured:
- Add >
- < Remove
- Add All >>
- << Remove All
Figure 4.3. Configuring Projects
A new JBoss Server should now appear in the Servers view.
Starting JBoss Server
4.2. Starting JBoss Server
Starting JBoss Server is quite simple. JBoss Developer Studio allows you to control its behavior with the help of a special toolbar, where you could start it in a regular or debug mode, stop it or restart it.
- To launch the server click the green-with-white-arrow icon in the Servers view or right click server name in this view and click the Start button. If this view is not open, select Window → Show View → Other → Server → Servers
While launching, server output is written to the Console view:
**Figure 4.4. New JBoss Server**
**Figure 4.5. Starting from Icon**
**Figure 4.6. Console Output**
Chapter 4. Setting up a JBoss...
When the server is started you should see *Started* in the square brackets right next its name in the Servers view.
Figure 4.7. Server is Started
4.3. Stopping the JBoss Server
To stop the server, click the *Stop* button icon in Servers or right click the server name and press *Stop*.
Figure 4.8. Stopping Server
When the server is stopped you will see *Stopped* in the square brackets next to its name.
4.4. Server Container Preferences
You can control how JBoss Developer Studio interacts with server containers in the Server editor. Double-click the server to open it in the editor.
Figure 4.9. Server Overview
Here you can specify some common settings: host name, server name, runtime as well as settings related to publishing, timeouts and server ports.
Developing a simple JSP web application
In this chapter you’ll find out how to create a simple JSP application using JBoss Developer Studio. The application will show a classic “Hello World!” on the page.
We’ll assume that you have already launched JBoss Developer Studio and also that the Web Development perspective is the current perspective. If not, make it active by selecting Window → Open Perspective → Web Development from the menu bar or by selecting Window → Open Perspective → Other... from the menu bar and then selecting Web Development from the Select Perspective dialog box.
5.1. Setting Up the Project
We are going to start by creating a Dynamic Web Project with a minimal structure, i.e. with just required facets. Thus this section will perform you all necessary steps on how to do this.
• Go to the menu bar and select File → New → Other...
• Select Web → Dynamic Web Project in the New Project dialog box
• Click the Next button
• Enter "jspHello" as a project name
• Then select Minimal Configuration from the list of possible configurations and click the Finish button.
Figure 5.1. Create New Web Project
The *jspHello* node should appear in the upper-left Package Explorer view.

### 5.2. Creating JSP Page
This section covers all the points how to create, edit and then preview JSP page.
In our simple application we need to create only one JSP page which displays a "Hello World!" message.
- Right click the *WebContent* folder and select **New → JSP**.
- Type *hello.jsp* for a file name and click the **Next** button.
In the next window you can choose a template for your JSP page and see its preview.
- Select **New JSP File (xhtml)** template and click the **Finish** button.
Figure 5.3. Create JSP Page
Our hello.jsp page will now appear in the Project Explorer view.
5.2.1. Editing a JSP Page
Let's now make a little change so that a JSP page displays "Hello World!" message.
- Insert this line inside the `<body> </body>` tag:
```jsp
<% System.out.println("Hello World!"); %>
```
Notice that content assist functionality is always available when you are typing:

After changes made your hello.jsp page should look like this:
Figure 5.5. Hello.jsp Page Source
This line will actually output "Hello World!" message in the Console. To make the message displayed in the Browser, just replace this line with the simple Hello World!.
5.2.2. web.xml file
When you are creating web project the wizard creates the web.xml file for you automatically. The web.xml file editor provided by JBoss Developer Studio is available in two modes: Tree and Source.
Figure 5.6. Web.xml in Design and Source Mode
Both modes are fully synchronized. Let's add a mapping to our hello.jsp page in the web.xml file.
- Switch to the Source tab.
- Add the next code into `<welcome-file-list>`:
```xml
<welcome-file>hello.jsp</welcome-file>
```
If you go back to Tree tab you will see that the changes made in the Source tab are automatically reflected.
Actually you do not really need to do any configurations right now.
5.2.3. Deploying the project
Writing ant scripts and managing the packaging process can be quite a complicated and time consuming task for even the most trivial web applications. However, JBoss Developer Studio relieves you of this burden. All you need is to start your JBoss Server and launch your application in your favorite browser.
You can also create a JAR archive with JBoss Developer Studio’s Archive Tools and export it to any web server.
5.2.3.1. JAR Config
Project archives managing is available through the Project Archives view.
* Select Window \rightarrow Show view \rightarrow Other \rightarrow JBoss Tools \rightarrow Project archives from the menu bar
* Select a project in Package Explorer you want to be archived
In the Project Archives view you will see that the project is now listed:

**Figure 5.7. Project Archives**
Right click on the project and select the JAR type of archive.
Deploying the project
Figure 5.8. Project Archives
In the New JAR dialog you can see automatically selected default values.
Figure 5.9. New JAR Archive
- Click the Finish button. The JAR file will appear in Package Explorer and also in Project Archives view as structure tree:
5.2.3.2. Auto redeploy
When you create a web application and register it on the JBoss Server as it is automatically deployed into the /deploy directory of the server, JBoss Developer Studio's auto-redeploy feature
ensures you do not need to restart the server. Any changes made in the application in exploded format will trigger a redeployment on the server.
You can also use the “Finger touch” button for a quick restart of the project without restarting the server:

**Figure 5.13. Finger Touch button**
The “Finger” touches descriptors dependent on project (i.e. web.xml for WAR, application.xml for EAR, jboss-esb.xml in ESB projects).
### 5.2.4. JSP Page Preview
JBoss Developer Studio comes with JSP design-time preview features. When designing JSP pages you can easily preview how they will look during runtime. You can even attach your stylesheet to the Preview.
- Make a little change to hello.jsp page, e.g. put this code snippet:
```jsp
<%= new java.util.Date() %>
```
- Click the **Save** button.
- Switch to Preview page by clicking the Preview tab at the bottom of the page. You will see how the page will look at runtime.
### 5.2.5. Launch JSP Project
Now launch the project onto a JBoss server:
- Start a JBoss Server from the Servers view by clicking the Start the server icon (  ).
- Click the **Run** icon or right click your project folder and select **Run As → Run on Server**. If you haven't made any changes in the web.xml file or cleared it out you can launch the application by right clicking the hello.jsp page and selecting **Run on the Server**.
You should see the next page in a Browser:

**Figure 5.14. Running Project**
You have learnt how to organize a Dynamic Web Project with a minimal configuration, add new elements to it (in our case it is a JSP page), deploy, and run it on a JBoss Server from within JBoss Developer Studio.
Rapid Application Development of a JSF application
In this chapter you will learn how to create a JSF application being based on the Rapid Application Development (RAD) philosophy. We will create the familiar Guess Number application. The game is played according to the following rules. You are asked to guess a number between 0 and 100. If the guess is correct, a success page is displayed with a link to play again. If the guess is incorrect, a message is printed notifying that a smaller or a larger number should be entered and the game continues.
You will now learn how to create such an application from scratch, along the way demonstrating the powerful features included in JBoss Developer Studio such as project templating, Visual Page Editor, code completion and others. You will design the JSF application and then run the application from inside JBoss Developer Studio using a JBoss server.
6.1. Setting up the project
First, you should create a JSF 1.2 project using an integrated JBoss Developer Studio’s new project wizard and predefined templates. Follow the next steps:
* In the Web Projects view (if it is not open select Window → Show View → Others → JBoss Tools Web → Web Projects) click Create New JSF Project button.

**Figure 6.1. Create New JSF Project**
* Enter GuessNumber as a project name, in JSF Environment drop down list choose JSF 1.2
* Leave everything else as it is and click the Finish button
Our project will appear in the Project Explorer and Web Projects views. As you can see JBoss Developer Studio has created the entire skeleton for the project with all required libraries, `faces-config.xml` file and `web.xml` file.
Setting up the project
Figure 6.2. New JSF Project
As the project has been set up, new JSP pages should now be created.
6.2. Creating JSP Pages
Here, we are going to add two pages to our application. The first page is called `inputnumber.jsp`. It prompts you to enter a number. If the guess is incorrect, the same page will be redisplayed with a message indicating whether a smaller or a larger number should be tried. The second page is called `success.jsp`. This page will be shown after you guess the number correctly. From this page you also have the option to play the game again.
Steps for adding two pages to your application:
- First a folder called `pages` needs to be created under the `WebContent` folder. To do this right click on the `WebContent` folder in the Package Explorer view and select **New → Folder**. Set the **Folder Name** to `pages` and click the **Finish** button.
Figure 6.3. Create pages folder
- Open the `faces-config.xml` file.
- Right click anywhere on the diagram mode
- From the context menu select **New View**
Figure 6.4. Create New View
- Type `pages/inputnumber` as the value for the From View ID field
- Leave everything else as is and click the Finish button
- In the same way create another JSF view. Type `pages/success` as the value for From View ID
- Select File → Save
On the diagram you will see two created views.
Creating Transition between two views
6.3. Creating Transition between two views
Then, we should create connection between JSP pages.
- In the diagram, select the **Create New Connection** icon third from the top along the upper left side of the diagram to get an arrow cursor with a two-pronged plug at the arrow's bottom.
Figure 6.6. Create Connection
- Click on the `pages/inputnumber` page icon and then click on the `pages/success` page icon
A transition should appear between the two icons of views.
Creating Resource File
6.4. Creating Resource File
A resource file is a file with a `.properties` extension for collecting text messages in one central place. JBoss Developer Studio allows you to create quickly a resource file. The messages stored in a resource file can be displayed to you on a Web page during application execution.
With resource file you don’t hard code anything into the JSP pages. It also makes it easier to translate your application to other languages. All you have to do is to translate all your messages to the other language and save them in a new properties file with a name that ends with the appropriate ISO-639 language code.
It is a good idea to keep your resources inside the `JavaSource` folder, where you keep your `.java` files. Every time you build the project, all `.properties` files will then be copied to the `classes` folder by default.
* Right click the `JavaSource` folder and select **New → Folder**
Figure 6.7. Created Connection
* Select File → **Save** from the menu bar
Chapter 6. Rapid Application ...
• Enter game as the Folder name and click the Finish button
Your resource file and java bean will be stored in this folder.
• Right click on the game folder and select New → Properties File
• Type messages as the value for “name” attribute and click the Finish button
JBoss Developer Studio will automatically open messages.properties file for editing.

• Click the Add button for adding new attribute to your resource file
• Enter how_to_play for the "name" and Please pick a number between 0 and 100. for the value
• Click the **Finish** button
• Add the following properties using the same process:
```
makeguess_button=Make Guess
trayagain_button=Play Again?
success_text=How cool.. You have guessed the number, {0} is correct!
tryagain_smaller=Oops..incorrect guess. Please try a smaller number.
tryagain_bigger=Oops..incorrect guess. Please try a bigger number.
```
• Select **File → Save** from the menu bar
Your .properties file should now look like follows:

**Figure 6.9. Properties are Added**
The **Up** and **Down** buttons allow you to move the attributes in the list. To delete the attribute, select it and press the **Delete** button.
If you want to change a value or a name of your attribute, select it and then click the **Edit** button.
If the `.properties` file is rather big and there are a lot of entries in it, you can use filtering and regular expressions narrow down the list. The Filter and Regular Expressions Search is implemented by an expandable panel, closed by default:
When "Expression" is not selected (as by default), filter is case insensitive. When "Expression" is selected, filter uses regular expressions which are case sensitive.

**Figure 6.10. Filter and Regular Expressions Search Panel**
Enter the characters that should be searched for in the entries to the 'name' or 'value' input fields accordingly. The filtered results will be displayed in the table below:
Figure 6.11. Filter results
When using regular expressions please note, that regular expression syntax does not use "***" for any characters and "?" for any one character. It's necessary to use "." for any one character and "." for any characters. Symbols "***" and "?" are used to show that the preceding token is not required, for example, "a.a" matches "aba" but not "aa", while "a.?a" or a."a" matches both; besides "a."a" matches "abca".
To find the exact match, use sequences \A and \z in expression. For example, expression "^date \z" matches only string "date"; expression "^Adate" matches "date" and "dateline", expression "date$z" matches "date" and "Begin date", and expression "date" matches all of them.
6.5. Creating a Java Bean
In this section you'll learn how to create a Java bean that will hold business logic of our application.
- Right click the game folder
• Select **New → Class**
• Type *NumberBean* for bean name
A java bean is created.
• Declare the variable of your entered number:
```java
Integer userNumber;
```
JBoss Developer Studio allows for quick generation of getters and setters for java bean.
• Right click the *NumberBean.java* file in the Package Explorer view
• Select **Source → Generate Getters and Setters...**
• Check *userNumber* box and click the **OK** button
Figure 6.12. Generate Getters and Setters
• Add the declaration of the second variable
```java
int randomNumber;
```
• .. other bean methods:
```java
public NumberBean ()
{
randomNumber = (int)(Math.random()*100);
System.out.println ( "Random number: "+randomNumber);
}
public String playagain ()
{
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session =
(HttpSession) context.getExternalContext().getSession(false);
session.invalidate();
return "playagain";
}
public String checkGuess ()
{
// if guessed, return 'success' for navigation
if ( userNumber.intValue() == randomNumber )
{
return "success";
}
else
{
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = ResourceBundle.getBundle("game.messages",
context.getViewRoot().getLocale());
String msg = "";
// if number bigger, get appropriate message
if ( userNumber.intValue() > randomNumber )
msg = bundle.getString("tryagain_smaller");
else // if number smaller, get appropriate message
msg = bundle.getString("tryagain_bigger");
// add message to be displayed on the page via <h:messages> tag
context.addMessage (null, new FacesMessage(msg));
// return 'tryagain' for navigation
return "tryagain";
}
}
```
• And the import declarations:
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.faces.application.FacesMessage;
import java.util.ResourceBundle;
The Java Bean contains the following code:
```java
package game;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;
import javax.faces.application.FacesMessage;
import java.util.ResourceBundle;
public class NumberBean
{
Integer userNumber;
int randomNumber; // random number generated by application
public Integer getUserNumber ()
{
return userNumber;
}
public void setUserNumber (Integer value)
{
this.userNumber = value;
}
// constructor, generates random number
public NumberBean ()
{
randomNumber = (int)(Math.random()*100);
System.out.println (
"Random number: " + randomNumber);
}
public String playagain ()
{
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session =
(HttpSession) context.getExternalContext().getSession(false);
session.invalidate();
return "playagain";
}
// check if user guessed the number
public String checkGuess ()
```
6.6. Editing faces-config.xml File
In this section you will learn about the faces-config.xml file.
This file holds two navigation rules and defines the backing bean used.
• **Open the faces-config.xml file in a source mode**
• **Here we will add one more navigation rule and a managed bean declaration, so that the content of the file looks like this:**
```xml
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
version="1.2"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xi="http://www.w3.org/2001/XInclude"
>
```
// if guessed, return 'success' for navigation
if ( userNumber.intValue() == randomNumber )
{
return "success";
}
// incorrect guess
else
{
// get a reference to properties file to retrieve messages
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle =
ResourceBundle.getBundle("game.messages",
context.getViewRoot().getLocale());
String msg = "";
// if number is bigger, get appropriate message
if ( userNumber.intValue() > randomNumber )
msg = bundle.getString("tryagain_smaller");
else // if number smaller, get appropriate message
msg = bundle.getString("tryagain_bigger");
// add message to be displayed on the page via <h:messages> tag
context.addMessage (null, new FacesMessage(msg));
// return 'tryagain' for navigation
return "tryagain";
}
```
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>playagain</from-outcome>
<to-view-id>/pages/inputnumber.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/pages/inputnumber.jsp</from-view-id>
<navigation-case>
<from-outcome>success</from-outcome>
<to-view-id>/pages/success.jsp</to-view-id>
</navigation-case>
</navigation-rule>
The first navigation rule states that from any page (* stands for any page) an outcome of playagain will take you to the /pages/inputnumber.jsp file. Outcome values are returned from backing bean methods in this example. The second navigation rule states that if you are at the page /pages/inputnumber.jsp, and the outcome is success, then navigate to the /pages/success.jsp page.
6.7. Editing the JSP View Files
Now, we will continue editing the JSP files for our two "views" using the Visual Page Editor.
6.7.1. Editing inputnumber.jsp page
First, edit the inputnumber.jsp file.
On this page we will have an output text component displaying a message, a text field for user’s number entering and a button for input submission.
- Open the inputnumber.jsp file by double-clicking on the /pages/inputnumber.jsp icon
The Visual Page Editor will open in a screen split between source code along the top and a WYSIWYG view along the bottom. You can see that some JSF code will have already been generated since we chose a template when creating the page.
At the beginning it's necessary to create a `<h:form>` component that will hold the other components.
- Place the mouse cursor inside the `<f:view>` tag
- Go to JBoss Tools Palette and expand JSF HTML folder by selecting it
- Click on the `<h:form>` tag
Editing inputnumber.jsp page
Figure 6.13. Insert h:form
• In the Insert Tag dialog select the id field and click on the second column. A blinking cursor will appear in a input text field inviting to enter a value of id

**Figure 6.14. Define Id of Form**
• Enter inputNumbers and click the Finish button
In source view you can see the declaration of a form.
```html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h:form id="inputNumbers">
</h:form>
</f:view>
</body>
</html>
Figure 6.15. Created Form
```
First let's declare the properties file in the `inputnumber.jsp` page using the `loadBundle` JSF tag.
- Add this declaration on the top of a page, right after the first two lines:
```javascript
<f:loadBundle basename="game.messages" var="msg"/>
```
As always JBoss Developer Studio provides code assist:
**Figure 6.16. Code Assist**
- Switch to Visual tab, where it is possible to work with the editor through a WYSIWYG interface
- Click the `outputText` item from the **JSF HTML** group in the **JBoss Tools Palette** view, drag the cursor over to the editor, and drop it inside the blue box in the editor
- Select the second column in the value row.
- Click the ... button next to the value field
JBoss Developer Studio will display a list of possible values:
Figure 6.17. Choose Value
- Expand Resource Bundles → msg
- Select the how_to_play value and click the OK button. Then click the Finish button.
Figure 6.18. Selecting Value
The text will appear on the page:
Figure 6.19. Created OutputText Component
• Switch to Source mode and insert a `<br/>` tag after the `<h:outputText>` component to make a new line
• Click the Save button
• On the Palette click on `inputText`, drag the cursor over to the editor, and drop it inside the editor after the text
• Select the value row and click in the second column
• Click the ... button next to the value field
• Expand Managed Beans → NumberBean
• Select `userNumber` value and click the OK button
• Select the Advanced tab
• Select the id row and click in the second column
• Type userNumber in the text field
• Select the required row and click in the second column
• Click ... button next to the value field
• Expand Enumeration and select true as a value
**Figure 6.20. Add "required" Attribute**
• Click the OK button, then click the Finish button
• Go to Source mode
• Add the validation attribute to <f:validateLongRange> for user input validation
```
<h:inputText id="userNumber" value="#{NumberBean.userNumber}" required="true"/>
```
• Click the **Save** button
• Again select **Visual** mode
• On the Palette, click on **commandButton**, drag the cursor over to the editor, and drop it inside the editor after the **inputText** component.
• In the editing dialog select the **value** row and click on the second column
• Click the **...** button next to the value field
• Expand **Resource Bundles** → **msg** and select **makeguess_button** as a value
• Click the **OK** button
• Select the **action** row and click in the second column
• Type **#{NumberBean.checkGuess}** in the text field
• Click the **Finish** button
• In **Source** mode add `<br/>` tags between the `<outputText>, <inputText> and <commandButton>` components to place them on different lines
`inputnumber.jsp` page should look like this:
```jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%@ taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<f:loadBundle basename="game.messages" var="msg"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<f:view>
<h:form id="inputNumbers">
<h:outputText value="#{msg.how_to_play}"/>
<br/>
<h:messages style="color: blue" />
</h:form>
</f:view>
</body>
</html>
```
6.7.2. Editing success.jsp page
We now edit the `success.jsp` page in the same way as we just edited the `inputnumber.jsp` file. The code for the `success.jsp` page should look like the following:
```html
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h" %>
<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f" %>
<f:loadBundle basename="game.messages" var="msg"/>
<html>
<head>
<title></title>
</head>
<body>
<f:view>
<h:form id="result">
<h:outputFormat value="${msg.success_text}"
<f:param value="${NumberBean.userNumber}" />
<br />
<br />
<h:commandButton value="${msg.trayagain_button}"
action="${NumberBean.playagain}" />
</h:form>
</f:view>
</body>
</html>
```
Again you can use code assist provided by JBoss Developer Studio when editing jsp page:
The `success.jsp` page is shown if you correctly guessed the number. The `<h:outputFormat>` tag will get the value of `success_text` from the properties file. The `{0}` in `success_text` will be substituted for by the value of the value attribute within the `<f:param>` tag during runtime.
In the final result you have a button which allows you to replay the game. The `action` value references a backing bean method. In this case, the method only terminates the current session so that when you are shown the first page, the input text box is clear and a new random number is generated.
- Switch to Preview mode to see how this page will look in a browser:
6.8. Creating index.jsp page
Now we need to create the index.jsp page.
The index.jsp page is the entry point of our application. It's just forwarding to the inputnumber.jsp page.
- Right click the WebContent folder and select New → JSP File
- Enter index for name field and click the Next button.
- Untick the Use JSP Template check box and click the Finish button.
- Edit the source of the file so it looks like the following:
6.9. Running the Application
Finally, we have all the pieces needed to run the application.
• Start up JBoss server by clicking on the **Start** icon in the Servers view. (If the JBoss Server is already running, stop it by clicking on the red icon and then start it again. After the messages in the Console tabbed view stop scrolling, JBoss is available)
• Right-click on the project and select **Run As → Run on Server**
• Play with the application by entering correct as well as incorrect values
Note the .jsf extension of a page. It means that we trigger the JSF controller servlet to handle the page according the servlet mapping in the *faces-config.xml* file.
Figure 6.23. You are Asked to Enter a Number Between 0 and 100
Figure 6.24. Your Input is Validated and an Error Message is Displayed if Invalid Input was Entered
Figure 6.25. After You Enter a Guess, the Application Tells You Whether a Smaller or a Larger Number Should be Tried
How cool.. You have guessed the number, 16 is correct!
Figure 6.26. Your Guess is Correct
Uninstalling the JBoss Developer Studio
- Ensure JBoss Developer Studio is not running
- Run the Uninstaller
FAQ
Refer to the following FAQ to get the answers on the most “popular” questions concerning JBoss Developer Studio.
8.1. What should I do if the Visual Page Editor does not start under Linux
Linux users may need to do the following to get the Visual Page Editor to work correctly on their machines.
1. On Red Hat based Linux distributions install the libXp.i386 package
2. Type
```
ln -s libstdc++.so.5.0.7 libstdc++.so.5
```
3. and/or use
```
yum install libXp
```
4. Open the JBoss Developer Studio perspective. If you see the Help view open, close it and restart JBoss Developer Studio
5. If it doesn't help and you use Fedora with Eclipse Version: 3.4.1, the issue can be produced because the libswt-xulrunner-gtk-3449.so file doesn't present in eclipse-swt-3.4.1-5.fc10.x86_64.rpm/eclipse/plugins/org.eclipse.swt.gtk.linux.x86_64_3.4.1.v3449c.jar. To add this file to eclipse you should:
• Decompress `eclipse/plugins/org.eclipse.swt.gtk.linux.x86_3.4.1.v3449c.jar` form `eclipse-SDK-3.4.1-linux-gtk-x86_64.tar.gz`
• Copy `libswt-xulrunner-gtk-3449.so` file to your Fedora Eclipse location.
• Open the file `jbdevstudio.ini`, which can be found in your Fedora Eclipse location and add the following line:
```
-Dswt.library.path=/usr/lib/eclipse
```
,where `/usr/lib/eclipse` is the path to your eclipse folder.
6. If none of these work, do the following:
- Clear the JBoss Developer Studio log file, `<workspace>\.metadata\.log`
- Start JBoss Developer Studio with the `-debug` option:
```
jbdevstudio -debug
```
- Post the JBoss Developer Studio log file (`<workspace>\.metadata\.log`) on the forums.
8.2. Visual Editor starts OK, but the Missing Natures dialog appears

Some functionality of Visual Editor may not work if a project doesn't have `org.jboss.tools.jsf.jsfnature` or `org.jboss.tools.jst.web.kb.kbnature` in `.project` configuration. To fix this problem and turn off the message box execute next steps:
1. Right mouse button click on a project in Package Explorer.
2. Select **Configure → Add JSF Capabilities** from the context menu.
3. Configure your project using Add JSF Capabilities wizard and press Finish.
If you are sure that your project does not need JSF capabilities, just disable this message box by checking **Do not show this dialog again!** checkbox.
8.3. I have an existing Seam 1.2.1 project. Can I migrate or import the project into a JBoss Developer Studio Seam project?
Use the following steps to manually transfer an existing Seam 1.2.1 project into a new JBoss Developer Studio Seam project:
• Create a Seam Web project to get the JBoss tools structure
Then from your Seam 1.2.1 seam-gen project start doing the following:
• Copy src to src
• Copy view to Web content
• Copy resources individual files to where they are in the seam web project etc.
8.4. I have an existing Struts or JSF project. Can I open the project in JBoss Developer Studio?
Yes. From main menu select File → File → Import → Other → JSF Project (or Struts Project) and follow wizard's steps.
8.5. Can I import a WAR file?
Yes. Select File → Import → Web → WAR file then follow importing steps.
8.6. Is it possible to increase the performance of Eclipse after installing your product?
JBoss Developer Studio configures eclipse via the jbdevstudio.ini file to allocate extra memory, but if you for some reason need more memory then by default, you can manually make adjustments in this file. For example:
```
-vmargs -Xms128m -Xmx512m -XX:MaxPermSize=128m
```
8.7. How can I add my own tag library to the JBoss Tools Palette?
See the section on Adding Tag Libraries in the Visual Web Tools Guide.
8.8. How to get Code Assist for Seam specific resources in an externally generated project?
To get Code Assist for Seam specific resources in an externally generated project, you should enable Seam features in Project Preferences. Right click an imported project and navigate Properties → Seam Settings. Check Seam support box to enable all available Seam Settings.
8.9. How to import an example Seam project from jboss-eap directory?
To import an example Seam project from jboss-eap into your working directory, you should perform the following steps:
• Select New → Other → Java Project from Existing Buildfile
• Point to the build.xml file of any chosen project by clicking the Browse button
• Click the Finish button to open the project
As these seam examples are non WTP projects, next you should enable Seam support for them. To do that, right click the project and select Properties → Seam Settings.
8.10. Is a cross-platform project import possible for JBoss Developer Studio?
Yes. You can easily import created in Linux JSF, Struts or Seam project to Windows and vice versa.
To do the transferring JSF, Struts or Seam project, select Menu → Import → General → Existing Projects into Workspace.
Further Reading
• **Seam Dev Tools Reference Guide**
This guide helps you to understand what Seam is and how to install Seam plug-in into Eclipse. It tells you the necessary steps to start working with Seam Framework and assists in a simple Seam Project creation. Also you will learn how to create and run the CRUD Database Application with Seam as well as find out what Seam Editors Features and Seam Components are.
• **Visual Web Tools Reference Guide**
provides general orientation and an overview of visual web tools functionality. This guide discusses the following topics: editors, palette, web properties view, openOn, content assist, RichFaces support.
• **JBoss Server Manager Reference Guide**
This guide covers the basics of working with the JBoss server manager. You will read how to install runtimes and servers and quickly learn how to configure, start, stop the server and know how deployment and archiving process. You will find out how to manage installed JBoss Servers via JBoss AS Perspective. You will also read how to deploy modules onto the server.
• **jBPM Tools Reference Guide**
With jBPM Tools Reference Guide we'll help you to facilitate a cross-product learning and know how you can speed your development using special editors and visual designers. We'll also guide you through the steps on how to create a simple process and test it within jBPM jPDL perspective.
• **Hibernate Tools Reference Guide**
Throughout this guide you will learn how to install and use Hibernate Tools bath via Ant and through Eclipse. We'll supply you with the information on how to create mapping files, configuration file as well as a file for controlling reverse engineering by using specific wizards that Hibernate tooling provides. Also you will know about Code Generation and peculiarities of work within Hibernate Console Perspective.
• **ESB Editor Reference Guide**
This guide provides you with the information on ESB Editor and all necessary wizards for ESB files development.
• **JBoss Portal Tools Reference Guide**
The guide gives a detail look at how you can easily build a Portlet Web Application with JBoss Tools and deploy it onto JBoss Portal.
• **JBoss WS User Guide**
This guide gives you practical help on JBossWS usage. You will learn how to create a web service using JBossWS runtime, find out how to create a web service client from a WSDL document using JBoss WS and also see how to set your development environment.
• Smooks Tools Reference Guide
This guide is packed with useful and easy-to-understand information about graphical, configuration and source editor pages.
• Drools Tools Reference Guide
The guide help you to discover how to create a new Drools project, use debugging rules and work with different editors.
• JMX Tools Reference Guide
With the help of this guide you'll explore the best practices to follow when working with MBean Explorer, MBean Editor, Connections and etc.
• Eclipse Guvnor Tools Reference Guide
The purpose of this guide is to describe briefly the functionality present in the Eclipse Guvnor Tools (EGT) for Drools 5.
• JSF Tools Tutorial
This tutorial will describe how to deal with classic/old style of JSF development and how to create a simple JSF application.
• JSF Tools Reference Guide
From this guide you'll discover all peculiarities of work at a JSF project. You'll learn all shades that cover the process of project creation and take a closer look at the JSF configuration file. Also you'll get to know managed beans and how to work with them and find out, how to create and register a custom converter, custom validator and referenced beans in a JSF project.
• Struts Tools Reference Guide
In Struts Tools Reference Guide you will learn how to create and work with a new struts project. This guide also provides information about graphical editor for struts configuration files, tiles files, and struts validation files.
• Struts Tools Tutorial
This tutorial will describe the classical style of Struts development, and will step-by-step show you how to create a simple Struts application.
|
{"Source-Url": "https://docs.jboss.org/tools/3.3.0.Final/en/GettingStartedGuide/pdf/Getting_Started_Guide.pdf", "len_cl100k_base": 13848, "olmocr-version": "0.1.50", "pdf-total-pages": 106, "total-fallback-pages": 0, "total-input-tokens": 145630, "total-output-tokens": 17997, "length": "2e13", "weborganizer": {"__label__adult": 0.0003995895385742187, "__label__art_design": 0.0004439353942871094, "__label__crime_law": 0.00015676021575927734, "__label__education_jobs": 0.0010786056518554688, "__label__entertainment": 9.548664093017578e-05, "__label__fashion_beauty": 0.0001405477523803711, "__label__finance_business": 0.0002083778381347656, "__label__food_dining": 0.00023114681243896484, "__label__games": 0.0012340545654296875, "__label__hardware": 0.0004494190216064453, "__label__health": 0.0001316070556640625, "__label__history": 0.0001832246780395508, "__label__home_hobbies": 9.08970832824707e-05, "__label__industrial": 0.00017273426055908203, "__label__literature": 0.00022232532501220703, "__label__politics": 0.00013947486877441406, "__label__religion": 0.0003597736358642578, "__label__science_tech": 0.0009160041809082032, "__label__social_life": 0.00011098384857177734, "__label__software": 0.01171112060546875, "__label__software_dev": 0.98095703125, "__label__sports_fitness": 0.00029158592224121094, "__label__transportation": 0.0002486705780029297, "__label__travel": 0.0002300739288330078}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 59520, 0.01574]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 59520, 0.24287]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 59520, 0.77916]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 0, null], [0, 0, null], [0, 624, false], [624, 1156, null], [1156, 1544, null], [1544, 2155, null], [2155, 3073, null], [3073, 3269, null], [3269, 4836, null], [4836, 5151, null], [5151, 5478, null], [5478, 5960, null], [5960, 6804, null], [6804, 8991, null], [8991, 9752, null], [9752, 10186, null], [10186, 10549, null], [10549, 11082, null], [11082, 11409, null], [11409, 11553, null], [11553, 11999, null], [11999, 12164, null], [12164, 12298, null], [12298, 12563, null], [12563, 12922, null], [12922, 13334, null], [13334, 14055, null], [14055, 14818, null], [14818, 15077, null], [15077, 16122, null], [16122, 16514, null], [16514, 17136, null], [17136, 17339, null], [17339, 17538, null], [17538, 17538, null], [17538, 17815, null], [17815, 18468, null], [18468, 18655, null], [18655, 18655, null], [18655, 19549, null], [19549, 20372, null], [20372, 21354, null], [21354, 21691, null], [21691, 22346, null], [22346, 22974, null], [22974, 23148, null], [23148, 23148, null], [23148, 24249, null], [24249, 24284, null], [24284, 24909, null], [24909, 24937, null], [24937, 25422, null], [25422, 25844, null], [25844, 26296, null], [26296, 27241, null], [27241, 27522, null], [27522, 27737, null], [27737, 29168, null], [29168, 29494, null], [29494, 30962, null], [30962, 31193, null], [31193, 31245, null], [31245, 32091, null], [32091, 32247, null], [32247, 32564, null], [32564, 32891, null], [32891, 33075, null], [33075, 34101, null], [34101, 34712, null], [34712, 35288, null], [35288, 36248, null], [36248, 37131, null], [37131, 37567, null], [37567, 37609, null], [37609, 39003, null], [39003, 40225, null], [40225, 41628, null], [41628, 42878, null], [42878, 43370, null], [43370, 43427, null], [43427, 43760, null], [43760, 43992, null], [43992, 44760, null], [44760, 44905, null], [44905, 44969, null], [44969, 45483, null], [45483, 46011, null], [46011, 47456, null], [47456, 48227, null], [48227, 48887, null], [48887, 49318, null], [49318, 49989, null], [49989, 50052, null], [50052, 50152, null], [50152, 50269, null], [50269, 50360, null], [50360, 50360, null], [50360, 50470, null], [50470, 50470, null], [50470, 51814, null], [51814, 52858, null], [52858, 54193, null], [54193, 55406, null], [55406, 57630, null], [57630, 59520, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 0, null], [0, 0, null], [0, 624, true], [624, 1156, null], [1156, 1544, null], [1544, 2155, null], [2155, 3073, null], [3073, 3269, null], [3269, 4836, null], [4836, 5151, null], [5151, 5478, null], [5478, 5960, null], [5960, 6804, null], [6804, 8991, null], [8991, 9752, null], [9752, 10186, null], [10186, 10549, null], [10549, 11082, null], [11082, 11409, null], [11409, 11553, null], [11553, 11999, null], [11999, 12164, null], [12164, 12298, null], [12298, 12563, null], [12563, 12922, null], [12922, 13334, null], [13334, 14055, null], [14055, 14818, null], [14818, 15077, null], [15077, 16122, null], [16122, 16514, null], [16514, 17136, null], [17136, 17339, null], [17339, 17538, null], [17538, 17538, null], [17538, 17815, null], [17815, 18468, null], [18468, 18655, null], [18655, 18655, null], [18655, 19549, null], [19549, 20372, null], [20372, 21354, null], [21354, 21691, null], [21691, 22346, null], [22346, 22974, null], [22974, 23148, null], [23148, 23148, null], [23148, 24249, null], [24249, 24284, null], [24284, 24909, null], [24909, 24937, null], [24937, 25422, null], [25422, 25844, null], [25844, 26296, null], [26296, 27241, null], [27241, 27522, null], [27522, 27737, null], [27737, 29168, null], [29168, 29494, null], [29494, 30962, null], [30962, 31193, null], [31193, 31245, null], [31245, 32091, null], [32091, 32247, null], [32247, 32564, null], [32564, 32891, null], [32891, 33075, null], [33075, 34101, null], [34101, 34712, null], [34712, 35288, null], [35288, 36248, null], [36248, 37131, null], [37131, 37567, null], [37567, 37609, null], [37609, 39003, null], [39003, 40225, null], [40225, 41628, null], [41628, 42878, null], [42878, 43370, null], [43370, 43427, null], [43427, 43760, null], [43760, 43992, null], [43992, 44760, null], [44760, 44905, null], [44905, 44969, null], [44969, 45483, null], [45483, 46011, null], [46011, 47456, null], [47456, 48227, null], [48227, 48887, null], [48887, 49318, null], [49318, 49989, null], [49989, 50052, null], [50052, 50152, null], [50152, 50269, null], [50269, 50360, null], [50360, 50360, null], [50360, 50470, null], [50470, 50470, null], [50470, 51814, null], [51814, 52858, null], [52858, 54193, null], [54193, 55406, null], [55406, 57630, null], [57630, 59520, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 59520, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 59520, null]], "pdf_page_numbers": [[0, 0, 1], [0, 0, 2], [0, 0, 3], [0, 624, 4], [624, 1156, 5], [1156, 1544, 6], [1544, 2155, 7], [2155, 3073, 8], [3073, 3269, 9], [3269, 4836, 10], [4836, 5151, 11], [5151, 5478, 12], [5478, 5960, 13], [5960, 6804, 14], [6804, 8991, 15], [8991, 9752, 16], [9752, 10186, 17], [10186, 10549, 18], [10549, 11082, 19], [11082, 11409, 20], [11409, 11553, 21], [11553, 11999, 22], [11999, 12164, 23], [12164, 12298, 24], [12298, 12563, 25], [12563, 12922, 26], [12922, 13334, 27], [13334, 14055, 28], [14055, 14818, 29], [14818, 15077, 30], [15077, 16122, 31], [16122, 16514, 32], [16514, 17136, 33], [17136, 17339, 34], [17339, 17538, 35], [17538, 17538, 36], [17538, 17815, 37], [17815, 18468, 38], [18468, 18655, 39], [18655, 18655, 40], [18655, 19549, 41], [19549, 20372, 42], [20372, 21354, 43], [21354, 21691, 44], [21691, 22346, 45], [22346, 22974, 46], [22974, 23148, 47], [23148, 23148, 48], [23148, 24249, 49], [24249, 24284, 50], [24284, 24909, 51], [24909, 24937, 52], [24937, 25422, 53], [25422, 25844, 54], [25844, 26296, 55], [26296, 27241, 56], [27241, 27522, 57], [27522, 27737, 58], [27737, 29168, 59], [29168, 29494, 60], [29494, 30962, 61], [30962, 31193, 62], [31193, 31245, 63], [31245, 32091, 64], [32091, 32247, 65], [32247, 32564, 66], [32564, 32891, 67], [32891, 33075, 68], [33075, 34101, 69], [34101, 34712, 70], [34712, 35288, 71], [35288, 36248, 72], [36248, 37131, 73], [37131, 37567, 74], [37567, 37609, 75], [37609, 39003, 76], [39003, 40225, 77], [40225, 41628, 78], [41628, 42878, 79], [42878, 43370, 80], [43370, 43427, 81], [43427, 43760, 82], [43760, 43992, 83], [43992, 44760, 84], [44760, 44905, 85], [44905, 44969, 86], [44969, 45483, 87], [45483, 46011, 88], [46011, 47456, 89], [47456, 48227, 90], [48227, 48887, 91], [48887, 49318, 92], [49318, 49989, 93], [49989, 50052, 94], [50052, 50152, 95], [50152, 50269, 96], [50269, 50360, 97], [50360, 50360, 98], [50360, 50470, 99], [50470, 50470, 100], [50470, 51814, 101], [51814, 52858, 102], [52858, 54193, 103], [54193, 55406, 104], [55406, 57630, 105], [57630, 59520, 106]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 59520, 0.03872]]}
|
olmocr_science_pdfs
|
2024-11-30
|
2024-11-30
|
e03ff29c67926eedc9518a9b99c87186deaf46d3
|
Patterns for Maude Metalanguage Applications
Eugen-Ioan Goriac\textsuperscript{a,1,2} Georgiana Caltais\textsuperscript{a,1,2} Dorel Lucanu\textsuperscript{a,1,2} Oana Andrei\textsuperscript{b,3} Gheorghe Grigoras\textsuperscript{a,1,2}
\textsuperscript{a} Faculty of Computer Science
Alexandru Ioan Cuza University
Iaşi, Romania
\textsuperscript{b} INRIA Nancy Grand-Est \& LORIA
Nancy, France
Abstract
One of the most effective ways of improving the quality of software engineering, system design and development, and communication between the people concerned with these problems, is provided by software patterns. In this paper we present a set of basic patterns for Maude metalanguage applications. We show the viability of the defined patterns by comparing them to the developing approaches for several well-known Maude tools.
Keywords: Maude language, Maude metalanguage applications, software patterns.
1 Introduction
Maude \cite{Maude} is a high-level language and high-performance system based on equational and rewriting logic computation. It is a flexible and general semantic framework suitable for giving semantics to a wide range of languages and models of concurrency. It is also a good logical framework, i.e., a metalogic in which many other logics can be naturally represented and implemented. The reflective property of rewriting logic permits the development of many advanced metaprogramming and metalanguage applications.
A metalanguage application is a particular type of application in which Maude is used to define modules for specifying an object language syntax, parser, way of execution and manner of printing execution results. These kinds of applications
\footnote{1 This work is partially supported by the PNII grant IDEI 393.}
\footnote{2 Email: \{egoriac,gcaltai,dlucanu,grigoras\}@info.uaic.ro}
\footnote{3 Email: Oana.Andrei@loria.fr}
are implemented using the Maude metalevel capabilities. For a detailed description of working at metalevel and metalanguage applications, see Chapters 14 and 17, respectively, from [6].
There is already a significant number of metalanguage applications in Maude. Some of them are written by people with Maude programming experience; their applications have a high performance and a good quality design which make them reusable for other software engineers. An application written by someone less familiar with Maude has a low degree of re-usability. The success of the learning process by a new Maude user strongly depends on the kinds of examples he/she studies. We think that Maude has reached a certain maturity level when the best practices should be accessible to a large class of users. This goal can be reached by the means of a good software engineering problem-solving discipline. Such a discipline is given by patterns. The general goal of the patterns is to support design and development.
The contribution of this paper is the definition of a set of basic patterns which may be used in a wide range of Maude metalanguage applications. The design of these patterns is based on the experience acquired by the authors during the development of some applications [10,2] or by studying other applications like those presented in [11,8,7]. The referred applications are: the Inductive Theorem Prover (ITP), the Maude Termination Tool (MTT), the Church-Rosser Checker (CRC) the Real Time Maude Tool (RTM) and the Strategy language for Maude (STR).
The idea of defining patterns for Maude metalanguage applications came when we started to develop a new implementation of membrane systems [13] using strategy controllers [3]. The design of the new application is based on adapting some technologies used by other applications and on the Maude strategy language [11]. During the adaptation process we had to answer some standard questions like which part is application dependent and which one is independent. We realized that these questions can be avoided if we follow a problem solving discipline. That was the moment when we started thinking about patterns. The current version of the Maude strategy language includes good design practices which inspired us in defining the patterns presented in this paper. Actually defining the patterns did not prove to be an easy task. We needed to answer many difficult questions: how should a pattern be structured, which pattern should a certain development activity be associated to, which activities are repetitive and which ones need not be performed more than once during the development of a system, how are the patterns related to each other, how should a system implementation process be formalized.
We have identified four software patterns that should help Maude users in building metalanguage applications: User Interface (the implementation of a communication flow between the user and the system), System Language Signature (the validation of system inputs), System Language Parser (the implementation of a Full Maude parser for translating system input to its Maude semantics) and Error Handling (the detection and handling of user input errors).
The organization of the paper is as follows. Section 2 presents a template for patterns. Section 3 introduces a general context for Maude metalanguage applications, including definitions and conventions used throughout the paper. The patterns
presented in Section 4 work under this context. An iterative strategy of using the patterns is described in Section 5.
2 A template for Maude patterns
Patterns were first introduced by Christopher Alexander [1] and used in urban design and building architecture. Patterns provide a common language that people use in order to formulate problems and to solve them. Briefly, a pattern describes a design problem, a context in which the problem occurs and the core of a solution to that problem. The same solution sketch can be used by different people in order to solve their own particular problems and speed up the development process.
In software engineering, the patterns are used in various domains such as object-oriented design [9], software architecture [5], software testing [4], and so on. The template we use for Maude patterns includes the following six elements: the pattern name, problem, context, solution, result and known uses.
A well chosen name should express in a few words the problem. The problem is described using a concise statement in order to help the reader deciding whether the pattern is appropriate for his particular problem or not. The context specifies the conditions under which the pattern is applied. We may also mention here the built-in Maude modules or the related patterns involved in the description of the problem. Changing the context should invalidate the pattern. In particular, we have identified a general context corresponding to the family of applications we consider in this paper, namely Maude metalanguage applications. This general context is inherited by each of particular contexts of the patterns. The solution describes how the problem is solved. Here we mention the steps one should follow in order to implement the pattern. The description is general enough to address a wide range of situations. The result refers to the outcome of applying the pattern. Here we may also mention the related patterns. In the end, the known uses subsection emphasize the way some Maude tools have applied the presented pattern. The patterns are flexible enough to be combined in different ways in order to design various applications.
3 General Context
The patterns we define in this paper are intended to be used in the context given by the large family of Maude metalanguage applications developed for specifying and analyzing a specific system. Examples of specific systems are prototypes, simulators, provers, extensions of Maude, logics, models of computations and so on.
Such systems are specified using a specification language, called system specification language (SSL). The implementation consists of defining a Maude semantics for SSL and a user interface for introducing specifications and analyzing and executing these specifications using a language of commands, called system command language (SCL).
We assume that SSL is given by a grammar defining its syntax and a set of
rules or equations defining its semantics. We further assume that the syntax of SSL includes a special construct defining units. A unit is intended to describe a component of the system; in particular, the system is described either by a simple unit or by a compound unit. The user interface facilitates the communication between the user and the system: the user may introduce units or commands and the system displays the result obtained after a command is executed.
The commands and the units will be referred to as top input, whereas parts of commands or units that match the provided grammar will be referred to as partial input.
Maude implementation of a system consists of:
- Maude descriptions of the SSL and SCL semantics,
- the structure describing the states of the metalanguage application in Maude terms,
- a set of rewrite rules over system states modeling the execution of the commands in SCL.
Neither the Maude semantics of SSL, nor that of SCL can be described by means of patterns at this level of generality. However, we suppose that a Maude module describing the SSL and SCL semantics, SYSTEM-LANG-SEMANTICS, is defined.
The current system state can be changed or interrogated by using commands from SCL. The execution of a command is guided by the system specification language semantics and depends on the current system state and the provided parameters. Each command $Cmd$ is associated an operation $procCmd$ that denotes its semantics.
$$procCmd : \text{CurrentState Parameters} \to \text{Result}$$
We assume that all these operations are included or defined in the previously mentioned SYSTEM-LANG-SEMANTICS module. This module can also be thought of as an API of the system. It is used by the User Interface pattern but can as well be used by other applications. For instance, the semantics for membranes is given by using the API of the Maude strategy language [11].
The application of the patterns presented in the next section is illustrated by the implementation of a simple system able to perform topological sort. The system (referred to as TOPO\textsuperscript{4}) is provided first of all with a unit specifying the definition of a partial order set. After that, the system is able to interpret a topological sorting command which receives a parameter representing a linearization of the set to be sorted. The dialog with TOPO is intended to be as follows:
Maude> (poset SIMPLE-POSET is
rel a < b .
rel c < b .
rel b < c .
end)
Maude> tsort c d a b e .
result: a d e b c .
\textsuperscript{4} The implementation of the system is found at: http://circidei.info.uaic.ro/pmma2008/topo.maude
Regarding the implementation, an auxiliary module TOPO-DESCRIPTION is used for describing the core behavior of the system. It defines the universe of the poset (in our case, the letters from a to z) and the sorting algorithm (implemented as a rule that modifies a list of objects according to the partial order relation):
\[
\begin{align*}
op s & a b c d e f g h i j k l m n o p q r s t u v w x y z : \rightarrow \text{Obj} . \\
crl O & :\text{Obj} L0: \text{ListOfObjects} O':\text{Obj} \Rightarrow \\
O':\text{Obj} L0: \text{ListOfObjects} O :\text{Obj} & \text{if } O':\text{Obj} < O:\text{Obj} .
\end{align*}
\]
4 Basic Patterns for Maude Metalanguage Applications
4.1 User Interface
Problem. Define the communication flow between the user and the system under implementation.
Context. Maude uses the loop mode (see [6], Section 17.1) to design user interfaces. The loop mode works with triples \( \text{[input:QidList, state:State, output:QidList]} \), also called loop objects. These triples are provided by the LOOP-MODE Maude module. The \( \text{input} \) argument is the text introduced by the user (if any), the \( \text{output} \) argument is the text displayed by the system (if any) and the \( \text{state} \) argument is the (current) system state.
When handling a user request, the system converts the input stream into a list of quoted identifiers and then places this list on the first position of the loop object. When handling the output, the system unquotes the list of identifiers placed on the third position of the loop object and displays the result. The LOOP-MODE module is used not only for defining user interfaces but also for defining the system state structure and the rewrite rules used for modifying this state and for interacting with the loop. The system state structure can be defined in different ways for Maude metalanguage applications, by importing LOOP-MODE in the module used for state definition.
Solution. The solution is based on defining three modules in Maude used for introducing the system grammar and defining the system state structure in order to specialize the system loop:
```maude
mod META-SYSTEM-LANG-SIGN is
including META-LEVEL .
op SYSTEM-GRAMMAR : -> FModule .
define the SYSTEM-GRAMMAR module
endm
mod SYSTEM-STATE-HANDLING is
including SYSTEM-LANG-SEMANTICS .
define the state structure
endm
mod SYSTEM-INTERFACE is
including LOOP-MODE .
including META-SYSTEM-LANG-SIGN .
including SYSTEM-STATE-HANDLING .
define the initial state
define the input rule
define the output rule
endm
```
In what follows we describe how each of the above modules is implemented.
META-SYSTEM-LANG-SIGN. A module which specifies the system grammar is defined at metalevel (SYSTEM-GRAMMAR). This module imports the definition of the system language signature (SYSTEM-LANG-SIGN - see Section 4.2) and defines some
system-specific operators, like those able to handle input tokens (identifiers) or bubbles (lists of identifiers) (see [6], Section 17.4).
If avoiding the definition of the system grammar from scratch is desired, the existing Full Maude grammar can be used. By doing this, the created system will be able to handle anything the Full Maude system can. This is accomplished by appending `SYSTEM-LANG-SIGN` to the provided `GRAMMAR` module. The `addImports` metalevel appending operator is defined within the `UNIT` module and `GRAMMAR` is defined at metalevel within the `META-FULL-MAUDE-SIGN` module.
```
eq SYSTEM-GRAMMAR = addImports((including 'SYSTEM-LANG-SIGN .), GRAMMAR) .
```
When implementing the TOPO system, we choose to use the Full Maude provided grammar:
```
fmod META-TOPO-LANG-SIGN is
including META-LEVEL .
protecting META-FULL-MAUDE-SIGN .
op TOPO-GRAMMAR : -> FModule .
eq TOPO-GRAMMAR = addImports((including 'TOPO-LANG-SIGN .), GRAMMAR) .
endfm
```
**SYSTEM-STATE-HANDLING.** The best way to define the system state structure is inspired from Full Maude (see [6], Section 18.6) and it consists of using a Maude class:
```
class SystemStateClass |
input : TermList,
output : QidList,
attribute1 : Type1
...
```
In practice, a “compiled” form of this class is used when the system state structure is defined (see [12], Section 12.4.2). This is accomplished by declaring the class identifier, an operator of sort `SystemStateClass` and the attributes (including `input` and `output`) in an explicit way:
```
subsort SystemStateClass < Cid .
op SystemState : -> SystemStateClass .
op input :_ : TermList -> Attribute .
op output :_ : QidList -> Attribute .
op attribute1 :_ : Type1 -> Attribute .
...
```
The `input` and `output` attributes are used in order to create a user interface. This way we can provide a mechanism for passing the user input to the value of the system state input attribute and also for forwarding the system state output attribute’s content to the user output.
Instead of defining `TopoStateClass`, the TOPO system makes use of the Full Maude-specific `DatabaseClass` sort in order to characterize the current state. The only extra attribute added to the state structure is `defaultPOSet`, the name of the currently selected module defining the partial order relation:
```
op defaultPOSet :_ : Header -> Attribute .
```
**SYSTEM-INTERFACE.** System loop specialization consists of specifying the initial state, the rule processing the user input and the rule displaying the output messages.
Assuming that SystemStateClass is the only class used for defining the system states, we consider the relation Object < State in order to specify the admissible states within the persistent state of LOOP-MODE. The initial state of the system is defined in the same way as in Full Maude:
```
subsort Object < State .
op o :- > oid . --- the persistent system state object
op init :- > System .
rl [init] : init => [ nil, < o : SystemState | input : nilTermList, output : nil, attribute1 : initialValue1, ...
>, ('State 'Initialization 'Succeeded) ] .
```
The concrete initialization rule from the TOPO system is:
```
rl [init] : init => [ nil, < o : Database | db : initialDatabase,
input : nilTermList, output : nil,
defaultPOSet : nullHeader
>, ('TOPO 'State 'Initialization 'Succeeded) ] .
```
Here, the Full Maude-specific Database constant is used to instantiate the state class DatabaseClass. The inherited attribute db contains detailed information regarding Full Maude loaded units. Our attribute defaultPOSet receives the constant value nullHeader, denoting that in the initial state no module is selected to describe a partial order relation.
The input rewrite rule [in] parses the text introduced by the user. It calls the metaParse operator and sets the resulting term as the input attribute of the next state.
```
crl [in] :
[ Q QL,
< o : SystemState | input : nilTermList, Atts >, QL']
=>
[ nil,
< o : SystemState | input : getTerm(RP), Atts >, QL']
if RP := metaParse(SYSTEM-GRAMMAR, Q QL, '@Input@') ∧
RP :: ResultPair .
```
The output rewrite rule [out] transfers the value of the output attribute to the system output:
```
rl [out] : [ QL, < o : SystemState | output : (Q QL'), Atts >, QL''] =>
[ QL, < o : SystemState | output : nil, Atts >, (Q QL' QL'')] .
```
The template presented for these rules is applied directly when implementing the TOPO system: SystemState is replaced by Database and SYSTEM-GRAMMAR is replaced by TOPO-GRAMMAR.
**Result.** Three modules used for defining the system grammar and specializing the loop: SYSTEM-GRAMMAR, SYSTEM-STATE-HANDLING and SYSTEM-INTERFACE. The only thing that remains to be done in order to initialize the loop after having loaded the specified modules is to call the loop init . command from the Maude environment.
The SYSTEM-STATE-HANDLING module can be refined by applying the Error Handling pattern (Section 4.4).
**Known uses.** All the Maude tools referred to in Section 1 apply this pattern. The
only tool that applies the pattern by defining all required data within the same
module is ITP (it is not implemented using the exemplified modules structure).
The MTT, CRC, RTM and STR tools define the grammar module within a
META-SYSTEM-LANG-SIGN-like module. MTT, CRC, RTM and STR extend the
Full Maude grammar while ITP defines its own grammar from scratch. STR defines
a second grammar from scratch for internal use.
RTM and STR define new attributes for the system state in the manner
described by the pattern. The attributes are defined in a SYSTEM-STATE-HANDLING-
like module. The ITP tool defines attributes using an internal defined sort, other
than Attribute. All the tools define the [init], [in] and [out] rules in a
SYSTEM-INTERFACE-like module.
4.2 System Language Signature
Problem. Define the system language signature used in order to validate system
inputs (a system input is either a unit or a command).
Context. When referring to the system language signature both the system spec-
ification language signature and the system command language signature are con-
sidered. For these languages it is necessary to know the grammars defining their
syntax.
Solution. The general idea of this pattern is to define the modules:
```plaintext
fmod SYSTEM-SPEC-LANG-SORTS is
declare the metavariables
endfm
fmod SYSTEM-SPEC-LANG-SIGN is
including OPERATOR-ATTRIBUTES .
protecting SYSTEM-SPEC-LANG-SORTS .
declare constructors for metavariables
endfm
mod SYSTEM-SPEC-LANG-SIGN is
including SYSTEM-SPEC-LANG-SIGN .
including SYSTEM-CMD-LANG-SIGN .
endm
SYSTEM-SPEC-LANG-SORTS. This module declares the metavariables from the
SSL grammar: for each metavariable MetaVar, a sort @MetaVar@ is defined. Whenever
a list of metavariables of sort @MetaVar@ is desired, a view must be considered:
```
view @MetaVar@ from TRIV to SYSTEM-SPEC-LANG-SORTS is
sort Elt to @MetaVar@ .
endv
```
These views are used for implementing the parameterized modules defining the
generic data types for lists. Now List{MetaVar} is a sort representing a list of
separated metavariables, denoted in the SSL grammar by MetaVar*.
The metavariables from the TOPO sytem are POSet and DeclRelation. The
former one represents a unit defining a partial order relation, while the latter rep-
resents an element of the relation (recall the example presented at the end of Sec-
tion 3). The TOPO-SPEC-LANG-SORTS module includes declarations for the sorts
@POSet@ and @DeclRelation@. A view for the @DeclRelation@ is created in order
to specify the list of elements characterizing the partial order relation associated
with the set.
**SYSTEM-SPEC-LANG-SIGN.** This module includes an operator declaration for each metaexpression occurring in the specification language grammar. For instance, the operator for a metaexpression of the form \( \text{resWord1 \ metaVar1 \ resWord2 \ metaVar2 \ resWord3} \) is defined as follows:
\[
\text{op resWord1\_resWord2\_resWord3 : @MetaVar1@ \@MetaVar2@ \@ResultMetaVar@ .}
\]
When \( @\text{MetaVarX}@ \) is used for specifying an identifier or a list of identifiers, it is replaced by either \( @\text{Token}@ \) or \( @\text{Bubble}@ \), respectively. These sorts are declared in the Full Maude-specific module \( \text{OPERATOR-ATTRIBUTES} \), which must be imported.
The operators declared for the TOPO system are:
\[
\text{op poset_is_end : @Token@ \List{\DeclRelation}@ \@POSet@ .}
\]
\[
\text{op rel_<. : @Token@ @Token@ \@DeclRelation@ .}
\]
In order to be handled as valid system input (see the \[\text{in}\] rule in Section 4.1), each sort denoting a top metavariable (a metavariable corresponding to a top input, see Section 3) must be declared as a subsort of the predefined \( @\text{Input}@ \) sort:
\[
\text{subsort @\text{TopMetaVar}@ < @\text{Input}@ .}
\]
For the TOPO system, \( @\text{TopMetaVar}@ \) is replaced by \( @\text{POSet}@ \).
**SYSTEM-CMD-LANG-SIGN.** This module is used for command declarations. For each command a new operator defining its signature must be added. If, for instance, the form of the command is \( \text{resWord \ param1 \ param2} \), the operator defining its signature is:
\[
\text{op resWord_._ : @Param1@ \@Param2@ \@Command@ .}
\]
In most cases, commands receive basic identifiers or lists of basic identifiers as parameters, meaning that \( @\text{ParamX}@ \) is either \( @\text{Token}@ \) or \( @\text{Bubble}@ \), respectively. Commands are operators of the predefined \( @\text{Command}@ \) sort. The declaration of this sort is found in the Full Maude-specific \( \text{COMMANDS} \) module.
The TOPO system is able to interpret two commands - one for setting the default module defining the partial order relation and one for actually performing the topological sort:
\[
\text{op set’default’poset_. : @Token@ \@Command@ .}
\]
\[
\text{op tsort_. : @Bubble@ \@Command@ .}
\]
**SYSTEM-LANG-SIGN.** This module includes both the specification language signature and commands language signature modules. It is used at metalevel for defining the grammar module: \( \text{SYSTEM-GRAMMAR} \) (see Section 4.1).
**Result.** The \( \text{SYSTEM-SPEC-LANG-SORTS} \) module used for defining the specification language sorts and three other modules: \( \text{SYSTEM-SPEC-LANG-SIGN} \) for the specification language signature, \( \text{SYSTEM-CMD-LANG-SIGN} \) for the commands language signature and a module combining them both, \( \text{SYSTEM-LANG-SIGN} \).
Two other patterns are related to this one: \text{System Language Parser} (see Section 4.3) and \text{Error Handling} (see Section 4.4). They use the language signature in order to handle and validate the system input.
Known uses. All the Maude tools referred to in Section 1 define their signatures in the manner resembling the one described by this pattern. ITP defines the signature within the \texttt{SYSTEM-INTERFACE}-like module, using an internal defined 'Input sort, instead of deriving from the \texttt{@Input@} provided module.
In one or more dedicated *-SIGN-like modules, MTT, CRC, RTM and STR define commands. They all use the provided \texttt{@Command@} sort in order to declare commands. RTM and STR define unit input-like signature, the former using the provided \texttt{@Module@} sort and the latter using an internal defined sort. STR does not define a \texttt{SYSTEM-SORTS}-like module because it defines the external unit corresponding sorts within the \texttt{SYSTEM-LANG-SIGN}-like module.
### 4.3 System Language Parser
**Problem.** Develop a parser in Full Maude for transforming the input matching the system language grammar into a semantics in terms of the Maude language.
**Context.** We assume that the system specific loop is implemented (see Section 4.1) and the system signature is defined (see Section 4.2). The parsing of the input requires the use of the \texttt{metaParse} operator, already mentioned in Section 4.1.
The presentation on how to write a parser for the SSL is made for the following simple generic grammar (recall from Section 4.2 that \texttt{MetaVar*} represents a list of separated metavariables):
\[
\begin{align*}
\text{MetaVar} & : = \text{MetaExpr} \\
\text{MetaExpr} & : = \text{resWord1 MetaVar1 resWord2 MetaVar2 ... resWordEnd | MetaVar* | ...} \\
\end{align*}
\]
The grammar for the TOPO system specification language is:
\[
\begin{align*}
\text{POSet} & : = \text{poset Name is Relation* end} \\
\text{Name} & : = \text{Identifier} \\
\text{Relation} & : = \text{rel LHS < RHS} . \\
\text{LHS} & : = \text{Obj} \\
\text{RHS} & : = \text{Obj} \\
\text{Obj} & : = a | b | ... | z
\end{align*}
\]
**Solution.** Each top or partial input must be handled by its own parsing operator. Besides these operators, a set of rules which transfer the input to the corresponding top unit parsing operator must be implemented. This is achieved by defining a parsing-dedicated module and writing extra code for the previously defined \texttt{SYSTEM-STATE-HANDLING} module (see Section 4.1):
\[
\begin{align*}
\text{mod SYSTEM-LANG-PARSER is} & \quad \text{mod SYSTEM-STATE-HANDLING is} \\
\text{including SYSTEM-LANG-SIGN .} & \quad \text{including SYSTEM-LANG-PARSER .} \\
\text{define parsing operators for metavariables} & \quad \text{define parsing rules for each top input} \\
\text{endm} & \quad \text{... endm}
\end{align*}
\]
\texttt{SYSTEM-LANG-PARSER}. Let \texttt{TopMetaVar} and \texttt{PartialMetaVar} denote a top and a partial input, respectively, related to a unit. The parsing operators that must be added are:
parseTopMetaVar : Term Term ... Term -> MaudeCodeSort .
Here, *MaudeCodeSort* is the result of the parsing operation and represents the matching of the input unit to Maude specific code. For instance, a unit from SSL can be mapped to a Maude module.
A top input parsing operator must make calls to partial input parsing operators in this manner:
\[
\text{parseTopMetaVar}(T_1, T_2, \ldots, T_n) = \\
\text{parsePartialMetaVar}_1(T_1, \\
\text{parsePartialMetaVar}_2(T_2, \\
\ldots \\
\text{parsePartialMetaVar}_n(T_n, \text{initialMaudeCode})\ldots) .
\]
An input parsing operator *parseMetaVar* can handle the input in a few different ways:
a) it can use the provided term “as is” (e.g., as a QID, without any restrictions) and generate the related Maude code (see Fig. 1.a)
b) it can use *metaParse* in order to check if it corresponds to a previously defined signature and to generate the Maude code (see Fig. 1.b)
c) it may call other parsing operators if the term is the metarepresentation of a list of terms (see Fig. 1.c)
\[
a) \ceq \text{parseMetaVar}(T, \ldots) = \\
\quad \text{useQidDirectly}(\text{QID}) \\
\quad \text{if } T' := \text{token}[T] \land \\
\quad \text{QID} := \text{downTerm}(T', 'nil) \land \\
\quad \ldots .
\]
\[
b) \ceq \text{parseMetaVar}(T, \ldots) = \\
\quad \text{useParsedTerm}(S) \\
\quad \text{if } T' := \text{bubble}[T] \land \\
\quad \text{QL} := \text{downTerm}(T', 'nil) \land \\
\quad \text{RP} := \text{metaParse}(\text{MetaModule}, \\
\quad \text{QL}, '\text{DesiredSort}) \land \\
\quad \text{S} := \text{getTerm}(\text{RP}) \land \\
\quad \ldots .
\]
\[
c) \eq \text{parseMetaVar}(\text{\_\_}_[T], \ldots) = \\
\quad \text{parseTermList}(T) .
\]
Fig. 1. Partial input handling
For the TOPO system, the parsing operators decompose the input unit in order to obtain the elements of the partial order relation. The elements are transformed into Full Maude-specific equations and the unit itself is transformed into a Full Maude module. This module imports the *TOPO-DESCRIPTION* module introduced in Section 3 in order to be able to recognize the objects the relation is defined on. The parsing operators are:
\[
\begin{align*}
op\ \text{parsePOSet} : & \text{Term Term} \mapsto \text{Module} . \\
op\ \text{parseDeclRelation} : & \text{Term Module} \mapsto \text{Module} . \\
eq \text{parsePOSet}(T, T') = & \text{parseDeclRelation}(T', \\
\quad \text{addImports}(\text{including } '\text{BOOL} . \\
\quad \text{including } '\text{TOPO-DESCRIPTION} .), \\
\quad \text{setName}(\text{emptySModule}, \text{parseHeader}(T))) . \\
eq \text{parseDeclRelation}(\text{\_\_}_[T], M) = & \text{parseDeclRelation}(T, M) . \\
eq \text{parseDeclRelation}(\text{\_\_}_[T, TL], M) = & \text{parseDeclRelation}(\text{\_\_}_[TL], \text{parseDeclRelation}(T, M)) . \\
c\eq \text{parseDeclRelation}(\text{\_\_\_}_[, 'token[Q], 'token[Q'], M) = & \end{align*}
\]
addEqs(eq '_<_[T, T'] = 'true.Bool [none] ., M)
if RP := metaParse(upModule('TOPO-DESCRIPTION, false),
downTerm(Q, 'nil), 'Obj) ∧
RP :: ResultPair ∧
T := getTerm(RP) ∧
... --- same for RP', Q' and T'
SYSTEM-STATE-HANDLING. For a top input constructor of the form resWord1 MetaVar1 resWord2 MetaVar2 ... resWordN MetaVarN resWordEnd, defined in one of the system language signature modules, the following parsing rule is added:
crl [parseTopMetaVar] :
< ... input : ('resWord1_resWord2...resWordN_resWordEnd[T1, T2, ..., Tn]) ... > =>
< ... input : nilTermList ... >
if ... M:MaudeCodeSort := parseTopMetaVar(T1, T2, ..., Tn) ... .
Sometimes the parsing rule can handle the input by its own, with or without making use of the metaParse operator. This usually happens when parsing commands. Obviously, no extra parsing operators must be added in this case.
The rules added to the state handling module from the TOPO system are:
--- Transforms the input order specification unit into a Full Maude module
--- and adds it to the database.
crl [parsePOSet] :
< O : X@Database | db : DB, input : ('poset_is_end[T, T']),
output : nil, Atts > =>
< O : X@Database | db : instTermModule(getName(M), M, DB),
input : nilTermList, output : ('Introduced 'order 'spec. getName(M)), Atts >
if M := parsePOSet(T, T') .
--- Uses the procRew metalevel operator in order to apply the rewriting rule
--- that performs the topological sort on the objects provided on input.
crl [parseCommand--topo] :
< O : X@Database | db : DB, input : (Q[T]),
defaultPOSet : H, output : nil, Atts > =>
< O : X@Database | db : DB, input : nilTermList,
output : ('QL'), defaultPOSet : H, Atts >
if (Q == 'tsort_.) ∧ QL := downTerm(unBubble(T), 'nil) ∧
RP := metaParse(upModule('TOPO-DESCRIPTION, false), QL, 'ListOfObj) ∧
RP :: ResultPair ∧ M := getFlatModule(H, DB) ∧
QL' := procRew(H, M, T, none, DB) .
--- Sets the default module that specifies the partial order set.
crl [parseCommand--set-default-poset] :
< O : X@Database | db : DB, input : (Q[T]),
output : nil, defaultPOSet : H, Atts > =>
< O : X@Database | db : DB', input : nilTermList,
output : ('Default 'order 'set 'to: H'),
defaultPOSet : H', Atts >
if (Q == 'set'default'poset_.) ∧
< DB' ; H' := evalModExp(downTerm(unToken(T), 'nil), DB) .
Result. The SYSTEM-LANG-PARSER module defining parsing operators and the enrichment of the state handling module with rules dedicated to transforming top input into Maude code.
This pattern is related to Error Handling pattern (Section 4.4) because each parsing operation must be enhanced in order to detect and handle syntactically incorrect user input.
Known uses. The Maude tool which follows most of the steps described by this pattern is STR. It creates parsing rules for the unit-like input within the system state handling module. The operators dedicated to unit parsing are also declared in this module (no SYSTEM-LANG-PARSER is created). The other tool defining internal units (RTM) uses some parsing operators provided by Full Maude.
MTT, RTM and STR implement parsing rules for commands processing in the system state handling module. ITP and CRC implement parsing equations instead of rules. The parsing equations/rules from all tools make calls to internal defined processing operators or to operators provided by Full Maude.
4.4 Error Handling
Problem. Detecting and handling errors resulting from syntactically incorrect user input.
Context. User input should always be checked for errors. Otherwise, the result would be a bad system behavior or even a deadlock. Let us try to understand what happens when syntactically incorrect user input is provided.
As stated in Section 4.1, one of the predefined attributes of the system state structure is the \texttt{input} attribute. Its value is the metarepresentation of the current user input. At initialization, this attribute receives the \texttt{nilTermList} value. The system can only receive input when the \texttt{input} attribute has this value (check the \texttt{[in]} rule from Section 4.1 for details).
Let us assume, for example, that the user enters a command along with some parameters. The value of the \texttt{input} attribute becomes the metarepresentation of that command. If the system is not able to parse one of the provided parameters, the associated rule fails and the \texttt{input} attribute remains unchanged (meaning that the attribute does not receive the \texttt{nilTermList} value). We say that the state of the system is \textit{unstable} because it is not able to accept any user input.
Therefore an error handling mechanism able to avoid such situations is needed.
Solution. For a unit parsing rule \texttt{[parseTopMetaVar]}, a dual rule able to handle the error is created: \texttt{[parseTopMetaVar-error]}. The new rule fires only when \texttt{[parseTopMetaVar]} cannot be applied because of an input error. The error handling rule must stabilize the system and print an error message to the output.
Let us consider the parsing rule needed to call the \texttt{parseTopMetaVar} operation. As stated in Section 4.1, \texttt{metaParse} can be regarded as the basic metalevel parsing operation. Therefore \texttt{parseTopMetaVar} either calls this operation itself or some of its suboperators must do so. The \texttt{metaParse} operator fails when the returned value is not of sort \texttt{ResultPair}, but of sort \texttt{ResultPair?}. This is why a parsing operator that makes a direct call to \texttt{metaParse} must check its returned value and if a basic parsing failure occurs, an error must be generated.
In order to be able to receive error-prone parameters and return error values, a generic (top or partial) input operator \texttt{parseMetaVar} must be transformed into a Maude partial operator (see [6], Section 3.5):
An operator for error transmission must also be added:
\[
\text{op errorMetaVar : QidList} \rightarrow \text{[MaudeCodeSort]}.
\]
The propagation of an error is achieved by enforcing \text{parseMetaVar} to return the \text{errorMetaVar(error message)} value when one of the internal parsing steps fails. An internal parsing step can be either a \text{metaParse} call or a call to some other parsing operator \text{parseSubMetaVar}. For the latter case, the presented procedure must be applied recursively until all parsing operators are able to intercept and forward the error message:
--- direct call to \text{metaParse}
\[
\text{ceq parseMetaVar(...) = errorMetaVar(printSyntaxError(RP, QL))} \\
\text{if ... RP := metaParse(MetaModule, QL, 'DesiredSort') ∧ not(RP :: ResultPair) ... .}
\]
--- call to a parsing suboperator
\[
\text{eq parseMetaVar(..., errorSubMetaVariable(QL)) = errorMetaVar(QL).} \\
\text{ceq parseMetaVar(...) = errorMetaVar(QL)} \\
\text{if ... errorSubMetaVariable(QL) := parseSubMetaVariable(...) ... .}
\]
The error handling rule \text{[parseTopMetaVar-error]} modifies the system state by operating only on the input and output attributes. The rule checks if the value returned by \text{parseTopMetaVar} is \text{errorTopMetaVar(error message)}. If that is the case, then the input attribute receives the \text{nilTermList} value (in order to stabilize the system) and the QL error message is transferred to the output attribute of the current state (for feedback).
Sometimes the parsing rule calls \text{metaParse} directly. In this case the dual rule must check for the operator’s failure directly. This is what happens for the particular case in which the user input does not correspond with the system grammar (see Section 4.1). The dual of the input parsing rule \text{[in]} able to handle errors is:
\[
\text{crl [in-error]} : \\
\text{[ Q QL,} \\
\text{< o : SystemState | output : nil, Atts >,} \\
\text{QL’ ] =>} \\
\text{[ nil,} \\
\text{< o : SystemState |} \\
\text{output : ('Parsing 'error: printSyntaxError(RP, Q QL)), Atts >,} \\
\text{QL’]} \\
\text{if RP := metaParse(SYSTEM-GRAMMAR, Q QL, '@Input@)) ∧ not(RP :: ResultPair).}
\]
The TOPO system checks for errors when parsing the left hand side and right hand side terms of a relation element:
\[
\text{op errorDeclRelation : QidList} \rightarrow \text{[Module].} \\
\text{eq parseDeclRelation('__[TL, errorDeclRelation(QL)] = errorDeclRelation(QL).} \\
\text{ceq parseDeclRelation('rel_<_.['token[Q], 'token[Z]]', M) =} \\
\text{errorDeclRelation('Wrong 'LHS: printSyntaxError(RP, downTerm(Q, 'nil)))} \\
\text{if RP := metaParse(upModule('TOPO-DESCRIPTION, false),} \\
\text{downTerm(Q, 'nil), 'Obj) ∧ not RP :: ResultPair.} \\
\text{... --- same for the right hand side parsing error handling}
\]
The rule handling the error is:
crl [parsePOSet-error] :
< O : X@Database | input : ('poset_is_end[T,T'])), output : nil, Atts > =>
< O : X@Database | input : nilTermList, output : (QL), Atts >
if errorDeclRelation(QL) := parsePOSet(T, T') .
Result. A more stable system, able to detect and handle bad user input, making use of a freshly added error handling rule and some related error propagation operators.
Known uses. Most of the Maude tools referred to in Section 1 apply this pattern. ITP implements its own way of handling errors, but the idea of using kinds and implementing partial operations is the same.
CRC and RTM use the error handling operators provided by Full Maude. The operators are used internally in the same manner described in this pattern. SRT fully applies this pattern. The tool implements parsing rules able to detect errors. They make use of error handling operators for each top and partial input.
All the tools check if the user input corresponds with the system grammar. For CRC the check is made directly by the initial [in] rule. MTT and STR make this check in the same way described in the pattern. ITP and RTM add two new error checking rules - one for syntax errors and the other for ambiguous input (when the input can be parsed in more ways).
5 Pattern-based Iterations Used in the Development of Maude Metalanguage Applications
Maude metalanguage applications can be developed by using an iterative strategy. The idea is to build the base version of the system to be implemented and then, at each iteration to add new capabilities to that system. Every time an iteration is performed, the enriched system has to be tested for errors.
The base version of the system is a version the user can interact with. This goal is achieved by applying the User Interface pattern (see Section 4.1). At this point a minimal system state structure and the [in] and [out] rules are defined. These are basic rules that help creating the user interface. This version of the system can be tested by using the "loop init ." command. The actions performed during this step are illustrated in Fig. 2a).
The next step is to create the modules that will contain the system language signature. The structure of these modules is presented in the System Language Signature pattern (see Section 4.2). Also the module that will contain parser definitions is created according to the System Language Parser pattern (see Section 4.3). Fig. 2b) illustrates the activity diagram corresponding to this iteration.
The system development continues with the signature specification, according to a predefined grammar. Every time the system needs to be enhanced so that it can accept a new command or unit, the System Language Signature pattern must be applied. Handling the new input is achieved by enriching the system using the System Language Parser and Error Handling (see Section 4.4) patterns. The system
is tested by providing many instances of the freshly defined input and observing whether the response is the expected one or not. The actions performed during this iteration are illustrated in Fig. 2c).

a) User interface
b) System language signature
c) System input handling
Fig. 2. Activity diagrams for Metalanguage Applications development
6 Conclusions
This paper introduces four software patterns useful for developing Maude metalanguage applications for specifying and analyzing systems. The principles that guided us through defining a Maude pattern are:
- it solves a problem (captures solutions),
• it is a proved concept, not theories or speculation,
• the solution is not obvious (it generates a solution to a problem indirectly),
• it describes a relationship (deep system structure and mechanisms),
• the pattern has a significant human component (minimize human intervention).
Each pattern tackles a different problem that occurs during the implementation of a system. The User Interface pattern is applied when defining a specialized loop, the System Language Signature pattern is used for creating a new input language, the System Language Parser pattern is used for parsing units and commands written in the created language, and the Error Handling pattern is applied when checking for errors. An overview of the interaction between the modules created during the development of a metalanguage application using these patterns is illustrated in Fig. 3.
The patterns have been tested by a group of three undergraduate students with basic knowledge regarding the Maude system. In a matter of few hours they managed to implement a new system able to receive, parse and interpret user input corresponding to a minimal grammar.
These patterns compose a minimal set that can be extended if more complex systems need to be developed.
Acknowledgement
The authors would like to thank Professor Roberto Bruni and the anonymous reviewers for their valuable suggestions and comments. Many thanks addressed to Elena Naum, Ramona Dunca and Alexandru Ştefan for their assistance and suggestions.
References
|
{"Source-Url": "http://kops.uni-konstanz.de/bitstream/handle/123456789/46033/Goriac_2-287b40j1gr234.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 10723, "olmocr-version": "0.1.53", "pdf-total-pages": 18, "total-fallback-pages": 0, "total-input-tokens": 45238, "total-output-tokens": 12720, "length": "2e13", "weborganizer": {"__label__adult": 0.0002503395080566406, "__label__art_design": 0.0003514289855957031, "__label__crime_law": 0.0001920461654663086, "__label__education_jobs": 0.0005464553833007812, "__label__entertainment": 5.0187110900878906e-05, "__label__fashion_beauty": 0.00010323524475097656, "__label__finance_business": 0.00012612342834472656, "__label__food_dining": 0.00023698806762695312, "__label__games": 0.0003476142883300781, "__label__hardware": 0.0005273818969726562, "__label__health": 0.00022041797637939453, "__label__history": 0.00015687942504882812, "__label__home_hobbies": 6.490945816040039e-05, "__label__industrial": 0.0002651214599609375, "__label__literature": 0.00021779537200927737, "__label__politics": 0.00017333030700683594, "__label__religion": 0.0003399848937988281, "__label__science_tech": 0.006885528564453125, "__label__social_life": 6.210803985595703e-05, "__label__software": 0.005260467529296875, "__label__software_dev": 0.98291015625, "__label__sports_fitness": 0.00017940998077392578, "__label__transportation": 0.0003104209899902344, "__label__travel": 0.00013709068298339844}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 46532, 0.00567]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 46532, 0.68077]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 46532, 0.78792]], "google_gemma-3-12b-it_contains_pii": [[0, 1880, false], [1880, 5334, null], [5334, 8272, null], [8272, 10920, null], [10920, 13806, null], [13806, 16363, null], [16363, 18883, null], [18883, 21486, null], [21486, 24557, null], [24557, 27424, null], [27424, 30387, null], [30387, 33077, null], [33077, 36252, null], [36252, 39059, null], [39059, 41982, null], [41982, 42668, null], [42668, 44341, null], [44341, 46532, null]], "google_gemma-3-12b-it_is_public_document": [[0, 1880, true], [1880, 5334, null], [5334, 8272, null], [8272, 10920, null], [10920, 13806, null], [13806, 16363, null], [16363, 18883, null], [18883, 21486, null], [21486, 24557, null], [24557, 27424, null], [27424, 30387, null], [30387, 33077, null], [33077, 36252, null], [36252, 39059, null], [39059, 41982, null], [41982, 42668, null], [42668, 44341, null], [44341, 46532, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 46532, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 46532, null]], "pdf_page_numbers": [[0, 1880, 1], [1880, 5334, 2], [5334, 8272, 3], [8272, 10920, 4], [10920, 13806, 5], [13806, 16363, 6], [16363, 18883, 7], [18883, 21486, 8], [21486, 24557, 9], [24557, 27424, 10], [27424, 30387, 11], [30387, 33077, 12], [33077, 36252, 13], [36252, 39059, 14], [39059, 41982, 15], [41982, 42668, 16], [42668, 44341, 17], [44341, 46532, 18]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 46532, 0.0]]}
|
olmocr_science_pdfs
|
2024-12-08
|
2024-12-08
|
beab2d67387b5b0945e6654bbe686884cd927120
|
### Citation
### As Published
http://dx.doi.org/10.1145/1755913.1755947
### Publisher
Association for Computing Machinery (ACM)
### Version
Author’s final manuscript
### Citable link
http://hdl.handle.net/1721.1/72691
### Terms of Use
Creative Commons Attribution-Noncommercial-Share Alike 3.0
### Detailed Terms
http://creativecommons.org/licenses/by-nc-sa/3.0/
Locating Cache Performance Bottlenecks Using Data Profiling
Aleksey Pesterev Nickolai Zeldovich Robert T. Morris
Massachusetts Institute of Technology Computer Science and Artificial Intelligence Lab
{alekseyp, nickolai, rtm}@csail.mit.edu
Abstract
Effective use of CPU data caches is critical to good performance, but poor cache use patterns are often hard to spot using existing execution profiling tools. Typical profilers attribute costs to specific code locations. The costs due to frequent cache misses on a given piece of data, however, may be spread over instructions throughout the application. The resulting individually small costs at a large number of instructions can easily appear insignificant in a code profiler’s output.
DProf helps programmers understand cache miss costs by attributing misses to data types instead of code. Associating cache misses with data helps programmers locate data structures that experience misses in many places in the application’s code. DProf introduces a number of new views of cache miss data, including a data profile, which reports the data types with the most cache misses, and a data flow graph, which summarizes how objects of a given type are accessed throughout their lifetime, and which accesses incur expensive cross-CPU cache loads. We present two case studies of using DProf to find and fix cache performance bottlenecks in Linux. The improvements provide a 16–57% throughput improvement on a range of memcached and Apache workloads.
Categories and Subject Descriptors C.4 [Performance of Systems]: Measurement Techniques; D.4.8 [Operating Systems]: Performance
General Terms Experimentation, Measurement, Performance
Keywords Cache Misses, Data Profiling, Debug Registers, Statistical Profiling
1. Introduction
Processors can consume data much faster than off-memory can supply it. While on-chip caches and prefetching can bridge some of this gap, it is nevertheless the case that programs often spend a significant fraction of their run-time stalled waiting for memory. Multicore chips will likely make this problem worse, both because they may increase total demand for data and because they allow for the possibility of cache misses due to contention over shared data. Understanding why software is suffering cache misses is often a pre-requisite to being able to improve the software’s performance.
Following Hennessy and Patterson [13], the reasons for cache misses can be classified as follows. Compulsory misses are those taken the very first time a memory location is read. True sharing misses are those taken on core X as a result of a write from core Y invalidating data needed on X. False sharing misses are those taken on core X as a result of a write from core Y to a different part of a cache line needed by X. Conflict misses are those taken because a core uses, in rapid succession, too many distinct items of data that happen to fall in the same associativity set. Finally, capacity misses are those taken because the working set of the software is larger than the total cache capacity.
Identifying the specific causes of cache misses can be difficult, even with tools such as CPU time profilers or hardware-counter based cache miss profilers. For example, if many different points in a program read a particular variable, and the variable is frequently modified, the miss costs will be distributed widely and thinly over a CPU time profile; no one profile entry will attract the programmer’s attention. Capacity misses may have the same lack of focused symptoms, because a cache that is too small for the active data will cause misses throughout the software; even if the programmer realizes that the cache miss rate is higher than it should be, it is rarely clear what data is contributing to the too-large working set. Conflict misses similarly can be difficult to spot and to attribute to specific items of data.
Creating a sharp distinction between misses due to invalidations, capacity misses, and associativity misses is important because the strategies to reduce misses are different in the three cases. Associativity conflicts can usually be fixed by allocating memory over a wider range of associativity sets. False cache line sharing can be fixed by moving the falsely shared data to different cache lines. True sharing can sometimes be reduced by factoring data into multiple pieces that usually need only be touched by a single CPU, or by re-structuring software so that only one CPU needs the data. Avoiding capacity misses may require changing the order.
in which data is processed to increase locality, or imposing admission control on the number of concurrent activities.
This paper describes a new tool called DProf whose goal is to help programmers understand and eliminate cache misses. DProf addresses two core challenges: identifying the causes of misses, and presenting those causes in a way that helps the programmer eliminate them. DProf uses performance monitoring hardware to gradually accumulate traces of running software’s references to memory addresses. These traces allow DProf to categorize all types of cache misses. Associativity misses are identifiable as repeated cycling of the same addresses in a single associativity set. True and false sharing are identifiable by comparing traces from different cores. DProf identifies capacity misses by estimating the working set size from the traces.
Once DProf has categorized cache misses, it identifies the types of data participating in each miss. DProf allows the programmer to navigate four different views of the cache misses incurred by the software’s data types. The highest level view is a “data profile”: a list of data types, sorted by how many misses they suffer. The “miss classification” view indicates the kinds of misses incurred by each data type. The “working set” view shows which data types were most active, how many objects of each type were active, and which associativity sets those objects used; this information helps diagnose capacity and associativity misses. Finally, to find instances of true and false sharing, the “data flow” view shows when data moves from one CPU to another.
We have implemented DProf within the Linux kernel, using Linux’s kernel allocator to help identify the type of each memory location that misses. The implementation uses the AMD instruction-based sampling (IBS) hardware [11] and x86 debug registers [14] to acquire a trace of references.
To evaluate the effectiveness of DProf, we present a number of case studies. Each involves a workload that generates significant misses within the kernel. In each case, existing tools such as OProfile do not usefully identify the cause of the misses. We show that DProf does identify them, and presents the programmer with information that is useful in understanding and eliminating the misses.
The rest of this paper starts with a description of the views that DProf provides, in Section 2. Section 3 describes how DProf generates those views, and Section 4 details our data collection mechanisms for x86 processors. Section 5 uses case studies to show how DProf can be used to find a range of problems related to cache misses in the Linux kernel. Section 6 compares DProf to related work, Section 7 mentions limitations and directions for future research, and Section 8 concludes.
2. DProf Views
After a programmer has run software with DProf profiling, DProf offers the programmer the following views:
**Data Profile** The highest level view consists of a data profile: a list of data type names, sorted by the total number of cache misses that objects of each type suffered. As a convenience, the data profile view also indicates whether objects of each type ever “bounce” between cores. This view is most useful when the design and handling of each data type is what causes misses for that type. A data profile view is less useful in other situations; for example, if the cache capacity is too small, all data will suffer misses. Aggregation by type helps draw attention to types that suffer many misses in total spread over many objects. The “data profile view” columns of Tables 4, 7, and 8 show examples of this kind of view.
**Miss Classification** This view shows what types of misses are most common for each data type. For example, objects of type skbuff might incur mostly capacity misses, objects of type futex mostly associativity conflict misses, and objects of type pktstat both true and false sharing misses. For capacity or conflict misses, the programmer would look next at the working set view; for sharing misses, the data flow view.
**Working Set** This view summarizes the working set of the profiled software, indicating what data types were most active, how many of each were active at any given time, and what cache associativity sets are used by each data type. This global knowledge of cache contents is important to track down the causes of capacity and conflict misses, which are caused by different data elements evicting each other from the cache. The working set column of Tables 4, 7, and 8 illustrate an example of this kind of output, although the full working set view also includes a distribution of data types by cache associativity sets. An example cache associativity histogram for one data type is shown in Figure 1. Using the working set view, the programmer can determine if the software is using too many distinct data items of a particular type at once. The distribution of data types by associativity set can also help determine if certain data types are aligned with each other, causing conflict misses.
**Data Flow** Finally, the data flow view shows the most common sequences of functions that reference particular objects of a given type. The view indicates points at which an object (or its cache lines) moves between cores, incurring cache misses due to either false or true sharing. Programmers can also use the data flow view to explore how a program processes a particular type of data, as we will illustrate in one of the case studies. Figure 2 shows an example data flow view.
3. Generating Views
DProf collects two kinds of data to help it generate views. The first kind is *path traces*. Each path trace records the life history of a particular data object, from allocate to free, in terms of the sequence of instruction locations that read or write the object. This sequence may be from a single thread...
### Table 1.
A sample path trace for a particular data type and execution path. This path trace is for a network packet structure and the transmit path. The CPU change flag indicates whether that program counter was encountered on the same CPU as the previous one, or on a different CPU. The offset indicates the offset into the data structure that was accessed at this program counter location. The cache hit probabilities indicate the percentage of time that memory access was satisfied using different caches in the system, and the access time indicates the average time spent waiting for that memory reference. An execution path is defined by the sequence of program counter values and CPU change flags, and DProf keeps track of how frequently each execution path is seen for each data type.
<table>
<thead>
<tr>
<th>Average Timestamp</th>
<th>Program Counter</th>
<th>CPU Change</th>
<th>Offsets</th>
<th>Cache Hit Probability</th>
<th>Access Time</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>kalloc()</td>
<td>no</td>
<td>0–128</td>
<td>—</td>
<td>0</td>
</tr>
<tr>
<td>5</td>
<td>tcp_write()</td>
<td>no</td>
<td>64–128</td>
<td>100% local L1</td>
<td>3 ns</td>
</tr>
<tr>
<td>10</td>
<td>tcp_xmit()</td>
<td>no</td>
<td>24–28</td>
<td>100% local L1</td>
<td>3 ns</td>
</tr>
<tr>
<td>25</td>
<td>dev_xmit()</td>
<td>yes</td>
<td>24–28</td>
<td>95% foreign cache</td>
<td>200 ns</td>
</tr>
<tr>
<td>50</td>
<td>kfree()</td>
<td>no</td>
<td>0–128</td>
<td>—</td>
<td>0</td>
</tr>
</tbody>
</table>
### Figure 1.
First level cache associativity set histogram of data accesses to 1024 byte network packet buffers. The y-axis represents the number of unique cache lines accessed in one associativity set. The gaps represent lost opportunities to spread out references over multiple associativity sets. They are formed because in Linux all 1024 byte packet buffers are aligned so that each byte of the buffer can only fall into 32 different associativity sets.
DProf is a statistical profiler and assumes a workload that is uniform over time. Without a cyclic workload a statistical profiler cannot capture enough samples to characterize the workload. This assumption is similarly made by other time and hardware-counter based statistical profilers.
Path traces are constructed by combining cache miss data generated by hardware-counters with traces of references to data gathered using hardware debug registers. Debug registers can be setup to trigger interrupts every time a particular memory location is accessed. We will describe how the path traces and address sets are collected in the next section, but for now we focus on the problem of generating different views using these data sources.
### 3.1 Data Profile
Recall that a data profile reflects the miss rates and CPU bouncing information for a given type (for example, see Tables 4, 7, and 8). To construct a data profile for type \( T \), DProf combines all of the path traces for \( T \). The CPU bounce flag in \( T \)’s data profile will be set if any path trace for \( T \) indicates a CPU change. The miss rate for \( T \)’s data profile is the average miss rate to DRAM or other CPUs’ caches encountered on all of the execution paths, according to the path traces, weighted by the frequency with which that path is observed.
### 3.2 Working Set
The working set view presents two kinds of information. First, an indication of whether some cache associativity sets suffer many more misses than others (suggesting associativity conflicts), and the data types involved in those misses. Figure 1 shows one such histogram for network packet buffers. Second, an estimate of which types are most common in the cache, to help diagnose capacity misses.
DProf runs a simple cache simulation to generate this information. DProf randomly picks objects from the address set to map objects to specific associativity sets in the cache. Thus, it is sufficient to store addresses modulo the maximum cache size in this data structure.
DProf uses the address set to map objects to specific associativity sets in the cache. Thus, it is sufficient to store addresses modulo the maximum cache size in this data structure.
working set view reports not only the most common data ACK, or data packets. If the cache is full of skbuff (Device DMA could cause a compulsory miss, but DMA-including both true sharing and false sharing), conflict Thus, DProf assumes there are no compulsory misses. To help catch such a problem, DProf repeats each miss in each path trace, DProf searches backwards in the object are accessed disjointly on multiple CPUs but share the same cache line. To help catch such a problem, DProf repeats the above procedure but searches backwards for writes to the entire cache line on a different CPU. Due to profiling limitations, DProf does not detect false sharing if multiple objects share the same cache line.
**Conflict Misses** An N-way set associative cache is composed of multiple associativity sets. When a cache line is added to the cache, the address of the cache line is used to deterministically calculate which set the cache line maps to. Each set can hold up to N cache lines simultaneously. Conflict misses take place when the software frequently accesses more than N different cache lines that map to the same associativity set. To detect conflict misses, DProf must first determine what associativity sets a particular data type falls into, and then determine whether those associativity sets are used to store significantly more data than other sets.
To determine the associativity sets used by type T, DProf adds the addresses from T’s address set to the offsets accessed in T’s path traces, and maps the resulting absolute addresses into associativity sets. To determine whether a particular associativity set is suffering from conflict misses, DProf computes the histogram of associativity sets, described earlier in the working set view. DProf then checks whether that associativity set is assigned more cache lines than it can hold, and if so, whether the number of cache lines assigned to it is much higher than the average number of cache lines assigned to other associativity sets. (In our prototype, we check if the number of cache lines is a factor of 2 more than average.) If both of those conditions hold, DProf marks that associativity set as suffering from conflict misses.
**Capacity Misses** Capacity misses occur when the total amount of data actively used by the software (the working set) is greater than the size of the cache. DProf helps the programmer understand capacity misses by estimating the primary contents of the working set.
There is overlap between conflict and capacity misses, since at a detailed level capacity misses are caused by associativity conflicts. DProf distinguishes between the two cases heuristically: if only a few associativity sets have lots of conflicts, DProf attributes the misses to conflicts; if most associativity sets have about the same number of conflicts, DProf indicates that the problem is capacity.
### 3.3 Miss Classification
For the miss classification view, DProf uses path traces to classify cache misses into three categories: invalidations (including both true sharing and false sharing), conflict misses, and capacity misses. Although compulsory misses are often treated as a separate class of cache miss, in practice all memory on a real system has been accessed by a CPU at some point in the past, so there are almost no compulsory misses. (Device DMA could cause a compulsory miss, but DMA-to-cache is common and would largely avoid such misses.) Thus, DProf assumes there are no compulsory misses.
**Invalidations** In invalidations occur when one core has data in its cache and a second core writes the data; the processor’s cache coherence protocol removes the data from the first core’s cache, and that core’s next access to the data will miss. DProf uses path traces to identify misses due to invalidations, and thus to identify instructions that cause invalidations. For each miss in each path trace, DProf searches backwards in the trace for a write to the same cache line from a different CPU. If there is such a write, then the miss is due to invalidation.
One type of false sharing occurs when two fields in an object are accessed disjointly on multiple CPUs but share the same cache line. To help catch such a problem, DProf repeats the above procedure but searches backwards for writes to the entire cache line on a different CPU. Due to profiling limitations, DProf does not detect false sharing if multiple objects share the same cache line.
**Conflict Misses** An N-way set associative cache is composed of multiple associativity sets. When a cache line is added to the cache, the address of the cache line is used to deterministically calculate which set the cache line maps to. Each set can hold up to N cache lines simultaneously. Conflict misses take place when the software frequently accesses more than N different cache lines that map to the same associativity set. To detect conflict misses, DProf must first determine what associativity sets a particular data type falls into, and then determine whether those associativity sets are used to store significantly more data than other sets.
To determine the associativity sets used by type T, DProf adds the addresses from T’s address set to the offsets accessed in T’s path traces, and maps the resulting absolute addresses into associativity sets. To determine whether a particular associativity set is suffering from conflict misses, DProf computes the histogram of associativity sets, described earlier in the working set view. DProf then checks whether that associativity set is assigned more cache lines than it can hold, and if so, whether the number of cache lines assigned to it is much higher than the average number of cache lines assigned to other associativity sets. (In our prototype, we check if the number of cache lines is a factor of 2 more than average.) If both of those conditions hold, DProf marks that associativity set as suffering from conflict misses.
**Capacity Misses** Capacity misses occur when the total amount of data actively used by the software (the working set) is greater than the size of the cache. DProf helps the programmer understand capacity misses by estimating the primary contents of the working set.
There is overlap between conflict and capacity misses, since at a detailed level capacity misses are caused by associativity conflicts. DProf distinguishes between the two cases heuristically: if only a few associativity sets have lots of conflicts, DProf attributes the misses to conflicts; if most associativity sets have about the same number of conflicts, DProf indicates that the problem is capacity.
### 3.4 Data Flow
DProf constructs the data flow view for a particular type T by combining the execution paths seen in T’s path traces into a single graph. All path traces start from an allocation routine like kalloc(), and end in a deallocation routine like kfree(). As a result, DProf can always construct a data flow graph from kalloc() to kfree(). When multiple execution paths share a prefix or suffix, DProf can merge the common program counter values into a shared sequence of nodes in the graph.
Table 2. An access sample that stores information about a memory access.
<table>
<thead>
<tr>
<th>Field</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>type</td>
<td>The data type containing this data.</td>
</tr>
<tr>
<td>offset</td>
<td>This data’s offset within the data type.</td>
</tr>
<tr>
<td>ip</td>
<td>Instruction address responsible for the access.</td>
</tr>
<tr>
<td>cpu</td>
<td>The CPU that executed the instruction.</td>
</tr>
<tr>
<td>miss</td>
<td>Whether the access missed.</td>
</tr>
<tr>
<td>level</td>
<td>Which cache hit.</td>
</tr>
<tr>
<td>lat</td>
<td>How long the access took.</td>
</tr>
</tbody>
</table>
4. Collecting Path Traces and Address Sets
As Section 3 outlined, DProf relies on two data structures to generate its views: the path traces and the address set. DProf constructs an address set by instrumenting the allocator to record allocation and deallocation of all objects, along with their type information.
DProf pieces together path traces by sampling raw data from CPU performance monitoring hardware as a workload executes. DProf combines the raw data into a set of path traces, one per data type / path combination. Because DProf samples, its path traces are statistical estimates.
DProf collects two kinds of raw data: access samples and object access histories. Each access sample records information for a memory-referencing instruction execution randomly chosen by the hardware, and includes the instruction address, data memory address, whether the memory access hit in the cache, and the memory access latency (for misses). An object access history is a complete trace of all instructions that read or wrote a particular data object, from when it was allocated to when it was freed. These two types of raw data are dictated by the performance monitoring hardware provided by the CPUs we use. In particular, the hardware that collects object access histories does not record cache miss information. Combining access samples with object access histories allows construction of path traces.
DProf performs two additional steps in generating path traces. First, it finds the type of the data referenced by each access sample, to help it decide which object access histories each access sample might be relevant to. Second, it aggregates object access histories that refer to the same data type and involve the same path of instructions.
Currently DProf stores all raw samples in RAM while profiling. Techniques from DCPI [4] could be used to transfer samples to disk while profiling. The following subsections detail how DProf collects and combines the raw data.
4.1 Access Samples
To gather information about cache misses, DProf samples data accesses. Each sampled data access is saved as an “access sample” shown in Table 2. The output of a data access profiling session is a collection of access samples that captures the software’s most common data accesses and how many of the accesses missed in the cache.
DProf uses Instruction Based Sampling (IBS) [11] provided by AMD processors to collect access samples. IBS is a hardware feature that allows detailed CPU execution sampling. IBS works by randomly tagging an instruction that is about to enter the CPU’s pipeline. As a tagged instruction moves through the pipeline, built-in hardware counters keep track of major events like cache misses, branch mispredictions, and memory access latencies. When the tagged instruction retires, the CPU issues an interrupt alerting the operating system that an IBS sample is ready. IBS reports the instruction address for each sample and the physical and virtual memory addresses for instructions that access memory. IBS tagging is not completely random due to stalling instructions. IBS results are biased toward instructions that spend more time in a pipeline stage.
After initializing the IBS unit, DProf receives interrupts on each new IBS sample. The DProf interrupt handler creates a new access sample and fills it with the data described in Table 2.
4.2 Address to Type Resolution
To construct an access sample, DProf needs to compute the type and offset that corresponds to the memory address. The type information is necessary to aggregate accesses to objects of the same type, and to differentiate objects of different types placed at the same address by the memory allocator.
DProf assumes C-style data types, whose objects are contiguous in memory, and whose fields are located at well-known offsets from the top-level object’s base address. DProf implements a memory type resolver whose job is to generate a type and offset for any memory address at runtime. For a given address, the resolver finds the type of object that the address belongs to, and the base address of that object. Subtracting the address from the base address gives the offset into the type, which is used to infer the field.
The method for finding the type and base address of an address depends on whether the address refers to dynamically-allocated or statically-allocated memory. For statically-allocated memory, the data type and the object base address can be found by looking at the debug information embedded in the executable.
For dynamically-allocated memory, DProf modifies the allocator to keep track of the type of all outstanding allocations. The Linux kernel’s allocator already has this information, since a separate memory pool is often used for each type of object. As a result, DProf can ask the allocator for the pool’s type, and the base address of the allocation that includes a given address. We are exploring off-line assembly typing techniques for associating types with dynamically-allocated memory from shared memory pools, and for allocators outside of the Linux kernel. For now, our approach has been to manually annotate with type information the few allocations that come from a generic pool.
4.3 Object Access Histories
Object access history profiling works by recording all instruction pointers that access a given object during that object’s lifetime. An object access history is a collection of elements shown in Table 3.
DProf uses debug registers provided by modern AMD and Intel CPUs that generate an interrupt for every access to a given address. Current hardware provides a limited number of these debug registers, each covering up to eight bytes of contiguous memory at a time. As a result, DProf must use debug registers to monitor a small part of each data object at a time, and to piece together the resulting offset access histories into a complete object access history.
DProf monitors one object at a time, on all CPUs. When a free debug register becomes available, DProf decides what type of object it would like to monitor, focusing on the most popular objects found in the access samples. DProf picks an offset within that data type to monitor, based on what offsets have not been covered yet. DProf then cooperates with the kernel memory allocator to wait until an object of that type is allocated. When an allocation happens, DProf configures the debug registers on every CPU to trace the given offset within the newly-allocated memory region, until the object is eventually freed, and the debug register is released.
The CPUs interrupt on each load and store to the currently monitored object and offset. The DProf interrupt handler creates a record of the access on each interrupt, as shown in Table 3. The offset field is known at allocation time, the ip and cpu fields are known at interrupt-time, and time field is computed using the RDTSC timestamp counter, relative to the object’s initial allocation time.
In order to build up an object access history for all offsets in a data type, DProf must determine how accesses to different offsets should be interleaved with one another. To do so, DProf performs pairwise sampling using pairs of debug registers, configured to track two different offsets within the same object. DProf samples all possible pairs of offsets within an object, and then combines the results into a single access history by matching up common access patterns to the same offset. While this process is not perfect, access patterns for most data types are sufficiently repetitive to allow DProf to perform this merging.
Table 3. An element from an object access history for a given type, used to record a single memory access to an offset within an object of that type.
<table>
<thead>
<tr>
<th>Field</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td>offset</td>
<td>Offset within data type that’s being accessed.</td>
</tr>
<tr>
<td>ip</td>
<td>Instruction address responsible for the access.</td>
</tr>
<tr>
<td>cpu</td>
<td>The CPU that executed the instruction.</td>
</tr>
<tr>
<td>time</td>
<td>Time of access, from object allocation.</td>
</tr>
</tbody>
</table>
To detect false sharing of a cache line used by multiple objects, DProf could observe cases when two objects share the same cache line and profile both at the same time. DProf currently does not support this mode of profiling.
4.4 Path Trace Generation
Once the access samples and object access histories have been collected, DProf combines the two data sets to create path traces for each data type. First, DProf aggregates all access samples that have the same type, offset, and ip values, to compute the average cost of accessing memory of a particular type by a given instruction. Aggregation takes place at the type level, as opposed to the type instance level, because there are not enough access samples collected per second to capture enough data about particular instances of a type. Then, DProf augments object access histories with data from the access samples, by adding the miss, level, and lat data from the access sample to object access history records with the same type, offset, and ip values. Finally, DProf combines all augmented object access histories that have the same execution path (same sequence of ip values and equivalent sequence of cpu values) by aggregating their time, miss, level, and lat values. All of the combined histories for a given type are that type’s path trace.
5. Evaluation
This section evaluates DProf by using it to find cache performance problems in the Linux 2.6.30 kernel for two workloads, Apache and memcached. The hardware involved is a 16-core AMD machine (four four-core Opteron chips) with an Intel 10GB Ethernet card (IXGBE) [10]. Each core has an L1 and L2 cache; the four cores on each chip share one L3 cache. An L1 hit costs 3 cycles, an L2 hit costs 14 cycles, and an L3 hit costs 50 cycles. A miss in the L3 costs 200-300 cycles to fetch the data from RAM or from another chip [6]. Sixteen other machines generate load via a 24-port 1GB switch with a 10GB Ethernet interface.
The IXGBE has 16 TX and RX queues. Each queue can be set to interrupt one specific core. The card hashes header fields of incoming packets to choose the queue. We configured the card to ensure that each load-generation host’s packets went to a different core, in order to reduce contention over a number of kernel locks and data structures. We also modified the kernel to avoid using global data structure locks in subsystems like the directory entry cache and the SLAB memory allocator. These changes were necessary to reduce lock contention—a first effect performance bottleneck—and bring data contention to the forefront.
This section presents two case studies of how DProf helps find the sources of costly cache misses, and then evaluates DProf’s profiling overhead. The case studies compare how precisely DProf and two existing popular tools, lock_stat and OProfile, direct the programmer’s attention to the underlying causes of cache misses.
5.1 Case Study: True Sharing
Memcached [2] is an in-memory key-value store often used to speed up web applications. A distributed key-value store can be created by running multiple instances of memcached and having clients deterministically distribute keys among all available servers.
For this case study, the test machine ran 16 instances of memcached. Each instance used a different UDP port and was pinned to one core. Separate memcached processes were used to avoid scalability bottlenecks with threaded memcached. Each load generating machine ran a UDP memcached client querying the same memcached instance, with different clients querying different instances. The Ethernet hardware was configured to deliver receive packet interrupts to the appropriate server core. Each UDP client repeatedly asked for one nonexistent key.
This configuration aimed to isolate all data accesses to one core and eliminate cross core sharing of data that results in both contention for locks and cache misses. Even though we configured the experiment to reduce cross core sharing, we were still not getting linear speed up running memcached.
5.1.1 Profiling with DProf
Table 4 shows part of the data profile generated by DProf. A few kernel objects had a high concentration of cache misses. In addition, the same objects were bouncing between cores. With a high proportion of cache misses, the size-1024 objects are a good place to start the analysis. These objects hold packet payload. The DProf data flow view shows that many of these objects move from one core to another between a call to dev_queue_xmit and dev_hard_start_xmit. This means that individual packets are handled by multiple cores during transmit processing, rather than by one as expected. The size-1024 objects are only the packet payloads; per-packet skb structures are used to store bookkeeping information about each packet. Since skbufs are on the list and are also bouncing, they are worth looking at next.
Figure 2 shows a snippet of the data flow view generated by DProf for skbufs. The view indicates that skbufs on the transmit path jump from one core to another between a call to pfifo_fast_enqueue and pfifo_fast_dequeue. Both of these functions are part of the Qdisc Linux subsystem that is used to schedule packet transmission. Packets are placed on the head of the queue and are taken off the queue when the card is ready to transmit them. The IXGBE driver was configured with 16 hardware transmit queues. In principle, each core should be able to transmit a packet without contending for locks by placing the packet onto a “local” queue dedicated to its use. Since skbufs jump to a different core at this point, this is apparently not happening.
Now that we have an idea of what the problem is, we need to find why packets are not placed on the local queue. The data flow graph limits the scope of the search: we only need
Figure 2. Partial data flow view for skb objects in memcached as reported by DProf. The thick line indicates a transition from one core to another. Darker boxes represent functions with high cache access latencies.
Table 4. Working set and data profile views for the top data types in memcached as reported by DProf. The percent reduction column shows the reduction in L3 misses caused by changing from a remote to a local queue selection policy. The number of L3 misses for size-1024 increased with the local policy.
to look at functions above pfifo_fast_enqueue to find why packets are not placed on to the local queue. Fortunately, we do not need to look far for the problem. Looking at the skb_txd_HASH, it is easy to spot that the transmit queue is chosen by hashing the content of the skbuff.
The problem is that the IXGBE driver does not provide its own custom queue selection function that overrides the suboptimal default. In the memcached benchmark it is best for the system to choose the local queue rather than balancing transmit load by hashing to a remote queue. Modifying the kernel in this way increased performance by 57%.
Changing the queue selection policy halved the number of L2 and L3 misses, as Table 5 shows. Many data types share in this reduction. The last column in Table 4 shows the percent reduction in L3 cache misses for the top data types.
5.1.2 Analysis using Lock_stat
We wanted to see how easy it would be to find the same problem using lock_stat. Lock_stat reports, for all Linux kernel locks, how long each lock is held, the wait time to acquire the lock, and the functions that acquire and release the lock. Lock_stat found four contended kernel locks shown in Table 6. Contention for locks implies that the memory protected by the lock is accessed on multiple CPUs, and might be a bottleneck. To try to use lock_stat’s results to understand why memcached wasn’t scaling, we looked at each lock it reported.
The first reported lock protects part of the event poll system call interface. In the memcached benchmark it might be safe to assume that socket descriptors generate most events. The event poll subsystem uses wait queues internally, so the “epoll” and “wait queue” lock uses might be related. Without call stacks, it is hard to tell how the two locks relate, or how other parts of the kernel might be using events or wait queues.
Contention over the SLAB cache lock indicates that data is allocated on one CPU and deallocated on another. cache_alloc_refill is called to refill the exhausted per-core local cache of free objects. The call to _drain_alien_cache shows that objects are frequently freed on a core other than the original allocating core, requiring the object to be placed back on the original core’s free lists. It is not clear from the lock_stat output what type of objects are being allocate and deallocated.
The Qdisc lock contention indicates that multiple cores are touching the same packet transmit queue. The dev_queue_xmit function places packets onto a queue and the _qdisc_run function takes them off. Studying the dev_queue_xmit function, we could make the same conclusion as we did with DProf. The fact that this is possible is something of a lucky coincidence for lock_stat, since there is no real reason why the choice of queue and the mechanics of placing the packet on that queue had to be in the same function. Often such pairs of actions are not in the same place in the code, and lock_stat often doesn’t identify the point in the code that effectively decides to share data with another core. DProf’s data flow views identify these problems more explicitly, limiting the functions that need to be examined to the ones that used the data just before the data switched to a different core.
5.1.3 Profiling with OProfile
OProfile [19] is an execution profiler, reporting the cost of each function or line of code. Table 12 shows the output of OProfile for the memcached workload. OProfile reports over 33 functions with more than 1% of the samples. It is hard to tell which functions are potential performance problems, since none stand out. The memcached benchmark is forcing the kernel to allocate, transmit, and deallocate millions of packets per second; it is reasonable for ixgbe_clean_rx_irq, kfree, and kmem_cache_free to be at the top of the list. Before getting to the interesting dev_queue_xmit function, the programmer must first examine the first 10 functions. Even when inspecting dev_queue_xmit, the programmer would
<table>
<thead>
<tr>
<th>Queue Selection Policy</th>
<th>Requests per Second</th>
<th>L2 Misses per Request</th>
<th>L2 Miss Rate</th>
<th>L3 Misses per Request</th>
<th>L3 Miss Rate</th>
</tr>
</thead>
<tbody>
<tr>
<td>Remote</td>
<td>1,100,000</td>
<td>80</td>
<td>1.4%</td>
<td>70</td>
<td>1.2%</td>
</tr>
<tr>
<td>Local</td>
<td>1,800,000</td>
<td>40</td>
<td>0.7%</td>
<td>30</td>
<td>0.5%</td>
</tr>
</tbody>
</table>
Table 5. Cache misses per request and cache miss rates for the L2 and L3 caches. Results are shown running memcached for both transmit queue selection policies. These numbers were gathered using hardware performance counters to collect cache miss and data access counts.
<table>
<thead>
<tr>
<th>Lock Name</th>
<th>Wait Time</th>
<th>Overhead</th>
<th>Functions</th>
</tr>
</thead>
<tbody>
<tr>
<td>epoll lock</td>
<td>0.66 sec</td>
<td>0.14%</td>
<td>sys_epoll_wait, ep_scan_ready_list, ep_poll_callback</td>
</tr>
<tr>
<td>wait queue</td>
<td>0.57 sec</td>
<td>0.12%</td>
<td>__wake_up_sync_key</td>
</tr>
<tr>
<td>Qdisc lock</td>
<td>1.21 sec</td>
<td>0.25%</td>
<td>dev_queue_xmit, __qdisc_run</td>
</tr>
<tr>
<td>SLAB cache lock</td>
<td>0.05 sec</td>
<td>0.01%</td>
<td>cache_alloc_refill, __drain_alien_cache</td>
</tr>
</tbody>
</table>
Table 6. Lock statistics reported by lock_stats during a 30 second run of memcached. The wait time is a sum over all 16 cores.
likely focus on the locking problem, just as in the lock_stat analysis.
The OProfile output mentions 6 functions that deal with packet transmission. Another 14 are generic functions that may manipulate packets. Even if the programmer realizes that the problem is packets placed on a remote queue, up to 20 functions would need to be studied to understand why this is happening.
OProfile does generate call graphs that present information similar to data flow views. For the purposes of this analysis, however, call graphs lack the continuity of DProf data flows when objects are placed in data structures and later retrieved, as with queues.
As shown in column 3 of Table 12, the reduction in L2 misses after changing the queue selection policy is spread over most of the top functions. That is, the 57% improvement is not concentrated in a few functions in a way that would be clear from OProfile output. By attributing miss costs to data types, rather than functions, DProf identifies the source of the performance problem more clearly than OProfile.
5.2 Case Study: Working Set
For this case study we configure the test machine to run the Apache [1] web server. 16 different Apache servers listen to different TCP ports, each pinned to a different core. Each Apache server serves a single 1024B static file out of memory pre-cached by the MMapFile directive. The 16 load generating machines repeatedly open a TCP connection, request the file once, and close the connection. Each client attempts to maintain a set request rate using up to 1024 TCP connections at any one time. The problem we used DProf to investigate was that the total number of requests served per second abruptly dropped off after the request generation rate was increased beyond a certain point.
5.2.1 Profiling with DProf
Using DProf we captured two runs of Apache: one at the peak and one when performance dropped off. Looking at the results shown in Table 7 and Table 8, it was obvious that something happened to the working set size of tcp.sock objects. The data flow view also indicated that the time from allocation to deallocation of tcp.sock objects increased significantly from the peak case to the drop off case. Here, we used DProf to perform differential analysis to figure out what went wrong between two different runs.
Investigation showed the following to be the problem. Each instance of Apache allowed many TCP requests to be backlogged on its accept queue. The load generating machines eagerly filled this queue with new requests. In the peak performance case, the time it took from when a request was received by the kernel to the time Apache accepted the new connection was short because Apache kept up with the load and the queue remained shallow. When Apache accepted a new connection, the tcp.sock was in a cache close to the core. In the drop off case the queue filled to its limit and by the time Apache accepted a connection, the tcp.sock cache lines had already been flushed from the caches closest to the core. The average cycle miss latency for a tcp.sock cache lines was 50 cycles in the peak case and 150 cycles in the drop off case.
We implemented admission control by limiting the number of TCP connections queued in memory. Connections that did not fit on the queue were dropped. This change eliminated the performance drop-off at the higher request rate raising performance to the same level as peak performance (an improvement of 16%).
5.2.2 Analysis with Lock_stat
The lock_stat analysis results are shown in Table 9. The results show that the Linux kernel fast user mutex (futex) subsystem is taking up execution time acquiring locks. This is indeed the
Table 7. Working set and data profile views for the top data types in Apache at peak performance as reported by DProf.
<table>
<thead>
<tr>
<th>Type Name</th>
<th>Description</th>
<th>Working Set View</th>
<th>Data Profile View</th>
</tr>
</thead>
<tbody>
<tr>
<td>tcp_sock</td>
<td>TCP socket structure</td>
<td>11.6MB</td>
<td>21.5%</td>
</tr>
<tr>
<td>task_struct</td>
<td>task structure</td>
<td>1.3MB</td>
<td>10.7%</td>
</tr>
<tr>
<td>net_device</td>
<td>network device structure</td>
<td>128B</td>
<td>12.0%</td>
</tr>
<tr>
<td>size-1024</td>
<td>packet payload</td>
<td>6.3MB</td>
<td>4.1%</td>
</tr>
<tr>
<td>skbuff</td>
<td>packet bookkeeping structure</td>
<td>7.2MB</td>
<td>3.7%</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>26.3MB</td>
<td>52.1%</td>
</tr>
</tbody>
</table>
Table 8. Working set and data profile views for the top data types in Apache at drop off as reported by DProf.
<table>
<thead>
<tr>
<th>Type Name</th>
<th>Description</th>
<th>Working Set View</th>
<th>Data Profile View</th>
</tr>
</thead>
<tbody>
<tr>
<td>tcp_sock</td>
<td>TCP socket structure</td>
<td>1.1MB</td>
<td>11.0%</td>
</tr>
<tr>
<td>task_struct</td>
<td>task structure</td>
<td>1.2MB</td>
<td>21.4%</td>
</tr>
<tr>
<td>net_device</td>
<td>network device structure</td>
<td>128B</td>
<td>3.4%</td>
</tr>
<tr>
<td>size-1024</td>
<td>packet payload</td>
<td>4.2MB</td>
<td>5.2%</td>
</tr>
<tr>
<td>skbuff</td>
<td>packet bookkeeping structure</td>
<td>4.3MB</td>
<td>3.3%</td>
</tr>
<tr>
<td>Total</td>
<td></td>
<td>10.8MB</td>
<td>44.2%</td>
</tr>
</tbody>
</table>
Table 9. Lock statistics acquired by lock_stats during a 30 second run of Apache. The wait time is a sum over all 16 cores.
<table>
<thead>
<tr>
<th>Lock Name</th>
<th>Wait Time</th>
<th>Overhead</th>
<th>Functions</th>
</tr>
</thead>
<tbody>
<tr>
<td>futex lock</td>
<td>1.98</td>
<td>0.4%</td>
<td>do_futex, futex_wait, futex_sleep</td>
</tr>
</tbody>
</table>
5.2.3 Profiling with OProfile
OProfile tracks events like context switches and thus does more work than DProf when collecting samples regardless of the sampling rate. We were not able to collect reliable data with OProfile because any major perturbation to the test machine caused the machine to go from the peak state straight into the drop off state.
5.3 Access Sample Overhead
The overhead of data access profiling comes from taking an interrupt to save an access sample. The overhead is proportional to the IBS sampling rate; Figure 3 shows the overhead of profiling for different IBS sampling rates for the Apache and memcached applications. The sampling rate is chosen based on the overhead tolerance. With lower sampling rates it is critical to sample long enough to capture enough access samples of data types in interest.
The cost of an IBS interrupt is about 2,000 cycles on the test machine. Half of the cycles are spent reading IBS data out of a core’s IBS registers, the rest is spent entering and exiting the interrupt and resolving the data’s address to its type.
Just like CPU cycle overhead, the memory overhead of data access profiling is proportional to the number of samples collected. Each access sample is 88 bytes. For example, a sixty second profile of memcached generated 7.4 million samples and took up 654MB of space; off-line aggregation brought space use below 20MB.
Table 10. Object access history collection times and overhead for different data types and applications.
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>Data Type</th>
<th>Data Type Size (bytes)</th>
<th>Histories</th>
<th>Histories Sets</th>
<th>Collection Time (s)</th>
<th>Overhead (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>memcached</td>
<td>size-1024</td>
<td>1024</td>
<td>8128</td>
<td>32</td>
<td>170</td>
<td>1.3</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>256</td>
<td>5120</td>
<td>80</td>
<td>95</td>
<td>0.8</td>
</tr>
<tr>
<td>Apache</td>
<td>size-1024</td>
<td>1024</td>
<td>20320</td>
<td>80</td>
<td>34</td>
<td>2.9</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>256</td>
<td>2048</td>
<td>32</td>
<td>24</td>
<td>1.6</td>
</tr>
<tr>
<td></td>
<td>skbuff_fclone</td>
<td>512</td>
<td>10240</td>
<td>80</td>
<td>2.5</td>
<td>16</td>
</tr>
<tr>
<td></td>
<td>tcp_sock</td>
<td>1600</td>
<td>32000</td>
<td>80</td>
<td>32</td>
<td>4.9</td>
</tr>
</tbody>
</table>
Table 11. Average object access history collection rates for different data types and applications.
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>Data Type</th>
<th>Elements per History</th>
<th>Histories per Second</th>
<th>Elements per Second</th>
</tr>
</thead>
<tbody>
<tr>
<td>memcached</td>
<td>size-1024</td>
<td>0.3</td>
<td>53</td>
<td>120</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>4.2</td>
<td>56</td>
<td>350</td>
</tr>
<tr>
<td>Apache</td>
<td>size-1024</td>
<td>0.5</td>
<td>660</td>
<td>1660</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>4.8</td>
<td>110</td>
<td>770</td>
</tr>
<tr>
<td></td>
<td>skbuff_fclone</td>
<td>4.0</td>
<td>4600</td>
<td>27500</td>
</tr>
<tr>
<td></td>
<td>tcp_sock</td>
<td>8.3</td>
<td>1030</td>
<td>10600</td>
</tr>
</tbody>
</table>
Figure 4. Percent of unique paths captured as a function of history sets collected. For all data types, the maximum number of unique paths is based on a profile with 720 history set. Only results for profiles with less than 160 sets are shown.
5.4 Object Access History Overhead
The overhead for capturing object access histories depends on the number of debug register interrupts triggered per second—which DProf has no control over—and the number of histories collected per second—which DProf can modulate. For the Apache and memcached applications Table 10 shows the range of overheads when profiling different data types. A **history set** is a collection of object access histories that cover every offset in a data type. For example, a **skbuff** is 256 bytes long and its history set is composed of 64 histories with debug register configured to monitor length of 4 bytes.
The overhead for capturing Apache **skbuff** access histories is 16% because the lifetime of this data type is short and DProf can collect many access histories per second. The collection rates are shown in Table 10. To reduce the overhead, DProf can collect less histories per second.
Table 13 shows a breakdown of the profiling overhead. The first component is the cost to take an interrupt and save an element. This interrupt is triggered every time the profiled object is accessed and costs the test machine 1,000 cycles.
There are two setup overheads: the cost to reserve an object for profiling with the memory subsystem and the cost to setup debug registers on all cores. At high histories per second rates, the dominating factor is the debug registers setup overhead. The core responsible for setting up debug registers incurs a cost of 130,000 cycles. The high cost is due to interrupts sent to all other cores to notify them to set their debug registers.
In addition to cycle overhead, history collection incurs a memory overhead of 32 bytes per element in an object access history.
The time to collect all histories depends on the size and lifetime of an object. Table 10 shows collection times for a number of data types. Table 11 shows the rates at which histories are collected. Since DProf profiles only a few bytes of an object at a time, the bigger the object the more runs are needed. Also because DProf can profile only a few objects at a time, the longer an object remains in use, the longer it takes to capture its history.
The time to setup an object to be monitored also adds to the profiling time. It costs about 220,000 cycles to setup an
object for profiling. Most of this cost comes from notifying all cores to setup their debug registers.
An object can take multiple paths; to record all of an object’s paths, DProf needs to profile multiple times until all paths are captured. DProf is concerned with capturing the most often taken paths. Paths that are not taken often usually do not contribute to the performance of an application. The question is how many times should an object be profiled to collect all relevant paths? There is no specific answer because the number depends on individual data types. We have found that for all the data types we studied, 30 to 100 history sets were sufficient to collect all relevant paths.
<table>
<thead>
<tr>
<th>Data Type</th>
<th>Interrupts/Memory/Communication</th>
</tr>
</thead>
<tbody>
<tr>
<td>size-1024</td>
<td>20% / 10% / 70%</td>
</tr>
<tr>
<td>skb</td>
<td>60% / 10% / 30%</td>
</tr>
<tr>
<td>skbuff_fclone</td>
<td>5% / 5% / 90%</td>
</tr>
<tr>
<td>tcp_sock</td>
<td>20% / 5% / 75%</td>
</tr>
</tbody>
</table>
Table 13. Object access history overhead breakdown for different data types used by Apache. The overhead is composed of the cost to take a debug register interrupt, the cost to communicate with the memory subsystem to allocate an object for profiling, and the cost to communicate with all cores to setup debug registers.
To verify this, we collected profiles with a large number of history sets (720 sets per data type) for a couple different data types used by the Apache and memcached applications. By collecting a profile with a large number of history sets we hope to capture all unique and relevant paths for a particular type. We then collected profiles with a decreasing number of history sets and counted the number of unique paths found. Figure 4 shows the result of this experiment. As the number of histories collected decreases, the percent of all unique paths captured decreases as well. In general 30 to 100 history sets are sufficient to capture most unique paths.
To build the data flow view, DProf must monitor multiple bytes of an object at the same time. This is needed order the accesses to fields of an object along each path. To get a complete picture, DProf profiles every pair of bytes in an object. Pairwise data collection takes longer because many more histories need to be collected to profile an object just once; the increase is quadratic. Table 14 shows times for pairwise profiling.
To reduce the time to collect pairwise histories, DProf does not profile all fields of a data type. Instead, DProf analyzes the access samples to find the most used fields. The programmer can tune which fields are in this set. DProf profiles just the bytes that cover the chosen fields.
6. Related Work
There are many studies of application cache performance, and the strong impact of cache access patterns on the performance has been noted for Unix kernels [8] and databases [3]. Recent work has provided tools to help programmers make more efficient use of caches for specific workloads [7, 18]. DProf, on the other hand, helps programmers determine the cause of cache misses that lead to poor system performance, so that they know where to either apply other tools, or make other changes to their code. Tools most similar to DProf can be subdivided into two categories: Section 6.1 describes code profilers and Section 6.2 describes data profilers.
6.1 Code Profilers
Code profilers such as Gprof [12], Quartz [5], and OProfile [19] gather runtime statistics about an application or the...
entire system, attributing costs such as CPU cycles or cache misses to functions or individual instructions. Code profilers rank functions by cost to draw a developer’s attention to those most likely to benefit from optimization. DProf is likely to be more useful than a code profiler in cases where the cache misses for an object are spread thinly over references from many functions. DProf also provides specialized views tailored to tracking down sources of cache misses that are often not apparent from code profilers, such as the working set exceeding the cache size.
OProfile [19] (which was inspired by DCPI [4]) samples hardware events and assigns them to instruction pointers. It can profile a variety of events counted by the CPU hardware: clock cycles, cache misses, memory accesses, branch mispredictions, etc. The output of a profiling session is a list of functions ranked by cost.
Both OProfile and DProf use hardware support for sampling performance information. In particular, DProf relies heavily on x86 debug registers [14] and IBS [11], which was inspired by ProfileMe [9].
### 6.2 Data Profilers
MemSpy [20] helps developers locate poor cache access patterns. MemSpy uses a system simulator to execute an application. The simulator allows MemSpy to interpose on all memory accesses and build a complete map of the cache. MemSpy can account for and explain every single cache miss and using a processor accurate model can approximate memory access latencies. Unfortunately, MemSpy has very high overhead and requires applications to run on top of a simulator. It also can only estimate the access latencies that would occur on out-of-order processors.
A number of other cache simulators have been proposed [24], including CProf [17] and valgrind’s cachegrind module [22, 23]. Most of these simulators are similar to MemSpy, differing in the amount of programmer annotations or instrumentation necessary to run the tool. The key difference from DProf is that none of these tools report cache misses for a particular data structure, making it easy to overlook cache misses that are spread throughout the application’s code.
Intel’s performance tuning utility (PTU) [15], a follow-on to VTune [16], uses Intel’s PEBS facility to precisely associate samples with instructions. The PEBS hardware is similar in purpose to IBS. Both Intel PEBS and AMD IBS can capture the addresses used by load and store instructions and access latencies for load instructions. DProf can use PEBS on Intel hardware to collect statistics.
Intel PTU does not associate addresses with dynamic memory; only with static memory. Collected samples are attributed to cache lines, and if the lines are a part of static data structures, the name of the data structure is associated with the cache line. This is mainly geared at profiling access to static arrays. In addition, there is no aggregation of samples by data type; only by instruction. Intel PTU uses the addresses of collected load and stores to calculate the working set of the application. The working set, however, is presented in terms of addresses and not data types.
The Intel hardware has a richer set of performance counters than the AMD hardware. False cache line sharing is detected by collecting a combination of hardware counters that count local misses and fetches of cache lines in the modified state from remote caches.
There have also been proposals to modify hardware for more direct cache access monitoring. The authors of FlashPoint [21] propose an interface that allows the programmer to tell the hardware what data they are interested in profiling. The hardware directly collects fine grained statistics and classifies cache misses.
### 7. Discussion
DProf is limited by the data collection mechanisms present in AMD and Intel processors. First, DProf estimates working set sizes indirectly, based on allocation, memory access, and deallocation events. Hardware support for examining the contents of CPU caches directly would make this task straightforward, and improve its precision. FlashPoint [21] is one example of a possible hardware change that can make tracking cache misses easier. DProf is also limited by having access to only four debug registers for tracing memory accesses through application code. As a result, computing object access histories requires pairwise tracing of all offset pairs in a data structure. Collecting precise information in this manner is difficult, and having a variable-size debug register would greatly help DProf.
<table>
<thead>
<tr>
<th>Benchmark</th>
<th>Data Type</th>
<th>Data Type Size (bytes)</th>
<th>Histories</th>
<th>Histories Sets</th>
<th>Collection Time (s)</th>
<th>Overhead (%)</th>
</tr>
</thead>
<tbody>
<tr>
<td>memcached</td>
<td>size-1024</td>
<td>1024</td>
<td>32132</td>
<td>1</td>
<td>400</td>
<td>0.9</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>256</td>
<td>2017</td>
<td>1</td>
<td>26</td>
<td>1.0</td>
</tr>
<tr>
<td>Apache</td>
<td>size-1024</td>
<td>1024</td>
<td>32132</td>
<td>1</td>
<td>50</td>
<td>4.8</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>256</td>
<td>2017</td>
<td>1</td>
<td>18</td>
<td>1.7</td>
</tr>
<tr>
<td></td>
<td>skbuff</td>
<td>512</td>
<td>8129</td>
<td>1</td>
<td>2.3</td>
<td>18</td>
</tr>
<tr>
<td></td>
<td>skbuff, fclone</td>
<td>1600</td>
<td>79801</td>
<td>1</td>
<td>81</td>
<td>5.5</td>
</tr>
</tbody>
</table>
Table 14. Object access history collection times and overhead using pair sampling for different data types and applications.
8. Conclusion
Cache misses are a significant factor in application performance, and are becoming increasingly more important on multicore systems. However, current performance profiling tools focus on attributing execution time to specific code locations, which can mask expensive cache misses that may occur throughout the code. This paper presents DProf, a data-oriented profiler that attributes cache misses to specific data types. Programmers can use DProf's data-oriented views to locate and fix different causes of cache misses in their applications, which may be difficult to locate using CPU profilers. We have used DProf to analyze cache misses encountered in the Linux kernel, and have found and fixed a number of suboptimal memory access patterns. Our fixed Linux kernel achieves 16–57% throughput improvement running a range of memcached and Apache workloads.
Acknowledgments
This research was partially supported by a MathWorks Fellowship and by NSF award CNS-0834415. We thank our shepherd Alexandra Fedorova and the anonymous reviewers for making suggestions that improved this paper.
References
|
{"Source-Url": "http://dspace.mit.edu/bitstream/handle/1721.1/72691/Morris_Locating%20cache.pdf?isAllowed=y&sequence=1", "len_cl100k_base": 14305, "olmocr-version": "0.1.53", "pdf-total-pages": 15, "total-fallback-pages": 0, "total-input-tokens": 48747, "total-output-tokens": 15776, "length": "2e13", "weborganizer": {"__label__adult": 0.00040030479431152344, "__label__art_design": 0.00044417381286621094, "__label__crime_law": 0.0003628730773925781, "__label__education_jobs": 0.0009026527404785156, "__label__entertainment": 0.00011932849884033204, "__label__fashion_beauty": 0.00020885467529296875, "__label__finance_business": 0.00040793418884277344, "__label__food_dining": 0.0003674030303955078, "__label__games": 0.001224517822265625, "__label__hardware": 0.006366729736328125, "__label__health": 0.0005559921264648438, "__label__history": 0.0004906654357910156, "__label__home_hobbies": 0.0001583099365234375, "__label__industrial": 0.0007977485656738281, "__label__literature": 0.0002827644348144531, "__label__politics": 0.0002956390380859375, "__label__religion": 0.0005469322204589844, "__label__science_tech": 0.1976318359375, "__label__social_life": 7.408857345581055e-05, "__label__software": 0.01439666748046875, "__label__software_dev": 0.7724609375, "__label__sports_fitness": 0.0003893375396728515, "__label__transportation": 0.0007891654968261719, "__label__travel": 0.00026988983154296875}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 68867, 0.03588]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 68867, 0.51388]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 68867, 0.89147]], "google_gemma-3-12b-it_contains_pii": [[0, 610, false], [610, 5173, null], [5173, 11060, null], [11060, 15230, null], [15230, 22358, null], [22358, 28026, null], [28026, 33726, null], [33726, 36844, null], [36844, 41145, null], [41145, 46449, null], [46449, 49874, null], [49874, 54317, null], [54317, 57826, null], [57826, 63410, null], [63410, 68867, null]], "google_gemma-3-12b-it_is_public_document": [[0, 610, true], [610, 5173, null], [5173, 11060, null], [11060, 15230, null], [15230, 22358, null], [22358, 28026, null], [28026, 33726, null], [33726, 36844, null], [36844, 41145, null], [41145, 46449, null], [46449, 49874, null], [49874, 54317, null], [54317, 57826, null], [57826, 63410, null], [63410, 68867, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 68867, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 68867, null]], "pdf_page_numbers": [[0, 610, 1], [610, 5173, 2], [5173, 11060, 3], [11060, 15230, 4], [15230, 22358, 5], [22358, 28026, 6], [28026, 33726, 7], [33726, 36844, 8], [36844, 41145, 9], [41145, 46449, 10], [46449, 49874, 11], [49874, 54317, 12], [54317, 57826, 13], [57826, 63410, 14], [63410, 68867, 15]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 68867, 0.28223]]}
|
olmocr_science_pdfs
|
2024-12-07
|
2024-12-07
|
b60c6a092a8e5a199ceb298fb7f410ac67f45634
|
Overview
- **Last week:** non-relational abstract domains
- Abstract each variable independently from the others
- Can express important properties (e.g., absence of overflow)
- Unable to represent relations between variables
- **This week:** relational abstract domains
- More precise, but more costly
- The need for relational domains
- Linear equality domain
- Polyhedra domain
- Project: relational analysis with the Apron library
- **Next week:** selected advanced topics on abstract domains
- (Not needed for the project)
Motivation
Relational assignments and tests
Example
\[ X \leftarrow \text{rand}(0, 10); \ Y \leftarrow \text{rand}(0, 10); \]
\[ \text{if } X > Y \text{ then } X \leftarrow Y \text{ else skip; } \]
\[ D \leftarrow Y - X; \]
\[ \text{assert } D \geq 0 \]
Interval analysis:
- \( S^\#[ X > Y? ] \) is abstracted as the identity
\[ S^\#[ \text{if } X > Y \text{ then } \cdots ] R^\# = R^\# \]
- \( D \leftarrow Y - X \) gives \( D \in [0, 10] -^\# [0, 10] = [-10, 10] \)
- the assertion \( D \geq 0 \) fails
Motivation
Relational assignments and tests
Example
\[
X \leftarrow \text{rand}(0, 10); \ Y \leftarrow \text{rand}(0, 10); \\
\text{if } X > Y \text{ then } X \leftarrow Y \text{ else skip}; \\
D \leftarrow Y - X; \\
\text{assert } D \geq 0
\]
Solution: relational domain
- represent explicitly the information \( X \leq Y \)
- infer that \( X \leq Y \) holds after the \text{if} \cdots \text{then} \cdots \text{else} \cdots \\
\( X \leq Y \) both after \( X \leftarrow Y \) when \( X > Y \), and after \text{skip} when \( X \leq Y \)
- use \( X \leq Y \) to deduce that \( Y - X \in [0, 10] \)
Note:
the invariant we seek, \( D \geq 0 \), can be exactly represented in the interval domain but inferring \( D \geq 0 \) requires a more expressive domain locally
Motivation
Relational loop invariants
Example
\[
\begin{align*}
& I \leftarrow 1; \ X \leftarrow 0; \\
& \textbf{while } I \leq 1000 \textbf{ do} \\
& \quad I \leftarrow I + 1; \ X \leftarrow X + 1; \\
& \textbf{assert } X \leq 1000
\end{align*}
\]
Interval analysis:
• after iterations with widening, we get in 2 iterations:
as loop invariant: \( I \in [1, +\infty) \) and \( X \in [0, +\infty) \)
after the loop: \( I \in [1001, +\infty) \) and \( X \in [0, +\infty) \implies \text{assert fails} \)
• using a decreasing iteration after widening, we get:
as loop invariant: \( I \in [1, 1001] \) and \( X \in [0, +\infty] \)
after the loop: \( I = 1001 \) and \( X \in [0, +\infty) \implies \text{assert fails} \)
(the test \( I \leq 1000 \) only refines \( I \), but gives no information on \( X \))
• without widening, we get \( I = 1001 \) and \( X = 1000 \implies \text{assert passes} \)
but we need 1000 iterations! (\( \simeq \) concrete fixpoint computation)
Relational loop invariants
Example
\[ I \leftarrow 1; \ X \leftarrow 0; \]
\[ \textbf{while } I \leq 1000 \textbf{ do} \]
\[ I \leftarrow I + 1; \ X \leftarrow X + 1; \]
\[ \textbf{assert } X \leq 1000 \]
**Solution:** relational domain
- infer a \textbf{relational loop invariant}: \( I = X + 1 \land 1 \leq I \leq 1001 \)
- \( I = X + 1 \) holds before entering the loop as \( 1 = 0 + 1 \)
- \( I = X + 1 \) is invariant by the loop body \( I \leftarrow I + 1; X \leftarrow X + 1 \)
(can be inferred in 2 iterations with widening in the polyhedra domain)
- propagate the loop exit condition \( I > 1000 \) to get:
- \( I = 1001 \)
- \( X = I - 1 = 1000 \implies \textbf{assert} \) passes
**Note:**
the invariant we seek after the loop exit has an interval form: \( X \leq 1000 \)
but we need to infer a more \textbf{expressive loop invariant} to deduce it
The affine equality domain
We look for invariants of the form:
$$\land_j \left( \sum_{i=1}^{n} \alpha_{ij} V_i = \beta_j \right), \quad \alpha_{ij}, \beta_j \in \mathbb{Q}$$
where all the $\alpha_{ij}$ and $\beta_j$ are inferred automatically.
We use a domain of affine spaces proposed by Karr in 1976
$$\mathcal{E}^\# \simeq \{ \text{affine subspaces of } V \rightarrow \mathbb{R} \}$$
(with a suitable machine representation)
Affine equality representation
**Machine representation:**
\[ \mathcal{E}^\# \overset{\text{def}}{=} \bigcup_m \{ \langle M, \vec{C} \rangle \mid M \in \mathbb{Q}^{m \times n}, \vec{C} \in \mathbb{Q}^m \} \cup \{ \bot \} \]
- either the constant \( \bot \)
- or a pair \( \langle M, \vec{C} \rangle \) where
- \( M \in \mathbb{Q}^{m \times n} \) is a \( m \times n \) matrix, \( n = |V| \) and \( m \leq n \),
- \( \vec{C} \in \mathbb{Q}^m \) is a row-vector with \( m \) rows
\( \langle M, \vec{C} \rangle \) represents an equation system, with solutions:
\[ \gamma(\langle M, \vec{C} \rangle) \overset{\text{def}}{=} \{ \vec{V} \in \mathbb{R}^n \mid M \times \vec{V} = \vec{C} \} \]
\( M \) should be in row echelon form:
- \( \forall i \leq m : \exists k_i : M_{ik_i} = 1 \) and
\( \forall c < k_i : M_{ic} = 0, \forall i \neq i : M_{lk_i} = 0 \),
- if \( i < i' \) then \( k_i < k_{i'} \) (leading index)
**Example:**
\[
\begin{bmatrix}
1 & 0 & 0 & 5 & 0 \\
0 & 1 & 0 & 6 & 0 \\
0 & 0 & 1 & 7 & 0 \\
0 & 0 & 0 & 0 & 1 \\
\end{bmatrix}
\]
**Remarks:**
- the representation is unique
- as \( m \leq n = |V| \), the memory cost is in \( \mathcal{O}(n^2) \) at worst
- \( \bot \) is represented as the empty equation system: \( m = 0 \)
**Galois connection:**
between arbitrary subsets and affine subsets
\[(\mathcal{P}(\mathbb{R}^{\mathbb{V}}), \subseteq) \leftrightarrow (\text{Aff}(\mathbb{R}^{\mathbb{V}}), \subseteq)\]
- \(\gamma(X) \overset{\text{def}}{=} X\) (identity)
- \(\alpha(X) \overset{\text{def}}{=} \text{smallest affine subset containing } X\)
\(\text{Aff}(\mathbb{R}^{\mathbb{V}})\) is closed under arbitrary intersections, so we have:
\[\alpha(X) = \cap \{ Y \in \text{Aff}(\mathbb{R}^{\mathbb{V}}) | X \subseteq Y \}\]
\(\text{Aff}(\mathbb{R}^{\mathbb{V}})\) contains every point in \(\mathbb{R}^{\mathbb{V}}\)
we can also construct \(\alpha(X)\) by (abstract) union:
\[\alpha(X) = \bigcup \{ \{x\} | x \in X \}\]
Notes:
- we have assimilated \(\mathbb{V} \to \mathbb{R}\) to \(\mathbb{R}^{\mathbb{V}}\)
- we have used \(\text{Aff}(\mathbb{R}^{\mathbb{V}})\) instead of the matrix representation \(\mathcal{E}\) for simplicity; a Galois connection also exists between \(\mathcal{P}(\mathbb{R}^{\mathbb{V}})\) and \(\mathcal{E}\)
Normalisation and emptiness testing
Let $\mathbf{M} \times \mathbf{V} = \mathbf{C}$ be a system, not necessarily in normal form. The Gaussian reduction tells in $O(n^3)$ time:
- whether the system is satisfiable, and in that case
- gives an equivalent system in normal form
i.e.: it returns an element in $\mathcal{E}^\#$
Example:
$$\begin{cases} 2X + Y + Z = 19 \\ 2X + Y - Z = 9 \\ 3Z = 15 \end{cases}$$
$\Downarrow$
$$\begin{cases} X + 0.5Y = 7 \\ Z = 5 \end{cases}$$
Gaussian reduction algorithm: \( Gauss(\langle M, \vec{C} \rangle) \)
\[
\begin{align*}
\text{Gauss}(\langle M, \vec{C} \rangle) & \quad \text{for } c \text{ from 1 to } n \quad (\text{column } c) \\
& \quad \text{if } \exists \ell > r : M_{\ell c} \neq 0 \quad (\text{pivot } \ell) \\
& \quad \quad r \leftarrow r + 1 \\
& \quad \quad \text{swap } \langle \vec{M}_\ell, C_\ell \rangle \text{ and } \langle \vec{M}_r, C_r \rangle \\
& \quad \quad \text{divide } \langle \vec{M}_r, C_r \rangle \text{ by } M_{rc} \\
& \quad \quad \text{for } j \text{ from 1 to } n, j \neq r \\
& \quad \quad \quad \text{replace } \langle \vec{M}_j, C_j \rangle \text{ with } \langle \vec{M}_j, C_j \rangle - M_{jc} \langle \vec{M}_r, C_r \rangle \\
& \quad \quad \text{if } \exists \ell : \langle \vec{M}_\ell, C_\ell \rangle = \langle 0, \ldots, 0, c \rangle, c \neq 0 \\
& \quad \quad \quad \text{then return } \bot \\
& \quad \text{remove all rows } \langle \vec{M}_\ell, C_\ell \rangle \text{ that equal } \langle 0, \ldots, 0, 0 \rangle
\end{align*}
\]
Affine equality operators
Abstract operators:
If $X^\# \neq \bot$, we define:
$X^\# \cap^\# Y^\# \overset{\text{def}}{=} Gauss \left( \langle \left[ \begin{array}{c} M_{X^\#} \\ M_{Y^\#} \end{array} \right], \left[ \begin{array}{c} \vec{C}_{X^\#} \\ \vec{C}_{Y^\#} \end{array} \right] \rangle \right)$ (join equations)
$X^\# =^\# Y^\# \iff M_{X^\#} = M_{Y^\#}$ and $\vec{C}_{X^\#} = \vec{C}_{Y^\#}$ (uniqueness)
$X^\# \subseteq^\# Y^\# \iff X^\# \cap^\# Y^\# =^\# X^\#$
$S^\#[\sum_j \alpha_j V_j = \beta?] X^\# \overset{\text{def}}{=} Gauss \left( \langle \left[ \begin{array}{c} \alpha_1 \cdots \alpha_n \end{array} \right], \left[ \begin{array}{c} \vec{C}_{X^\#} \\ \beta \end{array} \right] \rangle \right)$ (add equation)
$S^\#[e \otimes e'] X^\# \overset{\text{def}}{=} X^\#$ for other tests
Remark:
$\subseteq^\#, =^\#, \cap^\#, =^\#$ and $S^\#[\sum_j \alpha_j V_j - \beta = 0?]$ are exact:
$(X^\# \subseteq^\# Y^\# \iff \gamma(X^\#) \subseteq \gamma(Y^\#), \quad \gamma(X^\# \cap^\# Y^\#) = \gamma(X^\#) \cap \gamma(Y^\#), \ldots)$
Affine equality assignment
**Non-deterministic assignment:** \( S#[V_j \leftarrow [-\infty, +\infty]] \)
**Principle:** remove all the occurrences of \( V_j \)
but reduce the number of equations by only one
(add a single degree of freedom)
**Algorithm:** assuming \( V_j \) occurs in \( M \)
- Pick the row \( \langle \tilde{M}_i, C_i \rangle \) such that \( M_{ij} \neq 0 \) and \( i \) maximal
- Use it to eliminate all the occurrences of \( V_j \) in lines before \( i \)
\((i \) maximal \( \implies M \) stays in row echelon form\)
- Remove the row \( \langle \tilde{M}_i, C_i \rangle \)
Example: forgetting Z
\[
\begin{align*}
X + Z &= 10 \\
Y + Z &= 7 \\
\end{align*}
\]
\[
\Rightarrow \quad \begin{cases}
X - Y = 3
\end{cases}
\]
The operator is **exact**
Affine equality assignment
**Affine assignments:** \( S^\#[V_j \leftarrow \sum_i \alpha_i V_i + \beta] \)
\[
S^\#[V_j \leftarrow \sum_i \alpha_i V_i + \beta] \times^\# \triangleq
\]
if \( \alpha_j = 0 \), \((S^\#[V_j = \sum_i \alpha_i V_i + \beta?] \circ S^\#[V_j \leftarrow [-\infty, +\infty]] \times^\#)\)
if \( \alpha_j \neq 0 \), \( \langle M, \vec{C} \rangle \) where \( V_j \) is replaced with \( \frac{1}{\alpha_j} (V_j - \sum_{i \neq j} \alpha_i V_i - \beta) \)
(variable substitution)
**Proof sketch:** based on properties in the concrete
**non-invertible assignment:** \( \alpha_j = 0 \)
\[
S[V_j \leftarrow e] = S[V_j \leftarrow e] \circ S[V_j \leftarrow [-\infty, +\infty]] \text{ as the value of } V \text{ is not used in } e
\]
so \( S[V_j \leftarrow e] = S[V_j = e?] \circ S[V_j \leftarrow [-\infty, +\infty]] \)
**invertible assignment:** \( \alpha_j \neq 0 \)
\[
S[V_j \leftarrow e] \subseteq S[V_j \leftarrow e] \circ S[V_j \leftarrow [-\infty, +\infty]] \text{ as } e \text{ depends on } V
\]
\[
\rho \in S[V_j \leftarrow e] R \iff \exists \rho' \in R: \rho = \rho' [V_j \mapsto \sum_i \alpha_i \rho'(V_i) + \beta]
\]
\[
\iff \exists \rho' \in R: \rho[V_j \mapsto (\rho(V_j) - \sum_{i \neq j} \alpha_i \rho'(V_i) - \beta) / \alpha_j = \rho']
\]
\[
\iff \rho[V_j \mapsto (\rho(V_j) - \sum_{i \neq j} \alpha_i \rho(V_i) - \beta) / \alpha_j] \in R
\]
**Non-affine assignments:** revert to non-deterministic case
\[
S^\#[V_j \leftarrow e] \times^\# \triangleq S^\#[V_j \leftarrow [-\infty, +\infty]] \times^\#
\]
(imprecise but sound)
Affine equality join
**Join:** \( \langle M, \vec{C} \rangle \cup \# \langle N, \vec{D} \rangle \)
**Idea:** unify columns 1 to \( n \) of \( \langle M, \vec{C} \rangle \) and \( \langle N, \vec{D} \rangle \) using row operations
**Example:**
Assume that we have unified columns 1 to \( k \) to get \( \begin{pmatrix} R \\ 0 \end{pmatrix} \), arguments are in row echelon form, and we have to unify at column \( k + 1 \): \( t(\vec{0} 1 \vec{0}) \) with \( t(\vec{\beta} 0 \vec{0}) \)
\[
\begin{pmatrix} R & 0 & M_1 \\ 0 & 1 & M_2 \\ 0 & 0 & M_3 \end{pmatrix}, \quad \begin{pmatrix} R & \vec{\beta} & N_1 \\ 0 & 0 & N_2 \\ 0 & 0 & N_3 \end{pmatrix} \implies \begin{pmatrix} R & \vec{\beta} & M'_1 \\ 0 & 0 & 0 \\ 0 & 0 & M_3 \end{pmatrix}, \quad \begin{pmatrix} R & \vec{\beta} & N_1 \\ 0 & 0 & N_2 \\ 0 & 0 & N_3 \end{pmatrix}
\]
Use the row \( \begin{pmatrix} \vec{0} & 1 & M_2 \end{pmatrix} \) to create \( \vec{\beta} \) in the left argument
Then remove the row \( \begin{pmatrix} \vec{0} & 1 & M_2 \end{pmatrix} \)
The right argument is unchanged
\( \implies \) we have now unified columns 1 to \( k + 1 \)
Unifying \( t(\vec{\alpha} 0 \vec{0}) \) and \( t(\vec{0} 1 \vec{0}) \) is similar
Unifying \( t(\vec{\alpha} 0 \vec{0}) \) and \( t(\vec{\beta} 0 \vec{0}) \) is a bit more complicated...
No other case possible as we are in row echelon form
Analysis example
No infinite increasing chain: we can iterate without widening!
Example
\[
X \leftarrow 10; \; Y \leftarrow 100; \\
\textbf{while } X \neq 0 \textbf{ do} \\
\quad X \leftarrow X - 1; \\
\quad Y \leftarrow Y + 10
\]
Abstract loop iterations:
\[
\lim \lambda X^\#.I^\# \cup S^\#[\text{body}] (S^\#[X \neq 0?] X^\#)
\]
- loop entry: \( I^\# = (X = 10 \land Y = 100) \)
- after one loop body iteration: \( F^\#(I^\#) = (X = 9 \land Y = 110) \)
- \( X^\# \overset{\text{def}}{=} I^\# \cup F^\#(I^\#) = (10X + Y = 200) \)
- \( X^\# \) is stable
at loop exit, we get \( S^\#[X = 0?] (10X + Y = 200) = (X = 0 \land Y = 200) \)
The polyhedron domain
We look for invariants of the form: $\bigwedge_j \left( \sum_{i=1}^n \alpha_{ij} V_i \geq \beta_j \right)$
We use the polyhedron domain by Cousot and Halbwachs (1978)
$E^\# \simeq \{ \text{closed convex polyhedra of } \forall \rightarrow \mathbb{R} \}$
Note: polyhedra need not be bounded (≠ polytopes)
Polyhedra have dual representations (Weyl–Minkowski Theorem)
**Constraint representation**
\[ \langle M, \vec{C} \rangle \text{ with } M \in \mathbb{Q}^{m \times n} \text{ and } \vec{C} \in \mathbb{Q}^m \]
represents:
\[ \gamma(\langle M, \vec{C} \rangle) \overset{\text{def}}{=} \{ \vec{V} \mid M \times \vec{V} \geq \vec{C} \} \]
We will also often use a constraint set notation \( \{ \sum_i \alpha_{ij} V_i \geq \beta_j \} \)
**Generator representation**
\[ [P, R] \text{ where} \]
- \( P \in \mathbb{Q}^{n \times p} \) is a set of \( p \) points: \( \vec{P}_1, \ldots, \vec{P}_p \)
- \( R \in \mathbb{Q}^{n \times r} \) is a set of \( r \) rays: \( \vec{R}_1, \ldots, \vec{R}_r \)
\[ \gamma([P, R]) \overset{\text{def}}{=} \{ (\sum_{j=1}^p \alpha_j \vec{P}_j) + (\sum_{j=1}^r \beta_j \vec{R}_j) \mid \forall j, \alpha_j, \beta_j \geq 0: \sum_{j=1}^p \alpha_j = 1 \} \]
Generator representation examples:
\[ \gamma([P, R]) \overset{\text{def}}{=} \{ (\sum_{j=1}^{p} \alpha_j \vec{P}_j) + (\sum_{j=1}^{r} \beta_j \vec{R}_j) | \forall j, \alpha_j, \beta_j \geq 0: \sum_{j=1}^{p} \alpha_j = 1 \} \]
Duality in polyhedra
Duality: \( P^* \) is the dual of \( P \), so that:
- the generators of \( P^* \) are the constraints of \( P \)
- the constraints of \( P^* \) are the generators of \( P \)
- \( P^{**} = P \)
\[
0x + 0y + 1z \leq 1 \iff (0, 0, 1)
\]
Minimal representations
- A constraint / generator system is minimal if no constraint / generator can be omitted without changing the concretization.
- Minimal representations are not unique.
Example: three different constraint representations for a point
(a) \( y + x \geq 0, y - x \geq 0, y \leq 0, y \geq -5 \)
(b) \( y + x \geq 0, y - x \geq 0, y \leq 0 \)
(c) \( x \leq 0, x \geq 0, y \leq 0, y \geq 0 \)
Polyhedra representations (cont.)
- No bound on the size of representations (even minimal ones)
- No best abstraction $\alpha$
Example: a disc has infinitely many polyhedral over-approximations, but no best one
Chernikova’s algorithm
Algorithm by Chernikova (1968), improved by LeVerge (1992) to switch from a constraint system to an equivalent generator system
**Motivation:** most operators are easier on one representation
- By **duality**, we can use the same algorithm to switch from generators to constraints.
- The minimal generator system can be **exponential** in the original constraint system (e.g., hypercube: \(2n\) constraints, \(2^n\) vertices).
- **Equality** constraints and lines (pairs of opposed rays) may be handled separately and more efficiently.
- Chernikova’s algorithm minimizes the representation on-the-fly (not presented here).
**Algorithm:** incrementally add constraints one by one
Start with:
\[
\begin{align*}
P_0 &= \{ (0, \ldots, 0) \} & \text{(origin)} \\
R_0 &= \{ \bar{x}_i, -\bar{x}_i \mid 1 \leq i \leq n \} & \text{(axes)}
\end{align*}
\]
Chernikova’s algorithm (cont.)
Update \([P_{k-1}, R_{k-1}]\) to \([P_k, R_k]\)
by adding one constraint \(\vec{M}_k \cdot \vec{V} \geq C_k \in \langle \mathbf{M}, \vec{C} \rangle\):
start with \(P_k = R_k = \emptyset\),
- for any \(\vec{P} \in P_{k-1}\) s.t. \(\vec{M}_k \cdot \vec{P} \geq C_k\), add \(\vec{P}\) to \(P_k\)
- for any \(\vec{R} \in R_{k-1}\) s.t. \(\vec{M}_k \cdot \vec{R} \geq 0\), add \(\vec{R}\) to \(R_k\)
- for any \(\vec{P}, \vec{Q} \in P_{k-1}\) s.t. \(\vec{M}_k \cdot \vec{P} > C_k\) and \(\vec{M}_k \cdot \vec{Q} < C_k\), add \(\vec{O}\) to \(P_k\):
\[
\vec{O} \overset{\text{def}}{=} \frac{C_k - \vec{M}_k \cdot \vec{Q}}{\vec{M}_k \cdot \vec{P} - \vec{M}_k \cdot \vec{Q}} \vec{P} - \frac{C_k - \vec{M}_k \cdot \vec{P}}{\vec{M}_k \cdot \vec{P} - \vec{M}_k \cdot \vec{Q}} \vec{Q}
\]
Chernikova’s algorithm (cont.)
- for any $\vec{R}, \vec{S} \in \mathbb{R}_{k-1}$ s.t. $\vec{M}_k \cdot \vec{R} > 0$ and $\vec{M}_k \cdot \vec{S} < 0$, add to $\mathbb{R}_k$:
$$\vec{O} \triangleq (\vec{M}_k \cdot \vec{S})\vec{R} - (\vec{M}_k \cdot \vec{R})\vec{S}$$
- for any $\vec{P} \in \mathbb{P}_{k-1}$, $\vec{R} \in \mathbb{R}_{k-1}$ s.t. either $\vec{M}_k \cdot \vec{P} > C_k$ and $\vec{M}_k \cdot \vec{R} < 0$, or $\vec{M}_k \cdot \vec{P} < C_k$ and $\vec{M}_k \cdot \vec{R} > 0$, add to $\mathbb{P}_k$:
$$\vec{O} \triangleq \vec{P} + \frac{C_k - \vec{M}_k \cdot \vec{P}}{\vec{M}_k \cdot \vec{R}} \vec{R}$$
Chernikova’s algorithm example
Example:
\[ P_0 = \{(0, 0)\} \quad R_0 = \{(1, 0), (-1, 0), (0, 1), (0, -1)\} \]
Chernikova’s algorithm example
Example:
\[ Y \geq 1 \]
\[ P_0 = \{(0, 0)\} \]
\[ P_1 = \{(0, 1)\} \]
\[ R_0 = \{(1, 0), (-1, 0), (0, 1), (0, -1)\} \]
\[ R_1 = \{(1, 0), (-1, 0), (0, 1)\} \]
Chernikova’s algorithm example
Example:
\[ Y \geq 1 \]
\[ X + Y \geq 3 \]
\[ \mathbf{P}_0 = \{(0, 0)\} \]
\[ \mathbf{P}_1 = \{(0, 1)\} \]
\[ \mathbf{P}_2 = \{(2, 1)\} \]
\[ \mathbf{R}_0 = \{(1, 0), (-1, 0), (0, 1), (0, -1)\} \]
\[ \mathbf{R}_1 = \{(1, 0), (-1, 0), (0, 1)\} \]
\[ \mathbf{R}_2 = \{(1, 0), (-1, 1), (0, 1)\} \]
Chernikova’s algorithm example
Example:
\[ P_0 = \{(0, 0)\} \]
\[ R_0 = \{(1, 0), (-1, 0), (0, 1), (0, -1)\} \]
\[ P_1 = \{(0, 1)\} \]
\[ R_1 = \{(1, 0), (-1, 0), (0, 1)\} \]
\[ P_2 = \{(2, 1)\} \]
\[ R_2 = \{(1, 0), (-1, 1), (0, 1)\} \]
\[ P_3 = \{(2, 1), (1, 2)\} \]
\[ R_3 = \{(0, 1), (1, 1)\} \]
Operators on polyhedra
Abstract operators:
Given \( X^\#, Y^\# \neq \bot \), we define:
\[
X^\# \subseteq^\# Y^\# \iff \\
\forall \vec{P} \in P_{X^\#} : M_{Y^\#} \times \vec{P} \geq \vec{C}_{Y^\#} \\
\forall \vec{R} \in R_{X^\#} : M_{Y^\#} \times \vec{R} \geq \vec{0}
\]
\[
X^\# \equiv^\# Y^\# \iff X^\# \subseteq^\# Y^\# \text{ and } Y^\# \subseteq^\# X^\#
\]
\[
X^\# \cap^\# Y^\# \defeq \langle \left[ \begin{array}{c} M_{X^\#} \\ M_{Y^\#} \end{array} \right], \left[ \begin{array}{c} \vec{C}_{X^\#} \\ \vec{C}_{Y^\#} \end{array} \right] \rangle \quad \text{(join constraint sets)}
\]
\( \subseteq^\#, =^\# \text{ and } \cap^\# \) are exact (in \( \mathcal{P}(\forall \to \mathbb{R}) \))
**Join:** \[ X^\# \cup^\# Y^\# \overset{\text{def}}{=} \begin{bmatrix} \{ P_{X^\#}, P_{Y^\#} \} \quad [ R_{X^\#}, R_{Y^\#} \} \end{bmatrix} \] (join generator sets)
**Examples:**
- two polytopes
- a point and a line
\(\cup^\#\) is optimal (in \(\mathcal{P}(\mathbb{V} \rightarrow \mathbb{R})\)):
we get the topological closure of the convex hull of \(\gamma(X^\#) \cup \gamma(Y^\#)\)
Operators on polyhedra (cont.)
**Affine tests:**
\[ S^\#[\sum_i \alpha_i V_i \geq \beta?] X^\# \overset{\text{def}}{=} \langle \begin{bmatrix} M_{X^\#} \\ \alpha_1 \cdots \alpha_n \end{bmatrix}, \begin{bmatrix} \bar{C}_{X^\#} \end{bmatrix} \rangle \]
**Non-deterministic assignment:**
\[ S^\#[V_j \leftarrow [-\infty, +\infty]] X^\# \overset{\text{def}}{=} [P_{X^\#}, [R_{X^\#} \bar{x}_j (-\bar{x}_j)]] \]
- these operators are exact (in \( P(\forall \rightarrow \mathbb{R}) \))
- other tests can be abstracted as \( S^\#[c?] X^\# \overset{\text{def}}{=} X^\# \) (sound but not optimal)
Affine assignment:
\[ S^\# [ V_j \leftarrow \sum_i \alpha_i V_i + \beta ] \] \[ X^\# \overset{\text{def}}{=} \]
if \( \alpha_j = 0 \),
\[ (S^\# [ \sum_i \alpha_i V_i = V_j - \beta ] \circ S^\# [ V_j \leftarrow [-\infty, +\infty] ]) X^\# \]
if \( \alpha_j \neq 0 \), \( \langle M, \bar{C} \rangle \) where \( V_j \) is replaced with \( \frac{1}{\alpha_j} (V_j - \sum_{i \neq j} \alpha_i V_i - \beta) \)
- similar to the assignment in the equality domain
- the assignment is exact (in \( P(\mathbb{V} \to \mathbb{R}) \))
- assignments can also be defined on the generator system
- for non-affine assignments: \( S^\# [ V \leftarrow e ] \overset{\text{def}}{=} S^\# [ V \leftarrow [-\infty, +\infty] ] \)
(sound but not optimal)
Polyhedra widening
\[ \mathcal{E}^\# \text{ has strictly increasing infinite chains } \implies \text{ we need a widening} \]
**Definition:**
Take \( X^\# \) and \( Y^\# \) in minimal constraint-set form
\[ X^\# \bowtie Y^\# \overset{\text{def}}{=} \{ c \in X^\# \mid Y^\# \subseteq^\# \{ c \} \} \]
We suppress any unstable constraint \( c \in X^\# \), i.e., \( Y^\# \not\subseteq^\# \{ c \} \)
**Example:**

Polyhedra widening
\( \mathcal{E}' \) has strictly increasing infinite chains \( \implies \) we need a widening
**Definition:**
Take \( X' \) and \( Y' \) in minimal constraint-set form
\[
X' \triangledown Y' \overset{\text{def}}{=} \{ c \in X' \mid Y' \subseteq \{ c \} \} \\
\cup \{ c \in Y' \mid \exists c' \in X' : X' = (X' \setminus c') \cup \{ c \} \}
\]
We suppress any unstable constraint \( c \in X' \), i.e., \( Y' \not\subseteq \{ c \} \)
We also keep constraints \( c \in Y' \) equivalent to those in \( X' \), i.e., when \( \exists c' \in X' : X' = (X' \setminus c') \cup \{ c \} \)
**Example:**

Example
\[ \begin{align*}
X & \leftarrow 2; I \leftarrow 0; \\
\textbf{while} & \ I < 10 \ \textbf{do} \\
& \ \textbf{if} \ \text{rand}(0, 1) = 0 \ \textbf{then} \ X \leftarrow X + 2 \ \textbf{else} \ X \leftarrow X - 3; \\
& \ I \leftarrow I + 1
\end{align*} \]
Loop invariant:
increasing iterations with widening:
\[ X_1^\# = \{X = 2, I = 0\} \]
\[ X_2^\# = \{X = 2, I = 0\} \uplus \{X \in [-1, 4], I = 1\} \]
\[ = \{X = 2, I = 0\} \uplus \{I \in [0, 1], 2 - 3I \leq X \leq 2I + 2\} \]
\[ = \{I \geq 0, 2 - 3I \leq X \leq 2I + 2\} \]
decreasing iteration: (recover \( I \leq 10 \))
\[ X_3^\# = \{X = 2, I = 0\} \uplus \{I \in [1, 10], 2 - 3I \leq X \leq 2I + 2\} \]
\[ = \{I \in [0, 10], 2 - 3I \leq X \leq 2I + 2\} \]
at the loop exit, we find eventually: \( I = 10 \land X \in [-28, 22] \)
Partial conclusion
**Cost vs. precision:**
<table>
<thead>
<tr>
<th>Domain</th>
<th>Invariants</th>
<th>Memory cost</th>
<th>Time cost (per op.)</th>
</tr>
</thead>
<tbody>
<tr>
<td>intervals</td>
<td>$V \in [\ell, h]$</td>
<td>$O(</td>
<td>V</td>
</tr>
<tr>
<td>affine equalities</td>
<td>$\sum_i \alpha_i V_i = \beta_i$</td>
<td>$O(</td>
<td>V</td>
</tr>
<tr>
<td>polyhedra</td>
<td>$\sum_i \alpha_i V_i \geq \beta_i$</td>
<td>unbounded, exponential in practice</td>
<td></td>
</tr>
</tbody>
</table>
- domains provide a tradeoff between precision and cost
- relational invariants are sometimes necessary even to prove non-relational properties
an abstract domain is defined by
- a choice of **abstract properties and operators** (semantic aspect)
- data-structures and algorithms (algorithmic aspect)
an abstract domain mixes two kinds of approximations:
- **static approximations** (choice of abstract properties)
- **dynamic approximations** (widening)
Weakly relational domains
**Principle:** restrict the expressiveness of polyhedra to be more efficient at the cost of precision
**Example domains:**
- Based on constraint propagation: (closure algorithms)
- Octagons: \( \pm X \pm Y \leq c \)
- shortest path closure: \( x + y \leq c \land -y + z \leq d \implies x + z \leq c + d \)
- quadratic memory cost, cubic time cost
- Two-variables per inequality: \( \alpha x + \beta y \leq c \)
- slightly more complex closure algorithm, by Nelson
- Octahedra: \( \sum \alpha_i V_i \leq c, \alpha_i \in \{-1, 0, 1\} \)
- incomplete propagation, to avoid exponential cost
- Pentagons: \( X - Y \leq 0 \)
- restriction of octagons
- incomplete propagation, aims at linear cost
- Based on linear programming:
- Template polyhedra: \( M \times \vec{V} \geq \vec{C} \) for a fixed \( M \)
**Issue:**
in relational domains we used implicitly **real-valued** environments $\forall \rightarrow \mathbb{R}$
our concrete semantics is based on **integer-valued** environments $\forall \rightarrow \mathbb{Z}$
In fact, an abstract element $X^\#$ does not represent $\gamma(X^\#) \subseteq \mathbb{R}^{\forall}$, but:
$$\gamma_{\mathbb{Z}}(X^\#) \overset{\text{def}}{=} \gamma(X^\#) \cap \mathbb{Z}^{\forall}$$
(keep only integer points)
**Soundness and exactness** for $\gamma_{\mathbb{Z}}$
- $\subseteq^\#$ and $\equiv^\#$ are no longer exact
- e.g., $\gamma(2X = 1) \neq \gamma(\bot)$, but $\gamma_{\mathbb{Z}}(2X = 1) = \gamma(\bot) = \emptyset$
- $\cap^\#$ and affine tests are still exact
- affine and non-deterministic assignments are no longer exact
- e.g., $R^\# = (Y = 2X)$, $S^\#[X \leftarrow [-\infty, +\infty]] R^\# = \top$, but $S[X \leftarrow [-\infty, +\infty]] (\gamma_{\mathbb{Z}}(R^\#)) = \mathbb{Z} \times (2\mathbb{Z})$
- all the operators are **still sound**
- $\mathbb{Z}^{\forall} \subseteq \mathbb{R}^{\forall}$, so $\forall X^\#: \gamma_{\mathbb{Z}}(X^\#) \subseteq \gamma(X^\#)$
(in general, soundness, exactness, optimality depend on the definition of $\gamma$)
Integers (cont.)
Possible solutions:
- **enrich** the domain (add exact representations for operation results)
- congruence equalities: $\bigwedge_i \sum_j \alpha_{ij} V_j \equiv \beta_i \lfloor \gamma_i \rfloor$ (Granger 1991)
- Pressburger arithmetic (first order logic with 0, 1, +)
- decidable, but with **very costly** algorithms
- **design optimal** (non-exact) operators
- also based on **costly algorithms**, e.g.:
- normalization: integer hull
- smallest polyhedra containing $\gamma \mathbb{Z}(X^\#)$
- emptiness testing: integer programming
- NP-hard, while linear programming is P
- **pragmatic solution** (efficient, non-optimal)
- use regular operators for $\mathbb{R}^{|V|}$, then tighten each constraint to remove as many non-integer points as possible
- e.g.: $2X + 6Y \geq 3 \rightarrow X + 3Y \geq 2$
Note: we abstract integers as reals!
Using the Apron Library
Apron library
Underlying libraries & abstract domains
- box
- intervals
- octagons
- NewPolka
- convex polyhedra
- linear equalities
- PPL + Wrapper
- convex polyhedra
- linear congruences
Abstraction toolbox
- scalar & interval arithmetic
- linearization of expressions
- fall-back implementations
Developer interface
User interface
- C API
- OCaml binding
- C++ binding
Data-types
- Coefficients
- Expressions
- Constraints
- Generators
- Abs. values
Semantics:
- $A \xrightarrow{\gamma} \wp(\mathbb{Z}^n \times \mathbb{R}^m)$
- dimensions and space dimensionality
Variables and Environments
- Semantics: $A \xrightarrow{\gamma} \wp(V \rightarrow \mathbb{Z} \cup \mathbb{R})$
http://apron.cri.ensmp.fr/library
Apron modules
The Apron module contains sub-modules:
- **Abstract1**
abstract elements
- **Manager**
abstract domains (arguments to all Abstract1 operations)
- **Polka**
creates a manager for polyhedra abstract elements
- **Var**
integer or real program variables (denoted as a string)
- **Environment**
sets of integer and real program variables
- **Texpr1**
arithmetic expression trees
- **Tcons1**
arithmetic constraints (based on Texpr1)
- **Coeff**
numeric coefficients (appear in Texpr1, Tcons1)
Using the Apron Library
Variables and environments
**Variables:** type `Var.t`
variables are denoted by their name, as a string:
(assumes implicitly that no two program variables have the same name)
- `Var.of_string`: `string -> Var.t`
**Environments:** type `Environment.t`
an abstract element abstracts a set of mappings in $\mathbb{V} \rightarrow \mathbb{R}$
$\mathbb{V}$ is the environment; it contains integer-valued and real-valued variables
- `Environment.make`: `Var.t array -> Var.t array -> t`
`make ivars rvars` creates an environment with `ivars` integer variables and `rvars` real variables;
`make [] []` is the empty environment
- `Environment.add`: `Environment.t -> Var.t array -> Var.t array -> t`
`add env ivars rvars` adds some integer or real variables to `env`
- `Environment.remove`: `t -> Var.t array -> t`
internally, an abstract element abstracts a set of points in $\mathbb{R}^n$;
the environment maintains the mapping from variable names to dimensions in $[1, n]$
Concrete expression trees: type \texttt{Texpr1.expr}
\begin{align*}
\text{type } \texttt{expr} &= \ | \ \text{Cst of Coeff.t} & \text{(constants)} \\
& \quad \ | \ \text{Var of Var.t} & \text{(variables)} \\
& \quad \ | \ \text{Unop of unop * expr * typ * round} & \text{(unary op.)} \\
& \quad \ | \ \text{Binop of binop * expr * expr * typ * round} & \text{(binary op.)}
\end{align*}
- **unary operators**
\begin{align*}
\text{type } \texttt{Texpr1.unop} &= \text{Neg} \ | \ldots
\end{align*}
- **binary operators**
\begin{align*}
\text{type } \texttt{Texpr1.binop} &= \text{Add} \ | \ \text{Sub} \ | \ \text{Mul} \ | \ \text{Div} \ | \ldots
\end{align*}
- **numeric type:**
\begin{align*}
\text{(we only use integers, but reals and floats are also possible)}
\text{type } \texttt{Texpr1.typ} &= \text{Int} \ | \ldots
\end{align*}
- **rounding direction:**
\begin{align*}
\text{(only useful for the division on integers; we use rounding to zero, i.e., truncation)}
\text{type } \texttt{Texpr1.round} &= \text{Zero} \ | \ldots
\end{align*}
**Internal expression form:** type `Texpr1.t`
Concrete expression trees must be converted to an internal form to be used in abstract operations.
- `Texpr1.of_expr`: `Environment.t -> Texpr1.expr -> Texpr1.t`
(the environment is used to convert variable names to dimensions in $\mathbb{R}^n$)
**Coefficients:** type `Coeff.t`
Coefficients can be either a scalar $\{c\}$ or an interval $[a, b]$.
We can use the `Mpqf` module to convert from strings to arbitrary precision integers, before converting them into `Coeff.t`:
- For scalars $\{c\}$:
```
Coeff.s_of_mpfq (Mpfq.of_string c)
```
- For intervals $[a, b]$:
```
Coeff.i_of_mpfq (Mpfq.of_string a) (Mpfq.of_string b)
```
**Constraints:** type \( T\text{cons1} \).t
constructor \( expr \bowtie 0 \):
- \( T\text{cons1}.\text{make} \): \( T\text{expr1} \).t \( \rightarrow \) \( T\text{Cons1}.\text{typ} \) \( \rightarrow \) \( T\text{cons1} \).t
where:
\[
\text{type } T\text{cons1}.\text{typ} = \begin{array}{c}
\text{SUPEQ} \quad | \quad \text{SUP} \quad | \quad \text{EQ} \quad | \quad \text{DISEQ} \quad | \quad \ldots \\
\geq \quad | \quad > \quad | \quad = \quad | \quad \neq
\end{array}
\]
Note: avoid using DISEQ directly, which is not very precise; but use a disjunction of two SUP constraints instead
**Constraint arrays:** type \( T\text{cons1}.\text{earray} \)
abstract operators do not use constraints, but constraint arrays instead
Example: constructing an array \( ar \) containing a single constraint:
```plaintext
let c = T\text{cons1}.\text{make} \ \text{texpr1} \ \text{typ} \ \text{in}
let ar = T\text{cons1}.\text{array_make} \ \text{env} \ 1 \ \text{in}
T\text{cons1}.\text{array_set} \ ar \ 0 \ c
```
Abstract operators
Abstract elements: type Abstract1.t
- Abstract1.top: Manager.t -> Environment.t -> t
create an abstract element where variables have any value
- Abstract1.env: t -> Environment.t
recover the environment on which the abstract element is defined
- Abstract1.change_environment: Manager.t -> t ->
Environment.t -> bool -> t
set the new environment, adding or removing variables if necessary
the bool argument should be set to false: variables are not initialized
- Abstract1.assign_texpr: Manager.t -> t -> Var.t -> Texpr1.t ->
t option -> t
abstract assignment; the option argument should be set to None
- Abstract1.forget_array: Manager.t -> t -> Var.t array -> bool -> t
non-deterministic assignment: forget the value of variables (when bool is false)
- Abstract1.meet_tcons_array: Manager.t -> t -> Tcons1.earray -> t
abstract test: add one or several constraint(s)
Abstract operators (cont.)
- **Abstract1.join**: `Manager.t -> t -> t -> t`
abstract union $\cup$
- **Abstract1.meet**: `Manager.t -> t -> t -> t`
abstract intersection $\cap$
- **Abstract1.widen**: `Manager.t -> t -> t -> t`
widening $\nabla$
- **Abstract1.is_leq**: `Manager.t -> t -> t -> bool`
$\subseteq$: return true if the first argument is included in the second
- **Abstract1.is_bottom**: `Manager.t -> t -> t bool`
whether the abstract element represents $\emptyset$
- **Abstract1.print**: `Format.formatter -> t -> unit`
print the abstract element
Contract:
- operators return a new, immutable abstract element (functional style)
- operators return over-approximations
(not always optimal; e.g.: for non-linear expressions)
- predicates return true (definitely true) or false (don't know)
**Managers:** type `Manager.t`
The manager denotes a choice of abstract domain.
To use the polyhedra domain, construct the manager with:
```ml
let manager = Polka.manager_alloc_loose ()
```
The same `manager` variable is passed to all `Abstract1` function.
To choose another domain, you only need to change the line defining `manager`.
**Other libraries:**
- `Polka.manager_alloc_equalities` (affine equalities)
- `Polka.manager_alloc_strict` ($\geq$ and $>$ affine inequalities over $\mathbb{R}$)
- `Box.manager_alloc` (intervals)
- `Oct.manager_alloc` (octagons)
- `Ppl.manager_alloc_grid` (affine congruences)
- `PolkaGrid.manager_alloc` (affine inequalities and congruences)
Errors
**Argument compatibility:** ensure that:
- the **same manager** is used when creating and using an abstract element
- the type system checks for the compatibility between 'a Manager.t and 'a Abstract1.t
- expressions and abstract elements have the **same environment**
- assigned **variables exist** in the environment of the abstract element
- both abstract elements of binary operators (∪, ∩, ⊓, ⊆) are defined on the **same environment**
Failure to ensure this results in a **Manager.Error** exception
open Apron
module RelationalDomain = (struct
(* manager *)
type man = Polka.loose Polka.t
let manager = Polka.manager_alloc_loose ()
(* abstract elements *)
type t = man Abstract1.t
(* utilities *)
val expr_to_texpr: expr -> Texpr1.expr
(* implementation *)
...
end: ENVIRONMENT_DOMAIN)
To compile: add to the Makefile:
OCAMLLINC = ⋯ -I +zarith -I +apron -I +gmp
CMA = bigarray.cma gmp.cma apron.cma polkaMPQ.cma
Fall-back assignments and tests
```ocaml
let rec expr_to_texpr = function
| AST_binary (op, e1, e2) ->
match op with
| AST_PLUS -> Texpr1.Binop ...
| ...
| _ -> raise Top
let assign env var expr =
try
let e = expr_to_texpr expr in
Abstract1.assign_texpr ...
with Top -> Abstract1.forget_array ...
let compare abs e1 e2 =
try
...
Abstract1.meet_tcons_array ...
with Top -> abs
```
Idea:
raise Top to abort a computation
catch it to fall-back to sound coarse assignments and tests
|
{"Source-Url": "http://www.di.ens.fr/~rival/semverif-2014/sem-11-ia.pdf", "len_cl100k_base": 13119, "olmocr-version": "0.1.53", "pdf-total-pages": 56, "total-fallback-pages": 0, "total-input-tokens": 115115, "total-output-tokens": 16291, "length": "2e13", "weborganizer": {"__label__adult": 0.00030612945556640625, "__label__art_design": 0.0008759498596191406, "__label__crime_law": 0.0004096031188964844, "__label__education_jobs": 0.0027675628662109375, "__label__entertainment": 0.00010353326797485352, "__label__fashion_beauty": 0.0001748800277709961, "__label__finance_business": 0.000423431396484375, "__label__food_dining": 0.00039315223693847656, "__label__games": 0.0008692741394042969, "__label__hardware": 0.0010137557983398438, "__label__health": 0.0005083084106445312, "__label__history": 0.00042629241943359375, "__label__home_hobbies": 0.00040650367736816406, "__label__industrial": 0.0009756088256835938, "__label__literature": 0.00039315223693847656, "__label__politics": 0.0002887248992919922, "__label__religion": 0.0005807876586914062, "__label__science_tech": 0.093017578125, "__label__social_life": 0.0002137422561645508, "__label__software": 0.0154266357421875, "__label__software_dev": 0.87939453125, "__label__sports_fitness": 0.0003104209899902344, "__label__transportation": 0.0006046295166015625, "__label__travel": 0.00027179718017578125}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 36133, 0.01636]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 36133, 0.50161]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 36133, 0.51348]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 549, false], [549, 560, null], [560, 1061, null], [1061, 1831, null], [1831, 2817, null], [2817, 3693, null], [3693, 3693, null], [3693, 4127, null], [4127, 5381, null], [5381, 6403, null], [6403, 6881, null], [6881, 7923, null], [7923, 8972, null], [8972, 9750, null], [9750, 11317, null], [11317, 12681, null], [12681, 13323, null], [13323, 13323, null], [13323, 13652, null], [13652, 14534, null], [14534, 14761, null], [14761, 15019, null], [15019, 15436, null], [15436, 15649, null], [15649, 16524, null], [16524, 17336, null], [17336, 17955, null], [17955, 18069, null], [18069, 18263, null], [18263, 18593, null], [18593, 18895, null], [18895, 19591, null], [19591, 19979, null], [19979, 20571, null], [20571, 21304, null], [21304, 21737, null], [21737, 22399, null], [22399, 23200, null], [23200, 24152, null], [24152, 25016, null], [25016, 26225, null], [26225, 27118, null], [27118, 27142, null], [27142, 27862, null], [27862, 28389, null], [28389, 29408, null], [29408, 30482, null], [30482, 31182, null], [31182, 32213, null], [32213, 33124, null], [33124, 33960, null], [33960, 34646, null], [34646, 35161, null], [35161, 35607, null], [35607, 36133, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 549, true], [549, 560, null], [560, 1061, null], [1061, 1831, null], [1831, 2817, null], [2817, 3693, null], [3693, 3693, null], [3693, 4127, null], [4127, 5381, null], [5381, 6403, null], [6403, 6881, null], [6881, 7923, null], [7923, 8972, null], [8972, 9750, null], [9750, 11317, null], [11317, 12681, null], [12681, 13323, null], [13323, 13323, null], [13323, 13652, null], [13652, 14534, null], [14534, 14761, null], [14761, 15019, null], [15019, 15436, null], [15436, 15649, null], [15649, 16524, null], [16524, 17336, null], [17336, 17955, null], [17955, 18069, null], [18069, 18263, null], [18263, 18593, null], [18593, 18895, null], [18895, 19591, null], [19591, 19979, null], [19979, 20571, null], [20571, 21304, null], [21304, 21737, null], [21737, 22399, null], [22399, 23200, null], [23200, 24152, null], [24152, 25016, null], [25016, 26225, null], [26225, 27118, null], [27118, 27142, null], [27142, 27862, null], [27862, 28389, null], [28389, 29408, null], [29408, 30482, null], [30482, 31182, null], [31182, 32213, null], [32213, 33124, null], [33124, 33960, null], [33960, 34646, null], [34646, 35161, null], [35161, 35607, null], [35607, 36133, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, true], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 36133, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 36133, null]], "pdf_page_numbers": [[0, 0, 1], [0, 549, 2], [549, 560, 3], [560, 1061, 4], [1061, 1831, 5], [1831, 2817, 6], [2817, 3693, 7], [3693, 3693, 8], [3693, 4127, 9], [4127, 5381, 10], [5381, 6403, 11], [6403, 6881, 12], [6881, 7923, 13], [7923, 8972, 14], [8972, 9750, 15], [9750, 11317, 16], [11317, 12681, 17], [12681, 13323, 18], [13323, 13323, 19], [13323, 13652, 20], [13652, 14534, 21], [14534, 14761, 22], [14761, 15019, 23], [15019, 15436, 24], [15436, 15649, 25], [15649, 16524, 26], [16524, 17336, 27], [17336, 17955, 28], [17955, 18069, 29], [18069, 18263, 30], [18263, 18593, 31], [18593, 18895, 32], [18895, 19591, 33], [19591, 19979, 34], [19979, 20571, 35], [20571, 21304, 36], [21304, 21737, 37], [21737, 22399, 38], [22399, 23200, 39], [23200, 24152, 40], [24152, 25016, 41], [25016, 26225, 42], [26225, 27118, 43], [27118, 27142, 44], [27142, 27862, 45], [27862, 28389, 46], [28389, 29408, 47], [29408, 30482, 48], [30482, 31182, 49], [31182, 32213, 50], [32213, 33124, 51], [33124, 33960, 52], [33960, 34646, 53], [34646, 35161, 54], [35161, 35607, 55], [35607, 36133, 56]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 36133, 0.0071]]}
|
olmocr_science_pdfs
|
2024-12-09
|
2024-12-09
|
1d9ddcb4a98d599dce347a4e06f7e425337b5167
|
[REMOVED]
|
{"Source-Url": "https://vbn.aau.dk/ws/files/36514450/typeinst.pdf", "len_cl100k_base": 15119, "olmocr-version": "0.1.50", "pdf-total-pages": 21, "total-fallback-pages": 0, "total-input-tokens": 79989, "total-output-tokens": 17537, "length": "2e13", "weborganizer": {"__label__adult": 0.0003762245178222656, "__label__art_design": 0.0005993843078613281, "__label__crime_law": 0.00043272972106933594, "__label__education_jobs": 0.0011577606201171875, "__label__entertainment": 0.00010532140731811523, "__label__fashion_beauty": 0.00018155574798583984, "__label__finance_business": 0.00042557716369628906, "__label__food_dining": 0.00042176246643066406, "__label__games": 0.0011920928955078125, "__label__hardware": 0.0019483566284179688, "__label__health": 0.0005249977111816406, "__label__history": 0.0004444122314453125, "__label__home_hobbies": 0.0001690387725830078, "__label__industrial": 0.000888824462890625, "__label__literature": 0.0003743171691894531, "__label__politics": 0.0003483295440673828, "__label__religion": 0.0006246566772460938, "__label__science_tech": 0.162841796875, "__label__social_life": 0.00010883808135986328, "__label__software": 0.0109710693359375, "__label__software_dev": 0.81396484375, "__label__sports_fitness": 0.0003457069396972656, "__label__transportation": 0.0011186599731445312, "__label__travel": 0.00026154518127441406}, "weborganizer_max": "__label__software_dev", "avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_v1__avg_fraction_numbers_in_line_ratio": [[0, 56396, 0.02015]], "fineweb_edu_fasttext_gt2__fineweb_edu_fasttext_gt2__score": [[0, 56396, 0.2898]], "ft_lang_id_en_doc_v2__ft_lang_id_en_doc_v2__en": [[0, 56396, 0.80369]], "google_gemma-3-12b-it_contains_pii": [[0, 0, null], [0, 2487, false], [2487, 5548, null], [5548, 8916, null], [8916, 11414, null], [11414, 14843, null], [14843, 17947, null], [17947, 21316, null], [21316, 25112, null], [25112, 27586, null], [27586, 29926, null], [29926, 32134, null], [32134, 35274, null], [35274, 36787, null], [36787, 39784, null], [39784, 41737, null], [41737, 43767, null], [43767, 47457, null], [47457, 50428, null], [50428, 54604, null], [54604, 56396, null]], "google_gemma-3-12b-it_is_public_document": [[0, 0, null], [0, 2487, true], [2487, 5548, null], [5548, 8916, null], [8916, 11414, null], [11414, 14843, null], [14843, 17947, null], [17947, 21316, null], [21316, 25112, null], [25112, 27586, null], [27586, 29926, null], [29926, 32134, null], [32134, 35274, null], [35274, 36787, null], [36787, 39784, null], [39784, 41737, null], [41737, 43767, null], [43767, 47457, null], [47457, 50428, null], [50428, 54604, null], [54604, 56396, null]], "google_gemma-3-4b-it_v2tag__is_academic_paper": [[0, 5000, true], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_class_syllabus": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_completion_certificate": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_court_notice": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_homework_assignment": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_news_article": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_public_order": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_resume_cv": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_test_or_quiz": [[0, 5000, false], [5000, 56396, null]], "google_gemma-3-4b-it_v2tag__is_textbook": [[0, 5000, false], [5000, 56396, null]], "pdf_page_numbers": [[0, 0, 1], [0, 2487, 2], [2487, 5548, 3], [5548, 8916, 4], [8916, 11414, 5], [11414, 14843, 6], [14843, 17947, 7], [17947, 21316, 8], [21316, 25112, 9], [25112, 27586, 10], [27586, 29926, 11], [29926, 32134, 12], [32134, 35274, 13], [35274, 36787, 14], [36787, 39784, 15], [39784, 41737, 16], [41737, 43767, 17], [43767, 47457, 18], [47457, 50428, 19], [50428, 54604, 20], [54604, 56396, 21]], "pipe_delimited_lines_v1__pipe_delimited_lines_v1__pipe_delimited_lines_ratio": [[0, 56396, 0.0]]}
|
olmocr_science_pdfs
|
2024-11-29
|
2024-11-29
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.