Professional Documents
Culture Documents
Keywords: Context: Modern systems require programmers to develop code that dynamically adapts to different contexts,
Behavioral programming leading to the evolution of new context-oriented programming languages. These languages introduce new
Scenario-based programming software-engineering challenges, such as: how to maintain the separation of concerns of the codebase? how
Programming paradigm
to model the changing behaviors? how to verify the system behavior? and more.
Context awareness
Objective: This paper introduces Context-Oriented Behavioral Programming (COBP) — a novel paradigm for
Context-oriented programming
Context-Oriented Behavioral Programming
developing context-aware systems, centered on natural and incremental specification of context-dependent
behaviors. As the name suggests, we combine behavioral-programming (BP) — a scenario-based modeling
paradigm — with context idioms that explicitly specify when scenarios are relevant and what information
they need. The core idea is to connect the behavioral model with a data model that represents the context,
allowing an intuitive connection between the models via update and select queries. Combining behavioral-
programming with context-oriented programming brings the best of the two worlds, solving issues that arise
when using each of the approaches in separation.
Methods: We begin with providing abstract semantics for COBP and two implementations for the semantics,
laying the foundations for applying reasoning algorithms to context-aware behavioral programs. Next, we
exemplify the semantics with formal specifications of systems, including a variant of Conway’s Game of Life.
Then, we provide two case studies of real-life context-aware systems (one in robotics and another in IoT) that
were developed using this tool. Throughout the examples and case studies, we provide design patterns and a
methodology for coping with the above challenges.
Results: The case studies show that the proposed approach is applicable for developing real-life systems, and
presents measurable advantages over the alternatives — behavioral programming alone and context-oriented
programming alone.
Conclusion: We present a paradigm allowing programmers and system engineers to capture complex context-
dependent requirements and align their code with such requirements.
✩ This work was partially supported by the Institute for Innovation in Transportation, Tel-Aviv University, Israel, and the Fuel-Choices and Smart-Mobility
Initiative, Israel.
E-mail address: achiya@bgu.ac.il.
https://doi.org/10.1016/j.infsof.2020.106504
Received 5 May 2020; Received in revised form 19 October 2020; Accepted 30 November 2020
Available online 30 December 2020
0950-5849/© 2020 The Author. Published by Elsevier B.V. This is an open access article under the CC BY license (http://creativecommons.org/licenses/by/4.0/).
A. Elyasaf Information and Software Technology 133 (2021) 106504
others are only relevant for pawns, etc. Behaviors may also interact However, it requires to adapt these approaches, since they are all
with the context by querying or changing it. In Chess for example, one designed under the assumption that the only protocol between the b-
of the behaviors is to trigger the ‘check’ context whenever an opponent threads is requesting, blocking, and triggering of events. Therefore,
pieces is threatening the king. Specifying context-aware requirements the formal semantics presented here lay the foundations towards such
(i.e., context-dependent requirements and requirements that change the adaptations.
system context) with b-threads — requires explicit, first-class citizen
Outline. Section 2 elaborates on the behavioral programming
idioms for referencing and changing the system context — something
paradigm and describes its shortcoming when it comes to handling
that is not defined for BP. In [6] and [4], context idioms were proposed
the system context. Section 3 formally defines COBP, giving abstract
for two implementations of BP, in live-sequence charts (LSC) [7] and in
semantics for the language and presents two implementations of the
JavaScript (respectively). Using the extended languages with first-class
paradigm. Sections 4 to 6 demonstrate how the abstract semantics
citizen context idioms, they demonstrated how the new idioms allow
can be used for formally specifying context-aware systems. In Sec-
for a direct specification of context-aware requirements, resulting in
tions 8 to 10 we provide two case studies of context-aware systems that
a better alignment between the requirements and the specification. In
were programmed using this implementation. In Section 11 we discuss
both languages, the context idioms were defined as syntactic sugars on
reasoning approaches for COP and BP, as well as other approaches for
top of the original language idioms, and translational semantics were
integrating context with modeling and programming. We conclude this
proposed for the new idioms.
paper in Section 12, with a discussion about future research directions.
In this paper, we generalize the approach of [4,6] and present
Context-Oriented Behavioral Programming (COBP) — a novel, language- 2. The context of this paper: Behavioral programming
independent paradigm for developing context-aware systems, centered
on natural and incremental specification of context-dependent behav- When creating a system using BP, developers specify a set of sce-
iors. Specifically, we propose to add first-class citizen context idioms to narios that may, must, or must not happen. Each scenario is a simple
BP and define new formal semantics for specifying the relation between sequential thread of execution, called b-thread, that is normally aligned
the system context and the system behavior. One of the advantages of with a system requirement, such as ‘‘stop moving’’ or ‘‘turn to target’’.
these formal semantics over the translational semantics of [4,6], is the The set of b-threads in a model is called a behavioral program (b-
ability to directly implement the paradigm in different programming program). During run-time, all b-threads participating in a b-program
languages, rather than relying on existing BP implementations and are combined, yielding a complex behavior that is consistent with
translating to them. Based on this ability, we also present a JavaScript- all said b-threads. As we elaborate below, unlike other paradigms,
based implementation for the paradigm and provide two case-study such as functional programming or object-oriented programming, BP
systems that were developed with it (Sections 8 to 10). does not force developers to pick a single behavior for the system to
Another approach for integrating context with programming is use. Rather, the system is allowed to choose any compliant behavior.
the context-oriented programming (COP) paradigm [8]. Over the last This allows the run-time to optimize program execution at any given
decade, COP has evolved in a variety of languages and approaches, moment, e.g., based on available resources. The fact that all possible
starting from Costanza and Hirschfeld [8]. While there are many system behaviors comply with the b-threads (and thus with the system
variations in the way they handle the contextual data and the relevant requirements), ensures that whichever behavior is chosen, the system
behavioral variations, the layers is the most widespread model by will perform as specified.
far [9]. Layers are a language abstraction, grouping definitions of To make these concepts more concrete, we now turn to a tutorial
partial methods that implement some fragment of an aspect of the example of a simple b-program, first presented in [1]. All of the
system behavior [8]. We compare some of the idioms of COP and COBP examples in this paper are specified formally, based on the transition
in Section 9. systems that we define in Section 3. JavaScript-based programs are
Both in COP and COBP, the system may have two contradicting presented in Sections 8 to 10.
behaviors, as long as they are bound to different contexts. Consider Consider a system that controls taps of hot and cold water, whose
for example conflicting requirements, overridden by the context, like output flows are mixed, with the following requirements:
‘‘vacuum the carpet’’ and ‘‘do not vacuum while someone is asleep’’.
Composing the contexts and the behaviors at runtime, may lead to 1. When the system loads, pour some small amount of cold water
unpredictable behavior. Thus, both context-oriented approaches re- three times.
quire reasoning and formal verification techniques for verifying their 2. When the system loads, pour some small amount of hot water
software, i.e., that it will function correctly in all contexts and combi- three times.
nations thereof. Since reasoning algorithms depend on having a formal Fig. 1 shows a b-program that fulfills these requirements. It consists of
specification of the system, an effort has been made in developing two b-threads, added at the program start-up. The first is responsible
formal semantics for COP (as elaborated in Section 11). For this reason, for fulfilling requirement #1, and the second fulfills requirement #2.
one of the major purposes of this paper is to generalize the translational The program’s structure is aligned with the system requirements,
semantics of [4,6], and define formal semantics for the COBP paradigm. with a single b-thread for each requirement, requesting, and blocking
As we demonstrate in Section 10.2, a COBP model that is based on events at each of their state (the 𝑅 and 𝐵 sets). Harel, Marron and
these semantics, allows for applying reasoning techniques on the entire Weiss [2] proposed a simple protocol for interweaving the b-threads
system (i.e., context, behavior, and execution mechanism) with no and executing the model, depicted in Fig. 2. B-threads repeatedly
further input needed, as opposed to some COP implementations that execute an internal logic and then synchronize with each other, by
allow for applying reasoning techniques only for part of the model, or submitting a synchronization statement to a central event arbiter. Once
require a manual translation of the code into a formal model. all b-threads have submitted their statements, the central event arbiter
Furthermore, one of the key advantages of scenario-based program- selects an event that was requested and was not blocked. B-threads that
ming (SBP) [7] in general, and of BP in particular, is the amenability either requested or waited for this event (specified on the edges in our
of the software artifacts to formal analysis and synthesis. As we elab- example) are resumed, while the rest of the b-threads remain paused
orate in Section 11, most of the tools for BP and SBP rely on the for the next cycle. Back to our example, the specification in Fig. 1 does
mathematically rigorous nature of the semantics in providing tools not dictate an order in which actions are performed since the b-threads
for running formal analysis and synthesis algorithms. The addition do not block events of each other. Thus, any of the following runs are
of context improves the modularity of the specification, thus may possible: Cold–Cold–Hot–Hot–Cold–Hot, or Cold–Hot–Cold–Hot–Cold–
contribute each of the methods, as we demonstrate in Section 10.2. Hot, etc. This contrast with, say, imperative programming languages
2
A. Elyasaf Information and Software Technology 133 (2021) 106504
Fig. 1. A b-program that pour ‘Cold’ and ‘Hot’ water three times each, that consists of a single b-thread for each requirement. The b-threads are executed simultaneously, requesting,
and blocking events at each of their state (the 𝑅 and 𝐵 sets).
Fig. 3. The Interleave b-thread — ensures that two actions of the same type cannot
be executed consecutively, by blocking an additional request of ‘Cold’ until the ‘Hot’
is performed, and vice-versa.
3
A. Elyasaf Information and Software Technology 133 (2021) 106504
paradigm with explicit idioms for defining and referencing the context.
As previously noted, this approach was first presented in [6], where
the Live Sequence Charts (LSC) language was extended with context
idioms, along with a methodology for developing context-aware sys-
tems using the extended language. In [4], a similar extension has
been made to BPjs — an environment for running behavioral programs
written in JavaScript [11]. In both cases, the semantics were defined by
translating the context idioms to the existing idioms of LSC and BPjs. In
this paper we generalize these extended languages by defining abstract
semantics (rather than translational semantics) and lay the foundations
for further research on formal analysis and synthesis.
In COBP, the system state incorporates the context of the system
that can be queried and updated. For example, in the context-aware
version of the hot–cold system, we may define the context to be the
entire building, including the rooms, the taps, the amount of hot/cold
units that need to be poured, and any additional required data. We will
also define queries on the context such as 𝑟𝑜𝑜𝑚 𝑤𝑖𝑡ℎ 𝑡𝑎𝑝𝑠 and kitchen,
that return a list of all rooms with taps and of all kitchens, respectively.
A b-thread in COBP is a context-aware b-thread, denoted as CBT, that
is bound to a certain query on the context. Whenever there is a new
result to the query, a new live copy of the CBT is spawned, with the
query result given as a local variable to the live copy. Thus, we refer to
this result as the seed of the live copy. Similar to a b-thread, a CBT also
specifies an aspect of the system behavior that is relevant to each new
seed that is generated, allowing to use its data, and to query and update
the context. Back to our extended hot–cold system, we can convert the
original three b-threads into CBTs and bind them to the appropriate
query (i.e., 𝑟𝑜𝑜𝑚 𝑤𝑖𝑡ℎ 𝑡𝑎𝑝𝑠). Thus, the queries represent both the context
Fig. 4. The life cycle of a context-aware b-program. Each context-aware b-thread (CBT)
of the requirements and the context of the CBTs. The complete example is bound to a query on the contextual data. Whenever a new answer exists for a query,
of the extended hot–cold system is given in Section 5. new live copies are spawned for the relevant CBTs. The live copies repeatedly execute
The life cycle of COBP contains the life cycle of BP with several an internal logic that may depend on the contextual data and then synchronize with
each other, by submitting a synchronization statement to a central event arbiter. Once
modifications, as depicted in Fig. 4:
all live copies have submitted their statements, the arbiter selects an event that was
requested and was not blocked. The event is passed to the Effect Function that may
• The live copies are the ones that are executed, and the CBTs
update the contextual data, depending on its specification. The (updated) contextual
spawn new live copies upon each new answer to their query. dataset is passed back to the CBTs, along with the selected event. All CBTs that either
• The internal logic of the live copies does not only depend on the requested or waited for this event are resumed, while the rest remain paused for the
last event, as in BP, but also on the context. next cycle.
4
A. Elyasaf Information and Software Technology 133 (2021) 106504
automatically add an implicit self-loop at each b-thread’s state for any 3.2.2. Execution semantics for a context-aware behavioral program
𝑒 ∉ 𝐸𝑖 (i.e., event that the b-thread is not aware of). Here, to simplify In BP, the b-threads are executed, however in COBP, CBTs are not
the definitions, we explicitly add to all of our examples an ‘‘otherwise’’ directly executed. Whenever an aspect of the context becomes active
self-loop to all b-thread states. (i.e., there is a new result to the query) — a new live copy (Definition 7)
of each of the CBTs that are bound to the context — is spawned,
3.2. COBP semantics
with the result of the query used as the seed of the live copy, passed
to it as a local variable. The execution semantics of a context-aware
We begin with the definition of a context-aware behavioral program
and continue with its execution semantics. behavioral program (Definition 8) define a new LTS, where its states
are composed of the active live copies and the state of the system
3.2.1. Context-aware behavioral program context. The transition function defines how events are selected, how
A context-aware behavioral program is composed of the context the context is affected by the selected event, and how live copies are
data structure with its management functions (Definitions 4 and 5), spawned based on changes of the system context.
together with a set of context-aware b-threads (Definition 6). A context-
aware b-thread (CBT) is a behavioral thread that is bound to a certain Definition 7 (A Live Copy of a Context-Aware Behavior Thread). A live
query on the context. Our definition for context is inspired by the copy (instance) of a context-aware behavior thread is a tuple ⟨cbt , 𝑠, 𝑐⟩
definition of [10] — information that can be used to characterize the where cbt = ⟨𝑆, →, init , 𝑅, 𝐵, query⟩ is a context-aware behavior thread,
situation of entities or processes in a system. 𝑠 ∈ 𝑆, and 𝑐 ∈ range(query). We refer to 𝑐 as the seed of the live
copy. To simplify the notations, we extend the definition of 𝑅 and
Definition 4 (Context, Queries, and Updates). CTX is a (possibly infi- 𝐵 (see Definition 2) to accept a live copy: 𝑅(⟨cbt , 𝑠, 𝑐⟩) = 𝑅(𝑠) and
nite) set of all possible contexts that the system is designed to be aware 𝐵(⟨cbt , 𝑠, 𝑐⟩) = 𝐵(𝑠).
of. At any given moment the system is in a context ctx ∈ CTX . The
management of the context is done by the sets QUERY and UPDATE,
Definition 8 (Runs of Context-Aware B-Threads). The runs of a set
where each member query ∈ QUERY is a function with dom(query) =
of context-aware b-threads over an event-set 𝐸, and a cbt-set CBT , is
CTX (and arbitrary range) and each member update ∈ UPDATE is a
function from CTX to CTX . Finally, ctx init denotes the initial context of defined as the runs of the LTS ⟨𝑆, 𝐸, →, 𝑖𝑛𝑖𝑡⟩, where:
the system. 1. 𝑆 = {⟨ctx, LC⟩ ∶ ctx ∈ CTX , LC is a set of live copies}
As said before, we envision a complex data structure representing 2. init = ⟨ctx 𝑖𝑛𝑖𝑡 , {⟨cbt , 𝑠, 𝑐⟩ ∶ cbt ∈ CBT , 𝑠 = init (cbt ),
the different aspects of the contextual data. The set CTX is a mathemat- 𝑐 ∈ query(cbt )(ctx init )}⟩
𝑒
ical representation of all possible states of this data structure. While it 3. → includes a transition ⟨ctx, LC⟩ ←→ ←← ⟨ctx ′ , LC ′ ⟩ if and only if
may read as if we only allow one context at a time for the whole system, ⋃ ⋀ ⋃
this context is actually a combination of many contextual aspects, as we (a) 𝑒 ∈ 𝑅(𝑙𝑐) 𝑒∉ 𝐵(lc)
lc∈LC lc∈LC
demonstrate in the examples below. ⏟⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏟ ⏟⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏟
In applications, we envision a language for querying and updating 𝑒 is requested 𝑒 is not blocked
the context state such as SQL or procedural code, as we will show. In (b) ctx ′ = effect (𝑒)(ctx)
this case, the result of a query can be, for example, a tuple in a table (c) LC ′ = LC ′run ∪ LC ′new where
or the number of people in a room. We therefore do not to restrict the
range of the 𝑞𝑢𝑒𝑟𝑦 function in our mathematical abstraction.
′ 𝑒, 𝑐𝑡𝑥′ , 𝑐
𝐿𝐶𝑟𝑢𝑛 = {⟨𝑐𝑏𝑡, 𝑠′ , 𝑐⟩ ∶ ⟨𝑐𝑏𝑡, 𝑠, 𝑐⟩ ∈ 𝐿𝐶 and 𝑠 ←←←←←←←←←←←←←←→ ← 𝑐𝑏𝑡 𝑠′ }
Definition 5 (The Effect Function). The connection between the events ⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟
that the system generates and the updates of the context are defined by running live copies (based on transition systems)
the function effect ∶ 𝐸 → UPDATE that maps events to context update
functions. and
{ }
Note that we separate the definition of the event from the definition ′ ⟨𝑐𝑏𝑡, 𝑖𝑛𝑖𝑡(𝑐𝑏𝑡), 𝑐⟩ ∶ 𝑐𝑏𝑡 ∈ 𝐶𝐵𝑇 ,
𝐿𝐶𝑛𝑒𝑤 = ′
of its effect to enforce a separation of concerns between behavioral 𝑐 ∈ 𝑞𝑢𝑒𝑟𝑦(𝑐𝑏𝑡)(𝑐𝑡𝑥 ) ⧵ 𝑞𝑢𝑒𝑟𝑦(𝑐𝑏𝑡)(𝑐𝑡𝑥)
⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟
aspects and data aspects. spawned live copies (based on new query results)
5
A. Elyasaf Information and Software Technology 133 (2021) 106504
Fig. 5. A CBT (in LSC and JavaScript) that specifies that a room’s light should be turned on/off based on its occupancy. Since the scenario is bound to the NonemptyRoom
query (defined in the DAL), once a room (any room) becomes occupied, a new live copy of the scenario is spawned with the room given as the local variable 𝑟.
• Context-context perspective: Represents the relations between called BPjs [11]. In both implementations, context idioms (i.e., CBT,
different aspects of the context, such as: temporal (e.g., contexts effect function, etc.) are translated into idioms of the underline BP
day and night cannot be active simultaneously) and structural implementation.
(e.g., the building context is composed of rooms, a kitchen instance Both the PlayGo and the BPjs tools allow for scenarios (or b-
is also a room instance, etc.). threads) to share data objects between them. Yet, to avoid a violation
of the BP semantics, it is ‘‘well known’’ among BP developers that
These perspectives (and others), may ease the development process
scenarios are prohibited to indirectly alter the behavior of each other
by improving the readability, explainability, and correctness of the
by modifying shared objects. The COBP semantics address this issue by
model.
formalizing the connection between the data objects and the behavioral
Another interesting feature of the semantics is the process of context
specification. According to Definition 8, the change to 𝑐𝑡𝑥 during a
activation, i.e., adding a result to a query and spawning live copies. We
transition (i.e., Definition 8 [3.b]) must occur before advancing the set
note that only UPDATE functions may change the context, and they are
of live copies (i.e., Definition 8 [3.c]). Our implementations use shared
triggered only by the EFFECT function, that is triggered only upon se-
objects for maintaining the system context (i.e., 𝑐𝑡𝑥), and synchronize
lecting an event. Thus, while live copies are advanced simultaneously,
the access using the BP execution mechanism that chooses an event and
only one UPDATE function can be triggered during a system transition.
advances the b-threads.
Changes to the context may yield new results for one or more QUERY
functions and upon such a change, all the CBTs that are bound to these
3.4.1. System design
queries will spawn live copies simultaneously. For example, once a new
To increase the modularity and the separation of concerns of spec-
room of type kitchen is added to the context (either dynamically by
ifications, we adapt the multilayered architectural pattern. We note that
using the effect function mechanism or statically by adding it to the
according to the COBP semantics, the CBTs are unaware of the context
initial context), all CBTs that are bound to the 𝑟𝑜𝑜𝑚 𝑤𝑖𝑡ℎ 𝑡𝑎𝑝𝑠 query
schema, the UPDATE set, how each 𝑞 ∈ QUERY is defined, and how
and kitchen query spawn live copies simultaneously. This behavior is
the effect function is defined. This information represents data-related
desired if there is no special requirement for an order. If there is
aspects of the system, rather than behavioral, and the interface between
such a requirement, then the BP and COBP paradigms encourage us
the CBTs and the context is defined by the queries’ names and the
to specify this additional requirement with an additional CBT (like the
contract of the effect function (i.e., the effect of each event). With
third, interleave b-thread of the hot–cold example). Adhering to the
respect to these insights, we define the layers as follows:
formal semantics, our JavaScript implementation delicately deals these
nuances and others (elaborated below). 1. The business-logic layer (BLL) consists of the behavioral specifi-
The implementation of the event arbitrer, that continuously selects cation — the set of CBTs that specify the behavior of the system.
a requested and not blocked event, can be either naïve, i.e., select one When developing this layer, the programmer must be aware
randomly, or advanced, e.g., by using priorities, heuristics, learning, of which information is accessible from the context (i.e., the
etc. Again, this behavior is desired assuming that there is no special queries’ names and the structure of their results) and how events
requirement for ordering the events. Of course, such a degree of par- affect the context.
allelism may cause unpredictable behavior, and while the specification 2. The data-access layer (DAL) abstracts the context-related deci-
may be aligned to the requirements, there may be problems with the sions for the BLL. The contextual data is stored in a structured
requirements themselves. In order to deal with this problem, different dataset (e.g., a relational database, classes, etc.) and managed
reasoning approaches have been proposed for BP, as we elaborate in using a data-access layer (DAL). The DAL is defined by a ‘‘query
Section 11. We further demonstrate the process of context activation and command repository’’ and an effect function. The ‘‘query and
in the examples below. command repository’’ manages the contextual data using a high-
level query language (e.g., SQL, methods, etc.). The context’s
3.4. Implementations ‘select’ queries allow for triggering a stored procedure whenever
a record is added or removed from its result (in analogy to
In this section, we describe two COBP implementations and discuss ‘‘database views’’), and the context’s ‘update’ commands update
their relation to the semantics. The first one is based on the PlayGo the data as required (by adding, deleting, and changing objects
implementation of LSC [13] and is fully described in [6]. The second and object relations). Based on the selected event, the effect
implementation [4] is based on a JavaScript implementation of BP, function uses the ‘update’ commands for changing the context.
6
A. Elyasaf Information and Software Technology 133 (2021) 106504
To simplify the notations of the examples below, we define the 5. Example: A context-aware hot–cold system
effect of all events as the identity function (i.e., they do not
change the context), unless explicitly specified otherwise. We now demonstrate how the extended hot–cold system can be
3. The application (or service) layer defines the interaction be- implemented using the abstract semantics. We begin with describing
tween the BLL and the environment (e.g., a GUI, network mes- the system requirements:
sages, etc.). This interaction is already defined in BP by using
a publish–subscribe mechanism, where external, environmental 1. A building has different room types, such as: kitchen, bathroom,
events are selected only at a super step, i.e., when there are bedroom, living room, hall, etc.
no more internal events to select. Similarly, the environment 2. Kitchens and bathrooms have a button and a hot and a cold taps.
may listen to internal events and act upon them (e.g., trigger 3. For each room with taps:
actuators). The complete mechanism is elaborated in [2].
(a) When the button is pressed, pour some small amount of
The multilayered architecture facilitates the separation of concerns cold water three times.
between the layers, and by binding b-threads to queries, the modularity (b) When the button is pressed, pour some small amount of
of the behavioral specification is increased. Fig. 5 depicts how CBTs are hot water three times.
specified using this design. In the examples and case studies below, we
follow this design and separate each implementation into three sections 4. For each kitchen — two pouring actions of the same type cannot
— Context Specification (for the DB schema), Data-Access Layer, and be executed consecutively.
Behavioral Specification.
We note that requirements 3 and 4 define the desired system behav-
3.4.2. Spawning an terminating live copies ior for each room-with-taps/kitchen (respectively). Requirements 1 and
PlayGo includes a mechanism for spawning live copies upon 2 define data constraints on the system or data aspects of the system,
changes to data objects, allowing us to use it for dynamically activating thus define the schema of the system context rather than its behavior.
and terminating CBTs’ live copies. BPjs does not have such mecha- We also note that the system context is static and does not change
nism, though it can be created by adding a b-thread that waits for throughout the lifetime of this system. Of course, this is not always true
contextual-data updates and then requests an event that contains a list as requirements may depend on dynamic changes to the context, as we
of new/ended results to the queries. This event is used for spawning demonstrate in Section 6. For example, a requirement may depend on
and terminating live copies, as elaborate next. personal preferences (e.g., whenever Joe uses the kitchen’s taps — pour
We implement CBT as a function that registers a regular b-thread only two units), room temperature (e.g., do not pour hot water when
(see Listing 1). The b-thread waits for new-results announcement and the room temperature is high), etc.
registers another b-thread for each result (for executing 𝑓 𝑢𝑛𝑐 in paral-
lel), with the new answer given as a parameter.
5.1. Implementation
bp.registerCBT = function(name, query, func) {
bp.registerBThread("cbt: " + name, function() { We define the possible events to be 𝐸 = {Push𝑖 , Hot 𝑖 , Cold 𝑖 ∶ 𝑖 ∈ N},
while(true) { where 𝑖 represents the 𝑖th room, Push𝑖 represents pushing the room’s
bp.sync({ waitFor: CTX.NewResults(query)})
button, and Hot 𝑖 ∕Cold 𝑖 represents pouring hot/cold (respectively) wa-
.data.forEach(c =>
bp.registerBThread( ter.
"Live copy: " + name + " " + c.id,
function() { func(c); }); ); Context specification
}}); } • RoomType = {kitchen, bathroom, living room, …} is a set of all room
types.
Listing 1: The implementation of a CBT in BPjs.
• The 𝑖th room in the building is represented by room𝑖 = ⟨𝑖, type𝑖 ⟩,
In some cases, a live-copy should terminate whenever its seed where 𝑖 ∈ N is the room number and type𝑖 ∈ RoomType represents
no longer answers its query. In Chess, for example, live copies that the type of the room.
handle a piece’s behavior are no longer relevant once the piece is • The set of all possible system contexts, CTX , is defined as the set of
captured. The implementations and semantics of BP and COBP allow all possible rooms — {room𝑖 ∶ 𝑖 ∈ N}.
for b-threads/live copies to terminate themselves. Thus, live copies
may listen to the aforementioned announcement event and terminate
Data-access layer
themselves. This behavior can be either explicitly specified for certain
As noted before, the behavioral requirements depend on two aspects
states, or it can be implicitly applied to all. While the latter may be
of the context — ‘room with taps’ and ‘kitchen’. Therefore, the DAL has
preferred when the ‘‘certain states’’ are all of them, caution is required
since live copy may need to release resources or do some actions before the following two queries:
terminating. • RoomWithTaps = {⟨𝑖, type𝑖 ⟩ ∶ 𝑖 ∈ N ∧ type𝑖 ∈
{𝑘𝑖𝑡𝑐ℎ𝑒𝑛, 𝑏𝑎𝑡ℎ𝑟𝑜𝑜𝑚}}.
4. Examples: Motivations and overview
• Kitchen = {⟨𝑖, type𝑖 ⟩ ∶ 𝑖 ∈ N ∧ type𝑖 = kitchen}.
To demonstrate how context-aware systems can be specified, ex- The queries’ names are used by the CBTs as an abstraction for the
ecuted, and verified, using the abstract semantics, we now present queries. Thus, future changes to the context specification (e.g., due to
two toy examples that are given here merely for understanding these additional requirements) will not affect the definitions of the CBTs.
concepts. For each example, we demonstrate its ‘‘execution’’ using the
Since the system context is static and does not change, the effect
formal semantics, showing how the context and the live copies change
function for all events is the identity function.
over time.
While here we implement the examples abstractly, they have a
JavaScript implementation as well, that can be downloaded and ex- Behavioral specification (CBTs)
ecuted from https://github.com/bThink-BGU/Papers-2020-COBP. Fol- We translate the b-threads of Section 2 to CBTs, binding the hot/-
lowed by these examples, we present two real-life systems developed cold b-threads to the RoomWithTaps query, and the interleave b-thread
using our JavaScript implementation (Sections 8 to 10). to the kitchen query:
7
A. Elyasaf Information and Software Technology 133 (2021) 106504
5.3. A short discussion 1. Any individual with fewer than two neighbors — dies — as if by
underpopulation.
Succinctness. In some cases, COBP specifications are more succinct 2. Any individual with two or three neighbors — lives on to the
than BP specifications. In this example, we had three CBTs only, while next generation.
8
A. Elyasaf Information and Software Technology 133 (2021) 106504
3. Any individual with more than three neighbors — dies — as if • reproduce(row, col)(⟨Pop, Tick⟩) = ⟨Pop ∪ {⟨row, col⟩}, Tick⟩, is the
by overpopulation. effect of the event reproduce(row, col), adding the reproduced
4. Any three individuals that are the only ones that surrounds an individual to the population.
unpopulated cell — reproduce an individual at that cell. • tick(⟨Pop, Tick⟩) = tock(⟨Pop, Tick⟩) = ⟨Pop, 1 − Tick⟩, are the effects
of the events tick and tock.
All rules are applied simultaneously to all of the individuals —
births and deaths occur simultaneously, at a discrete moment called
Behavioral specification (CBTs)
a tick. The rules are repeatedly applied to create further generations.
For each rule, we define a context-aware b-thread, called CBT 𝑖 as
We note that each requirement depends on a different aspect of the
the CBT for the 𝑖th rule, where 𝑄𝑖 is the definition of its query, and
context: for the first requirement — ‘‘individual with fewer than two
BT 𝑖 is the definition for its tuple ⟨𝑆, →, init , 𝑅, 𝐵⟩.
neighbours’’, for the second requirement — ‘‘individual with two or
three neighbours’’, and so on. CBT 1 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄1
𝐵𝑇1 =
6.1. Implementation
𝑅 = die(row,col) die(row,col) 𝑅=∅
start
We define the possible events as 𝐸 = {die(row,col), reproduce 𝐵 = {tick} 𝐵=∅
(row,col), tick, tock ∶ row, col ∈ N}, where the events die(row, col) and
reproduce(row,col) represent the death and reproduce (respectively) of
otherwise
an individual at the cell ⟨row,col⟩. Finally, to synchronize the creation
of live copies we used tick to represent the state of the system at the CBT 2 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄2
beginning moment of a generation, and tock to represent the rest of the
𝐵𝑇2 =
system states.
𝑅=∅
start
Context specification 𝐵=∅
• We define the set of all possible system contexts, CTX , to be
{⟨Pop, Tick⟩ ∶ Pop ⊆ {⟨row, col⟩ ∶ row, col ∈ N}, Tick ∈ {0, 1}}, CBT 3 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄3
where the population (represented by Pop) is a set of locations 𝐵𝑇3 =
of all living individuals, and Tick = 1 if and only if all of the die(row,col)
𝑅 = die(row,col) 𝑅=∅
individuals have finished processing their rules for the current start
𝐵 = {tick} 𝐵=∅
generation, and the rules-processing of the following generation
has not yet started.
otherwise
• The set of all cells that can be reached from the cell ⟨row,col⟩
in one step, is defined by the function ngb(row,col) = {⟨row + CBT 4 ∶ 𝑄𝑢𝑒𝑟𝑦 = 𝑄4
1, col⟩, ⟨row +1, col+1⟩, ⟨row, col+1⟩, ⟨row −1, col+1⟩, ⟨row −1, col⟩,
𝐵𝑇4 =
⟨row-1, col-1⟩, ⟨row, col − 1⟩, ⟨row + 1, col − 1⟩}.
otherwise
Data-access layer
As noted before, each requirement is bound to a different context. 𝑅 = reproduce(row,col)
start
Therefore, for each context we define a different query, labeling it by 𝐵 = {tick}
the requirement ID:
reproduce(row,col)
⎧⎧ ⎫
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∈ 𝑃 𝑜𝑝 𝑅=∅
𝑄 1 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1
⎪ 𝐵=∅
⎪⎩ ∧ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| < 2 ⎭
⎪∅ , otherwise
⎩ To synchronize the generation tick, we define:
⎧⎧ ⎫
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪ CBT 𝑡𝑖𝑐𝑘 𝑄𝑢𝑒𝑟𝑦 = 𝑄𝑡𝑖𝑐𝑘
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∈ 𝑃 𝑜𝑝
𝑄 2 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1
⎪
𝐵𝑇𝑡𝑖𝑐𝑘 =
⎪⎩ ∧ 2 ≤ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| ≤ 3 ⎭ tick
⎪∅ , otherwise
⎩
𝑅 = {𝑡𝑖𝑐𝑘} 𝑅 = {𝑡𝑜𝑐𝑘}
⎧⎧ ⎫ start
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪
𝐵=∅ 𝐵 = 𝐸 ⧵ {𝑡𝑜𝑐𝑘}
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∈ 𝑃 𝑜𝑝
𝑄 3 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1
⎪
⎪⎩ ∧ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| > 3 ⎭ tock
otherwise otherwise
⎪∅ , otherwise
⎩
⎧⎧ ⎫ 6.2. Execution demonstrations
⎪⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∶ ⎪
⎪ ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩ ∉ 𝑃 𝑜𝑝
𝑄 4 = ⎨⎨⎪
⎬, 𝑡𝑖𝑐𝑘 = 1
⎪ We now demonstrate the execution of the program with different
⎪⎩ ∧ |𝑛𝑔𝑏(𝑟𝑜𝑤, 𝑐𝑜𝑙) ∩ 𝑃 𝑜𝑝| = 3 ⎭ initial populations. We do that by presenting how the context and the
⎪∅ , otherwise
⎩ live copies change over the generations. For each generation 𝑖, we
present the set of the live copies at their initial state, denoted by LC𝑖 ,
The effect function is:
and the state of the context at the beginning of the generation, denoted
• die(row, col)(⟨Pop, Tick⟩) = ⟨Pop ⧵ {⟨row, col⟩}, Tick⟩, is the effect by 𝑐𝑡𝑥𝑖 . Given 𝑛𝑎𝑚𝑒 ∈ {1, 2, 3, 4, 𝑡𝑖𝑐𝑘}, we denote LC 𝑛𝑎𝑚𝑒,⟨𝑟𝑜𝑤,𝑐𝑜𝑙⟩ =
of the event die(row, col) that removes the individual from the ⟨CBT 𝑛𝑎𝑚𝑒 , 𝑄𝑛𝑎𝑚𝑒 , ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩⟩ as the live copy of CBT 𝑛𝑎𝑚𝑒 where the result
population. of 𝑄𝑛𝑎𝑚𝑒 (i.e., the seed — 𝑐), is ⟨𝑟𝑜𝑤, 𝑐𝑜𝑙⟩.
9
A. Elyasaf Information and Software Technology 133 (2021) 106504
7.1. Implementation
We note that rule A defines a new context-dependent requirement, To the effect function we add an effect for the step(row,col) event,
while B rules only refine the context of the original rules. that advances the neighbors to their next dance location:
10
A. Elyasaf Information and Software Technology 133 (2021) 106504
for each one of them. Thus, for simplification, we denote the indi-
viduals as block = {⟨5, 0⟩, ⟨5, 1⟩, ⟨6, 0⟩, ⟨6, 1⟩}, and their live copies as
LCblock = {LC 𝐵2,⟨5,0⟩ , LC 𝐵2,⟨5,1⟩ , LC 𝐵2,⟨6,0⟩ , LC 𝐵2,⟨6,1⟩ }.
Generation 0:
ctx 0 = ⟨{⟨0, 1⟩, ⟨2, 0⟩, ⟨2, 2⟩} ∪ block, 0⟩
LC0 = {CBT tick , LC 𝐴,⟨1,1⟩ } ∪ LCblock
Generation 1:
ctx 1 = ⟨{⟨0, 1⟩, ⟨1, 1⟩, ⟨2, 0⟩, ⟨2, 2⟩} ∪ block, 0⟩
LC1 = { CBT tick , LC 𝐵1,⟨0,1⟩ , LC 𝐵3,⟨1,0⟩ , 𝐿𝐶𝐵2,⟨1,1⟩ , LC 𝐵3,⟨1,2⟩ ,
LC 𝐵1,⟨2,0⟩ , LC 𝐵3,⟨2,1⟩ , LC 𝐵1,⟨2,2⟩ } ∪ LCblock
Generation 2:
𝑐𝑡𝑥2 = ⟨{⟨1, 0⟩, ⟨1, 1⟩, ⟨1, 2⟩, ⟨2, 1⟩} ∪ 𝑏𝑙𝑜𝑐𝑘, 0⟩
LC2 = {CBT 𝑡𝑖𝑐𝑘 , 𝐿𝐶𝐵3,⟨0,1⟩ , 𝐿𝐶𝐵1,⟨1,0⟩ , 𝐿𝐶𝐵2,⟨1,1⟩ ,
Fig. 7. The individuals (in gray) at the beginning of the first three generation of the 𝐿𝐶𝐵1,⟨1,2⟩ , 𝐿𝐶𝐵2,⟨2,1⟩ } ∪ LC𝑏𝑙𝑜𝑐𝑘
extended Game of Life example. For each cell/individual that one of the rules is valid
for — the rule number is stated. The block pattern is at the bottom of the grid, and 7.3. A short discussion
the mating-dance pattern is at the top of the grid at generation 0. The dancing takes
place during generation 0, and at the end of the dance, a new individual is spawned Our initial definition for requirement A did not require that the
at cell ⟨1, 1⟩.
three individuals will be lonely. When we implemented and run the
last example, we observed a bug — in some cases, during the mating
dance, the individuals have been duplicated and each copy stepped into
step(row,col)(⟨𝑃 𝑜𝑝, 𝑇 𝑖𝑐𝑘⟩) = ⟨(Pop ⧵ ngb(row,col)) ∪
⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟ a different cell. We added an assertion that checks this run property,
Remove old locations and because of the formal semantics of the COBP paradigm, we were
{next (row, col, 𝑖, 𝑗) ∶ ⟨𝑖, 𝑗⟩ ∈ ngb(row,col)) ∩ Pop}, Tick⟩ able to verify the existence of the bug. Moreover, we were able to
⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏞⏟ find an initial seed that causes the bug — when the three cells are
Add next locations
ordered in a vertical or a horizontal line, then they are neighbors of
where next (row, col, 𝑖, 𝑗) is a function that returns the consecutive cell two unpopulated cells (i.e., from the two sides of the line). In fact,
to ⟨𝑖, 𝑗⟩ in the mating dance circle. For example, next (row, col, row, we discovered that the bug was in the requirements which is why
col + 1) = ⟨row,col, row + 1, col + 1⟩, next (row, col, row + 1, col + 1) = we changed them to three lonely individuals. We provide a detailed
⟨row, col, row + 1, col⟩, and so forth. description of the verification process and related experiments that we
have conducted in Section 10.2.
Behavioral specification (CBTs)
8. Case studies: Motivation and overview
Since the behavior of the original CBTs did not change, only their
context, we only change the query names of the CBTs (i.e., 𝑄1 will now
We now turn to present two case studies of two different industrial
be 𝑄𝐵1 , 𝑄2 will now be 𝑄𝐵2 , etc.). We define the following additional
fields — robotics and the internet-of-things. In both case studies we
CBT for rule A:
developed the systems using our BPjs-based implementation, described
in Section 3.4.
CBT 𝐴 : 𝑄𝑢𝑒𝑟𝑦 = 𝑄𝐴
The purposes of these case studies are: to present an implementation
𝐵𝑇𝐴 =
of the paradigm and a syntax for the abstract semantics; to discuss addi-
otherwise otherwise
tional implementation details and design patterns; and to demonstrate
real-life use cases where the paradigm may excel other paradigms, both
𝑅 = {step(row,col)} step(row,col) 𝑅 = {step(row,col)} context oriented and not. To keep the focus of this paper, we only
start
𝐵 = {tick} 𝐵 = {tick} discuss the key differences between our implementation and possible
implementations in other paradigms and languages. Additional aspects
⋯ step(row,col) × 7 ⋯ are discussed in Section 11.
The contextual data is stored in a relational database (an in-memory
𝑅 = {step(row,col)} reproduce(row,col) 𝑅=∅ SQLite database2 ) and managed by a data-access layer (DAL) using
𝐵 = {tick} 𝐵=∅ the Hibernate ORM framework.3 In analogy to ‘‘database views’’, the
context’s ‘select’ queries allow for triggering a stored procedure when-
ever a record is added or removed from its result (i.e., announcing
otherwise
the changes via events and spawning live copies upon new records)
. The context’s ‘update’ commands update the data as required (by
adding, deleting, and changing objects and object relations). Query and
7.2. Execution demonstrations update commands are accessed by their IDs in the business-logic layer
(i.e., the behavioral specification defined by the CBTs), leaving the
context-related implementation decisions to the lower layer (i.e., the
Mating dance and still life. In this example, depicted in Fig. 7, we have
DAL and the DB).
two patterns. At the bottom of the grid, is the block pattern of the still
This implementation can be found at https://github.com/bThink-
life type. It is called ‘still life’ since it does not change over generations.
BGU/BPjs-Context and the following case studies can be found at https:
The second pattern is our new dancing pattern. We demonstrate the //github.com/bThink-BGU/Papers-2020-COBP.
run for three generations, presenting only the initial state of each
generation. The dance starts and completes during the first generation.
Since the individuals of the block pattern do not change over 2
SQlite –https://www.sqlite.org
3
generations, at each generation a new live copy of CBT 𝐵2 is generated Hibernate ORM — https://hibernate.org/orm.
11
A. Elyasaf Information and Software Technology 133 (2021) 106504
bool Turtlebot3Drive::controlLoop() {
switch(state){
case GET_TB3_DIRECTION:
if(distToObstacle[CENTER] > min_forward_dist){
if(distToObstacle[LEFT] < min_side_dist){
previous_position = position;
state = TB3_RIGHT_TURN;
}else if(distToObstacle[RIGHT] < min_side_dist){
previous_position = position;
state = TB3_LEFT_TURN;
}else { state = TB3_DRIVE_FORWARD; }
}
if(distToObstacle[CENTER] < min_forward_dist){
previous_position = position;
state = TB3_RIGHT_TURN;
} break;
case TB3_DRIVE_FORWARD:
Move(LINEAR_VELOCITY, 0.0);
state = GET_TB3_DIRECTION;
break;
Fig. 8. The TurtleBot3 world (credit: http://emanual.robotis.com). The Robot must not case TB3_RIGHT_TURN:
hit the walls while moving around. ...
12
A. Elyasaf Information and Software Technology 133 (2021) 106504
Table 2 bp.registerCBT("GoToPowerSocket",
The ‘‘query and command’’ repository for the ROS case study.
"LowBattery", function(r) {
Type Name Command bp.sync({ request: bp.Event("NewTarget",
Q Robot SELECT * FROM robot { pos: socket_pos }) });
Q ObstacleAhead SELECT * FROM robot });
WHERE oAhead < min_forward_dist
Q ObstacleLeft SELECT * FROM robot // The result of the Delivery query has two ↩
WHERE oLeft < min_side_dist properties
Q ObstacleRight SELECT * FROM robot
WHERE oRight < min_side_dist // of type Target - source and target.
U SetObstacles UPDATE robot SET bp.registerCBT("Deliver", "Delivery", function(d) {
oAhead=:a, oLeft=:l, oRight=:r bp.sync({ request: newTarget(d.source) });
bp.sync({ waitFor: CTX.Ended("Target", d.source) });
bp.sync({ request: newTarget(d.target) });
bp.registerCBT("Movement", "Robot", function(r) { bp.sync({ waitFor: CTX.Ended("Target", d.target) });
while(true) });
bp.sync({ request:[
move(0.3, 0), /* move forward */ bp.registerCBT("GoToTarget", "Target", function(t) {
move(0, -1.5), /* turn left */ while(true) {
move(0, 1.5) /* turn right */] }); // calculate the moves for reaching the target.
}); var path = calcPath(t.robot, t.pos);
if(path.length == 0) {
bp.registerCBT("Avoid obstacles: ahead", // The TargetReached command ends the context ↩
"ObstacleAhead", function(r) { by
bp.sync({ block: move(0.3, 0), // deleting t from table Target.
waitFor: CTX.Ended("ObstacleAhead", r) }); bp.sync({ request: targetReached(t) });
}); break;
} else
bp.registerCBT("Avoid obstacles: left", bp.sync({ block: allMovesExcept(path[0]),
"ObstacleLeft", function(r) { waitFor: path[0]] });
bp.sync({ block: move(0, -1.5), }
waitFor: CTX.Ended("ObstacleLeft", r) }); });
});
Listing 4: Additional CBTs for the two new requirements: ‘‘when
bp.registerCBT("Avoid obstacles: right", the battery is low, the robot must reach the nearest power socket for
"ObstacleRight", function(r) { recharging’’, or ‘‘if the robot has a package to deliver, it must first take
bp.sync({ block: move(0, 1.5), it from the source location and then take it to its destination’’.
waitFor: CTX.Ended("ObstacleRight", r) });
});
13
A. Elyasaf Information and Software Technology 133 (2021) 106504
schema — adding a batteryLevel attribute to the robot table and two new
tables, called Target and Delivery. In addition, there are changes to the
DAL — adding queries and command for retrieving and manipulating
the data of the new schema, as well as updating the effect function for
triggering the new UPDATE commands.
14
A. Elyasaf Information and Software Technology 133 (2021) 106504
bp.registerCBT("Light: On",
"NonemptyRoom", function(room) {
bp.sync({ request: on(room.light) });
});
bp.registerCBT("Light: Off",
"EmptyRoom", function(room) {
bp.sync({ request: off(room.light) });
});
bp.registerCBT("Air-conditioner: On",
"NonemptyOffice", function(office) {
bp.sync({ request: on(office.airConditioner) });
});
bp.registerCBT("Air-conditioner: Off",
Fig. 10. The context schema for the smart-building case study. Both physical and "EmptyOffice", function(office) {
logical entities are represented in the schema. bp.sync({ request: off(office.airConditioner) });
});
Table 3
The ‘‘query and command’’ repository for the smart building case study. bp.registerCBT("Emergency: Lights",
Type Name Command "Room", function(room) {
Q Room SELECT * FROM roomt while(true)
Q Office SELECT * FROM office bp.registerCBT("Emergency: Light " + room.id,
Q Emergency SELECT * FROM emergency "Emergency", function(e) {
Q EmptyRoom SELECT * FROM room bp.sync({ block: off(room.light),
WHERE isEmpty=1 waitFor: CTX.Ended("Emergency", e) });
Q NonemptyRoom SELECT * FROM room });
WHERE isEmpty=0 });
Q EmptyOffice SELECT * FROM office
WHERE isEmpty=1 bp.registerCBT("Mark room as nonempty",
Q NonemptyOffice SELECT * FROM office
WHERE isEmpty=0 "EmptyRoom", function(room) {
Q NoMovement SELECT * FROM room bp.sync({ waitFor: motionDetected(room) });
WHERE timeFrom(lastMovement) bp.sync({ request: roomIsNonempty(room) });
> :seconds });
U RoomIsNonempty UPDATE room SET isEmpty=0 bp.registerCBT("Mark room as empty", "NoMovement",
WHERE id=:rId {seconds: 3*60}, function(room) {
U RoomIsEmpty UPDATE room SET isEmpty=1 bp.sync({ request: roomIsEmpty(room),
WHERE id=:rId waitFor: motionDetected(room) });
U UpdateMovement UPDATE room
SET lastMovement=date('now') });
WHERE id=:rId
Listing 5: The behavioral specification of the smart-building
case study. The last two CBTs specify when to mark a room as
empty/nonempty. The additional parameter in the last CBT provides
notation for devising the schema, though other representations may be the seconds parameter to the NoMovement query (see Section 10.2).
used as well.
Once the schema is designed, we populate it with the initial pre-
defined data. That is, adding buildings and rooms to the database and
associating devices to specific rooms, and rooms to specific buildings. Behavioral: R11) If a worker enters a room, announce her name in
the room’s speaker; R12) During an emergency, turn on all lights.
Data access layer To cope with these requirements, we can add object types that
QUERY and UPDATE are defined in Table 3. The effect of the represent new aspects of the context. To the schema, we add a Smart
motionDetected event updates the timestamp of the last movement by
Speaker data type (similarly to the other devices) (R9) and a Worker
calling UpdateMovement . The effect of roomIsEmpty and roomIsNonempty
data type, both associated with Room (see Fig. 11). To the DAL we
trigger a call to the corresponding update commands — RoomIsEmpty
and RoomIsNonempty. add commands for marking and un-marking that a worker has entered
a room (R11) (similar to the room occupancy update commands). We
Behavioral specification (CBTs) also modify the effect function for triggering them. For getting a view
The behavioral specification is given in Listing 5. The first two CBTs, of all workers that are inside a room (R10), we add the WorkerInARoom
Light ∶ On∕Off , are bound to queries EmptyRoom and NonemptyRoom query, defined as SELECT * FROM worker WHERE id IS NOT NULL. Fi-
(respectively), handling R5. The next two CBTs, nally, we add the following CBTs: two for detecting entrance/leaving of
Airconditioner ∶ On∕Off , are bound to the EmptyOffice and workers (and triggering the appropriate marking/unmarking command
NonemptyOffice queries (respectively), handling R6. R7 is handled in the using the effect function) (R10, R11); one for turning the lights on
Emergency ∶ Lights CBT, and finally, the last two CBTs, during an emergency (R12) (similar to the Emergency CBT in Listing
Mark room as empty/nonempty handle R8.
5); and one for announcing the worker name (demonstrated in Listing
As development evolves, new requirements may arise. In our exam-
6) (R11).
ple these include:
Physical: R9) Smart speakers are installed in all rooms (in addition Thanks to the incrementality feature of BP, no changes to the previ-
to R2 devices); R10) Workers can be identified in the system (e.g., by ous specification are needed, we only added elements to the schema, to
a RF tag or a Bluetooth device), while visitors cannot. the query and command repository, and to the behavioral specification.
15
A. Elyasaf Information and Software Technology 133 (2021) 106504
Table 4
Experimenting with a non-context-aware verification algorithm on the smart-building example. The com-
bination of two rooms and two movements resulted with ‘‘out of memory’’ exception, even though the
sequence of events of each room is not influenced by the events of other rooms. A context-aware algorithm
could have verify the behavior of the only one room.
Setup Results
# of # of # of # of Time (s)
rooms moves simulated states
minutes
1 1 1 10 61 3.5
2 1 2 10 178 7.3
3 1 1 20 236 8.1
4 1 2 20 1496 42
5 2 1 10 869 29
6 2 2 10 Out of memory
7 2 1 20 70,001 177.4
16
A. Elyasaf Information and Software Technology 133 (2021) 106504
pattern. Finally, the idioms and their formal semantics allow for im- Table 5
A comparison between the performance of BPjs verification tool and NASA’s JavaP-
proving verification algorithms, as we demonstrated in Section 10.2
athFinder (JPF). The formal semantics allow BPjs to count as states only synchronization
and discuss below. points, whereas JPF must look at all thread interleaving options.
Tool B-Threads States Time (ms)
11.1. Context-awareness in scenario-based programming JPF 3 438,568 511,000
JPF 6 out of memory
BPjs 25 27 2205
To the best of our knowledge, besides of the work of [4,6] that we BPjs 10,000 402 640,358
generalize here, there is no prior work on context for BP. Yet, there are
two, somewhat related works that we discuss here.
The work on BP began with scenario-based programming (SBP), a
way to create executable specifications of reactive systems, introduced 2. Bar-Sinai, Weiss and Shmuel [11] presented a verification tool
through the language of live sequence charts (LSC) and its Play-Engine for BPjs that we used for the examples of this paper (elaborated
implementation [7,21]. As explained in Section 3.4, while BP allows in Section 10.2). The tool avoids the translation by directly
traversing the state space of the program, as in NASA’s Java-
for behavioral specification only, the LSC language includes idioms for
PathFinder (JPF) [32]. The method only allows for explicit
both behavioral and data specifications. The lifelines represent objects,
model-checking. The advantage, however, is that it allows for
possibly with data properties, allowing to share data among scenarios.
model-checking any code because it uses the JavaScript inter-
A lifeline can either refer to a concrete object, or define a binding
preter in its state-space traversal. Bar-Sinai [33] compared the
expression that is evaluated at runtime, meaning that a live-copy of
performance of this method to the performance of JPF (also
the chart is instantiated whenever there is a new answer to the binding
summarized in Table 5). To compare, they verified with both
expression. Indeed here and in [6], we utilize this trait for defining
tools different programs with various number of b-threads. JPF
the context idioms as syntactic sugars of dynamic binding. Moreover,
verified the program as a standard, non-BP program, there-
the Play-Engine specification splits each chart to a prechart and a main
fore looking at all thread interleaving options, while BPjs only
chart, where the prechart describes events (and conditions), that when
counted synchronization points as states. Not surprisingly, the
they occur (or are satisfied), the system will attempt to execute the
JPF verification process was much longer, taking 85 s to verify
specification in the main chart. Thus, binding a chart to a context can
a program containing three b-threads, visiting 438,568 states.
be achieved by defining the context query inside the prechart area. While trying to verify a program with six b-threads, JPF ran out
While these two traits (dynamic binding and prechart) allow for sharing of memory after 8:31 min. BPjs was able to verify a program
data among scenarios, as previously noted, explicit context idioms have containing 10,000 b-threads in 10:67 min.
several advantages. 3. [14] used a hybrid approach that assumes that state explosion
Atir et al. [22] proposed to use the dynamic binding trait for ex- only comes from the b-threads composition, rather than their
tending LSC with idioms for specifying hierarchies between scenarios. individual size. Given that, the space of each b-thread can be
Using hierarchies, they were able to abstract parts of the behaviors to translated to a model, used by a model-checker for analyzing the
different charts and activate them from several places. Atir et al. did composition of the b-threads. This method allows for a robust
not refer to context specification, however in some cases, context can verification framework without manually creating a translator,
be viewed (and implemented) as hierarchy. The COBP paradigm and though it only applies to systems with small b-threads (in terms
the semantics we define here, extends this idea to other context types. of number of states).
4. Maoz and Ringert [34] used a tool for direct specification of
11.2. Synthesis and reasoning models using SMV-like languages. They presented a case study
of developing a software controller for a forklift robot using
GR(1) [30] synthesis tools. Their main observation is that exten-
A recent literature review [23], argued that the industry is cur-
sions of the specification language with auxiliary variables and
rently concerned with the quality assurance of context-aware software
higher-level specification patterns support writing specifications
systems (i.e., that the software will not fail upon context changes),
with better confidence. On the other hand, with growing specifi-
while failing to cover aspects of functional assurance. The problem with
cation size, understanding reasons for synthesized behavior and
covering all the possible variations of context during testing execution
for unrealizability turned out to be a major challenge.
is not feasible. This is where formal methods and reasoning techniques
may excel. In Section 10.2, we demonstrated how the addition of context to
As we explained in Section 1, COP and COBP share the need for the model improves its modularity, and how it can be used to improve
applying reasoning techniques on their model, in order to cope with the verification algorithm of [11]. Yet, such improvements, require an
unpredictable behavior that may occur due to the dynamic adaptation adaptation of each of the above approaches since all are designed under
to context conditions. In fact, the BP paradigm faces this problem as the assumption that the only protocol between b-threads is requests,
well, due to the distributed nature of the paradigm, resulting in many blocking, and triggering of events. In practice, when people use BP with
tailored reasoning techniques that we now elaborate on. shared data they know that the model-checking technologies will not
Starting from the pioneering work of Harel, Kugler and Pnueli [24], be applicable to their models. The formal COBP semantics presented
most of the synthesis and analysis tools for BP and SBP rely on the here enable the change of this, by adding mechanisms to encode the
mathematically rigorous nature of the semantics in providing tools for state of the context data so that the model-checker is aware of the new
running formal analysis and synthesis algorithms [11,14,25–30]. There form of inter-thread communication.
are different approaches for verifying behavioral code:
11.3. Context-oriented programming
1. Harel et al. [24] translated the model to SMV [31] and analyzed
the equivalent SMV model. The method allows for symbolic BP and COBP are language-independent paradigms, with abstract
model-checking that relies on a robust verification framework, semantics that are used and implemented by all BP languages. The
though it requires a translation that may not be either sound or evolution of COP was the other way around, where the first languages
complete. have been proposed before the semantics. Some COP implementations
17
A. Elyasaf Information and Software Technology 133 (2021) 106504
do not have formal semantics and require the translation of the ac- • Comparing COBP and COP. Both COBP and COP allow for context-
tual code to some formal language, for applying reasoning techniques aware programming, though they are fundamentally different
(see Section 11.3.1). Semantics have also been proposed for specific from each other. Some of the issues that were presented here
COP languages (see Section 11.3.2). Finally, some COP implementa- from the perspective of COBP, have been addressed and discussed
tions allow for developing the system in a modular manner (see Sec- by others from the perspective of COP. An in-depth comparison
tion 11.3.3), where part of the system (for example, the layer-activation between the two paradigms is needed for comprehending the
constraints) is formally specified, and the rest is defined using the differences between them.
underlying programming-language constructs (e.g., Java, Python, etc.). • Evaluating methodology aspects. We present several approaches
All the different COP languages and semantics elaborate below do for specifying COBP programs. The different examples demon-
not provide a formal semantics for the complete program (i.e., the busi- strated good and bad practices, discussing their advantages and
ness logic and its relation to the context). Thus, reasoning techniques disadvantages. Yet, these practices impact both qualitative and
can be applied only to the formally-specified parts, as opposed to COBP, quantitative aspects of the specifications, raising the need for a
where the model can be both executed and reasoned. user study that will evaluate these aspects.
18
A. Elyasaf Information and Software Technology 133 (2021) 106504
[17] Gal A. Kaminka, Mor Vered, Noa Agmon, Plan recognition in continuous [29] Joel Greenyer, Daniel Gritzner, Timo Gutahr, Florian König, Nils Glade, Assaf
domains, in: Sheila A. McIlraith, Kilian Q. Weinberger (Eds.), Proceedings of the Marron, Guy Katz, Scenariotools – A tool suite for the scenario-based modeling
Thirty-Second AAAI Conference on Artificial Intelligence, (AAAI-18), the 30th and analysis of reactive systems, Sci. Comput. Programm. (2017).
Innovative Applications of Artificial Intelligence (IAAI-18), and the 8th AAAI [30] Nir Piterman, Amir Pnueli, Yaniv Sa’ar, Synthesis of reactive(1) designs, in:
Symposium on Educational Advances in Artificial Intelligence, EAAI-18, New E. Allen Emerson, Kedar S. Namjoshi (Eds.), Verification, Model Checking, and
Orleans, Louisiana, USA, February 2–7, 2018, AAAI Press, 2018, pp. 6202–6210. Abstract Interpretation, Springer Berlin Heidelberg, Berlin, Heidelberg, 2006, pp.
[18] Michele Colledanchise, Petter Ögren, Behavior trees in robotics and AI: An 364–380.
introduction, 2017, CoRR, abs/1709.00084. [31] Kenneth L. McMillan, The SMV systems, 1993, pp. 61–85.
[19] Nicolás Cardozo, Sebastián González, Kim Mens, Ragnhild Van Der Straeten, [32] Gary Lindstrom, Peter C. Mehlitz, Willem Visser, Model checking real time java
Jorge Vallejos, Theo D’Hondt, Semantics for consistent activation in using java pathfinder, in: Doron A. Peled, Yih-Kuen Tsay (Eds.), Automated
context-oriented systems, Inf. Softw. Technol. 58 (2015) 71–94. Technology for Verification and Analysis, Third International Symposium, ATVA
[20] David Harel, Statecharts: A visual formalism for complex systems, Sci. Comput. 2005, Taipei, Taiwan, October 4-7, 2005, Proceedings, in: Lecture Notes in
Programm. 8 (3) (1987) 231–274. Computer Science, vol. 3707, Springer, 2005, pp. 444–456.
[21] David Harel, Rami Marelly, Come, Let’s Play: Scenario-Based Programming Using [33] Michael Bar-Sinai, Extending Behavioral Programming for Model-Driven
LSCs and the Play-Engine, Springer Science & Business Media, 2003. Engineering (Ph.D. thesis), Ben-Gurion University of the Negev, Israel, 2020.
[22] Yoram Atir, David Harel, Asaf Kleinbort, Shahar Maoz, Object composition in [34] Shahar Maoz, Jan Oliver Ringert, Synthesizing a lego forklift controller in GR(1):
scenario-based programming, in: Proceedings of the Theory and Practice of A Case Study, in: Pavol Cerný and Viktor Kuncak and Parthasarathy Madhusudan
Software, 11th International Conference on Fundamental Approaches To Software (Eds.), Proceedings Fourth Workshop on Synthesis, SYNT 2015, San Francisco,
Engineering, in: FASE’08/ETAPS’08, Springer-Verlag, Berlin, Heidelberg, 2008, CA, USA, 18th July 2015, in: EPTCS, vol. 202, 2015, pp. 58–72.
pp. 301–316. [35] Hans Schippers, Tim Molderez, Dirk Janssens, A Graph-based operational seman-
[23] Santiago Matalonga, Felyppe Rodrigues, Guilherme Horta Travassos, Charac- tics for context-oriented programming, in: Proceedings of the 2Nd International
terizing testing methods for context-aware software systems: Results from a Workshop on Context-Oriented Programming, 2010, pp. 1–6.
quasi-systematic literature review, J. Syst. Softw. 131 (2017) 1–21. [36] Pascal Costanza, Theo D’Hondt, Feature descriptions for context-oriented pro-
[24] David Harel, Hillel Kugler, Rami Marelly, Amir Pnueli, Smart play-out of gramming, in: Steffen Thiel, Klaus Pohl (Eds.), Software Product Lines, 12th
behavioral requirements, in: Mark Aagaard, John W. O’Leary (Eds.), Formal International Conference, SPLC 2008, Limerick, Ireland, September 8-12, 2008,
Methods in Computer-Aided Design, 4th International Conference, FMCAD 2002, Proceedings. Second Volume, Workshops, Lero Int. Science Centre, University of
Portland, OR, USA, November 6-8, 2002, Proceedings, in: Lecture Notes in Limerick, Ireland, 2008, pp. 9–14.
Computer Science, vol. 2517, Springer, 2002, pp. 378–398. [37] Tetsuo Kamina, Tomoyuki Aotani, Hidehiko Masuhara, EventCJ: A context-
[25] David Harel, Itai Segall, Planned and traversable play-out: A flexible method oriented programming language with declarative event-based context transition,
for executing scenario-based programs, in: Proceedings of the 13th International in: Paulo Borba, Shigeru Chiba (Eds.), Proceedings of the 10th International
Conference on Tools and Algorithms for the Construction and Analysis of Conference on Aspect-Oriented Software Development, AOSD 2011, Porto de
Systems, in: TACAS’07, Springer-Verlag, Berlin, Heidelberg, 2007, pp. 485–499. Galinhas, Brazil, March 21–25, 2011, ACM, 2011, pp. 253–264.
[26] David Harel, Hillel Kugler, Amir Pnueli, Synthesis revisited: Generating statechart [38] Tomoyuki Aotani, Tetsuo Kamina, Hidehiko Masuhara, Featherweight Eventcj: A
models from scenario-based requirements, in: Hans-Jörg Kreowski, Ugo Mon- core calculus for a context-oriented language with event-based per-instance layer
tanari, Fernando Orejas, Grzegorz Rozenberg, Gabriele Taentzer (Eds.), Formal transition, in: Proceedings of the 3rd International Workshop on Context-Oriented
Methods in Software and Systems Modeling, Essays Dedicated To Hartmut Ehrig, Programming, 2011, pp. 1–7.
on the Occasion of His 60th Birthday, in: Lecture Notes in Computer Science, [39] Sebastián González, Programming in Ambience: Gearing up for Dynamic
vol. 3393, Springer, 2005, pp. 309–324. Adaptation to Context (Ph.D. thesis), UCL-Université Catholique de Louvain,
[27] David Harel, Hillel Kugler, Shahar Maoz, Itai Segall, Accelerating smart play-out, 2008.
in: Jan van Leeuwen, Anca Muscholl, David Peleg, Jaroslav Pokorný, Bernhard [40] Aotani Tomoyuki, Gary T. Leavens, Towards modular reasoning for context-
Rumpe (Eds.), SOFSEM 2010: Theory and Practice of Computer Science, 36th oriented programs, in: Proceedings of the 18th Workshop on Formal Techniques
Conference on Current Trends in Theory and Practice of Computer Science, for Java-Like Programs, FTfJP’16, Association for Computing Machinery, New
Spindleruv MlÝN, Czech Republic, January 23-29, 2010. Proceedings, in: Lecture York, NY, USA, 2016, pp. 1–7.
Notes in Computer Science, vol. 5901, Springer, 2010, pp. 477–488.
[28] David Harel, Robby Lampert, Assaf Marron, Gera Weiss, Model-checking behav-
ioral programs, in: 2011 Proceedings of the Ninth ACM International Conference
on Embedded Software, EMSOFT, 2011, pp. 279–288.
19